repo
stringlengths
2
99
file
stringlengths
13
225
code
stringlengths
0
18.3M
file_length
int64
0
18.3M
avg_line_length
float64
0
1.36M
max_line_length
int64
0
4.26M
extension_type
stringclasses
1 value
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/sync/test_optimistic.py
from eth2spec.test.context import ( spec_state_test, with_bellatrix_and_later, ) from eth2spec.test.helpers.attestations import ( state_transition_with_full_block, ) from eth2spec.test.helpers.block import ( build_empty_block_for_next_slot, ) from eth2spec.test.helpers.execution_payload import ( compute_el_block_hash, ) from eth2spec.test.helpers.fork_choice import ( get_genesis_forkchoice_store_and_block, on_tick_and_append_step, ) from eth2spec.test.helpers.optimistic_sync import ( PayloadStatusV1, PayloadStatusV1Status, MegaStore, add_optimistic_block, get_optimistic_store, ) from eth2spec.test.helpers.state import ( next_epoch, state_transition_and_sign_block, ) @with_bellatrix_and_later @spec_state_test def test_from_syncing_to_invalid(spec, state): test_steps = [] # Initialization fc_store, anchor_block = get_genesis_forkchoice_store_and_block(spec, state) op_store = get_optimistic_store(spec, state, anchor_block) mega_store = MegaStore(spec, fc_store, op_store) block_hashes = {} yield 'anchor_state', state yield 'anchor_block', anchor_block next_epoch(spec, state) current_time = ( (spec.SAFE_SLOTS_TO_IMPORT_OPTIMISTICALLY * 10 + state.slot) * spec.config.SECONDS_PER_SLOT + fc_store.genesis_time ) on_tick_and_append_step(spec, fc_store, current_time, test_steps) # Block 0 block_0 = build_empty_block_for_next_slot(spec, state) block_hashes['block_0'] = block_0.body.execution_payload.block_hash signed_block = state_transition_and_sign_block(spec, state, block_0) yield from add_optimistic_block(spec, mega_store, signed_block, test_steps, status=PayloadStatusV1Status.VALID) assert spec.get_head(mega_store.fc_store) == mega_store.opt_store.head_block_root state_0 = state.copy() # Create VALID chain `a` signed_blocks_a = [] for i in range(3): block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = ( block_hashes[f'chain_a_{i - 1}'] if i != 0 else block_hashes['block_0'] ) block.body.execution_payload.extra_data = spec.hash(bytes(f'chain_a_{i}', 'UTF-8')) block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) block_hashes[f'chain_a_{i}'] = block.body.execution_payload.block_hash signed_block = state_transition_and_sign_block(spec, state, block) yield from add_optimistic_block(spec, mega_store, signed_block, test_steps, status=PayloadStatusV1Status.VALID) assert spec.get_head(mega_store.fc_store) == mega_store.opt_store.head_block_root signed_blocks_a.append(signed_block.copy()) # Create SYNCING chain `b` signed_blocks_b = [] state = state_0.copy() for i in range(3): block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = ( block_hashes[f'chain_b_{i - 1}'] if i != 0 else block_hashes['block_0'] ) block.body.execution_payload.extra_data = spec.hash(bytes(f'chain_b_{i}', 'UTF-8')) block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) block_hashes[f'chain_b_{i}'] = block.body.execution_payload.block_hash signed_block = state_transition_with_full_block(spec, state, True, True, block=block) signed_blocks_b.append(signed_block.copy()) yield from add_optimistic_block(spec, mega_store, signed_block, test_steps, status=PayloadStatusV1Status.SYNCING) assert spec.get_head(mega_store.fc_store) == mega_store.opt_store.head_block_root # Now add block 4 to chain `b` with INVALID block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = signed_blocks_b[-1].message.body.execution_payload.block_hash block.body.execution_payload.extra_data = spec.hash(bytes(f'chain_b_{i}', 'UTF-8')) block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) block_hashes['chain_b_3'] = block.body.execution_payload.block_hash # Ensure that no duplicate block hashes assert len(block_hashes) == len(set(block_hashes.values())) signed_block = state_transition_and_sign_block(spec, state, block) payload_status = PayloadStatusV1( status=PayloadStatusV1Status.INVALID, latest_valid_hash=block_0.body.execution_payload.block_hash, validation_error="invalid", ) yield from add_optimistic_block(spec, mega_store, signed_block, test_steps, payload_status=payload_status) assert mega_store.opt_store.head_block_root == signed_blocks_a[-1].message.hash_tree_root() yield 'steps', test_steps
4,887
41.504348
119
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/sync/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/genesis/test_initialization.py
from eth2spec.test.context import ( BELLATRIX, single_phase, spec_test, with_presets, with_phases, with_bellatrix_and_later, ) from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.helpers.deposits import ( prepare_full_genesis_deposits, ) from eth2spec.test.helpers.genesis import ( get_sample_genesis_execution_payload_header, ) def eth1_init_data(eth1_block_hash, eth1_timestamp): yield 'eth1', { 'eth1_block_hash': '0x' + eth1_block_hash.hex(), 'eth1_timestamp': int(eth1_timestamp), } @with_phases([BELLATRIX]) @spec_test @single_phase @with_presets([MINIMAL], reason="too slow") def test_initialize_pre_transition_no_param(spec): deposit_count = spec.config.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT deposits, deposit_root, _ = prepare_full_genesis_deposits( spec, spec.MAX_EFFECTIVE_BALANCE, deposit_count, signed=True, ) eth1_block_hash = b'\x12' * 32 eth1_timestamp = spec.config.MIN_GENESIS_TIME yield from eth1_init_data(eth1_block_hash, eth1_timestamp) yield 'deposits', deposits # initialize beacon_state *without* an execution_payload_header yield 'execution_payload_header', 'meta', False state = spec.initialize_beacon_state_from_eth1(eth1_block_hash, eth1_timestamp, deposits) assert not spec.is_merge_transition_complete(state) yield 'state', state @with_bellatrix_and_later @spec_test @single_phase @with_presets([MINIMAL], reason="too slow") def test_initialize_pre_transition_empty_payload(spec): deposit_count = spec.config.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT deposits, deposit_root, _ = prepare_full_genesis_deposits( spec, spec.MAX_EFFECTIVE_BALANCE, deposit_count, signed=True, ) eth1_block_hash = b'\x12' * 32 eth1_timestamp = spec.config.MIN_GENESIS_TIME yield from eth1_init_data(eth1_block_hash, eth1_timestamp) yield 'deposits', deposits # initialize beacon_state *with* an *empty* execution_payload_header yield 'execution_payload_header', 'meta', True execution_payload_header = spec.ExecutionPayloadHeader() state = spec.initialize_beacon_state_from_eth1( eth1_block_hash, eth1_timestamp, deposits, execution_payload_header=execution_payload_header, ) assert not spec.is_merge_transition_complete(state) yield 'execution_payload_header', execution_payload_header yield 'state', state @with_bellatrix_and_later @spec_test @single_phase @with_presets([MINIMAL], reason="too slow") def test_initialize_post_transition(spec): deposit_count = spec.config.MIN_GENESIS_ACTIVE_VALIDATOR_COUNT deposits, deposit_root, _ = prepare_full_genesis_deposits( spec, spec.MAX_EFFECTIVE_BALANCE, deposit_count, signed=True, ) eth1_block_hash = b'\x12' * 32 eth1_timestamp = spec.config.MIN_GENESIS_TIME yield from eth1_init_data(eth1_block_hash, eth1_timestamp) yield 'deposits', deposits # initialize beacon_state *with* an execution_payload_header yield 'execution_payload_header', 'meta', True genesis_execution_payload_header = get_sample_genesis_execution_payload_header(spec) state = spec.initialize_beacon_state_from_eth1( eth1_block_hash, eth1_timestamp, deposits, execution_payload_header=genesis_execution_payload_header, ) yield 'execution_payload_header', genesis_execution_payload_header assert spec.is_merge_transition_complete(state) yield 'state', state
3,603
28.300813
93
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/genesis/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/unittests/test_is_valid_terminal_pow_block.py
from eth2spec.utils.ssz.ssz_typing import uint256 from eth2spec.test.helpers.pow_block import ( prepare_random_pow_block, ) from eth2spec.test.context import ( spec_state_test, with_bellatrix_and_later, ) @with_bellatrix_and_later @spec_state_test def test_is_valid_terminal_pow_block_success_valid(spec, state): parent_block = prepare_random_pow_block(spec) parent_block.total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) block = prepare_random_pow_block(spec) block.parent_hash = parent_block.block_hash block.total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY assert spec.is_valid_terminal_pow_block(block, parent_block) @with_bellatrix_and_later @spec_state_test def test_is_valid_terminal_pow_block_fail_before_terminal(spec, state): parent_block = prepare_random_pow_block(spec) parent_block.total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(2) block = prepare_random_pow_block(spec) block.parent_hash = parent_block.block_hash block.total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) assert not spec.is_valid_terminal_pow_block(block, parent_block) @with_bellatrix_and_later @spec_state_test def test_is_valid_terminal_pow_block_fail_just_after_terminal(spec, state): parent_block = prepare_random_pow_block(spec) parent_block.total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY block = prepare_random_pow_block(spec) block.parent_hash = parent_block.block_hash block.total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY + uint256(1) assert not spec.is_valid_terminal_pow_block(block, parent_block)
1,669
36.111111
86
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/unittests/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/unittests/test_transition.py
from eth2spec.test.helpers.execution_payload import ( build_empty_execution_payload, build_state_with_incomplete_transition, build_state_with_complete_transition, ) from eth2spec.test.context import ( spec_state_test, with_bellatrix_and_later ) @with_bellatrix_and_later @spec_state_test def test_fail_merge_complete(spec, state): state = build_state_with_incomplete_transition(spec, state) assert not spec.is_merge_transition_complete(state) @with_bellatrix_and_later @spec_state_test def test_success_merge_complete(spec, state): state = build_state_with_complete_transition(spec, state) assert spec.is_merge_transition_complete(state) # with_complete_transition', 'with_execution_payload', 'is_merge_transition_block', 'is_execution_enabled' expected_results = [ (True, True, False, True), (True, False, False, True), (False, True, True, True), (False, False, False, False) ] @with_bellatrix_and_later @spec_state_test def test_is_merge_block_and_is_execution_enabled(spec, state): for result in expected_results: ( with_complete_transition, with_execution_payload, is_merge_transition_block, is_execution_enabled ) = result if with_complete_transition: state = build_state_with_complete_transition(spec, state) else: state = build_state_with_incomplete_transition(spec, state) body = spec.BeaconBlockBody() if with_execution_payload: body.execution_payload = build_empty_execution_payload(spec, state) assert spec.is_merge_transition_block(state, body) == is_merge_transition_block assert spec.is_execution_enabled(state, body) == is_execution_enabled
1,770
30.625
106
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/unittests/test_validate_merge_block.py
from typing import Optional from eth2spec.utils.ssz.ssz_typing import uint256, Bytes32 from eth2spec.test.helpers.block import ( build_empty_block_for_next_slot, ) from eth2spec.test.helpers.execution_payload import ( compute_el_block_hash, ) from eth2spec.test.helpers.pow_block import ( prepare_random_pow_chain, ) from eth2spec.test.context import ( spec_state_test, with_bellatrix_and_later, spec_configured_state_test ) TERMINAL_BLOCK_HASH_CONFIG_VAR = '0x0000000000000000000000000000000000000000000000000000000000000001' TERMINAL_BLOCK_HASH = Bytes32(TERMINAL_BLOCK_HASH_CONFIG_VAR) def run_validate_merge_block(spec, pow_chain, beacon_block, valid=True): """ Run ``validate_merge_block`` If ``valid == False``, run expecting ``AssertionError`` """ def get_pow_block(hash: spec.Bytes32) -> Optional[spec.PowBlock]: for block in pow_chain: if block.block_hash == hash: return block return None get_pow_block_backup = spec.get_pow_block # Guido authorized everyone to do this spec.get_pow_block = get_pow_block assertion_error_caught = False try: spec.validate_merge_block(beacon_block) except AssertionError: assertion_error_caught = True except Exception as e: spec.get_pow_block = get_pow_block_backup raise e spec.get_pow_block = get_pow_block_backup if valid: assert not assertion_error_caught else: assert assertion_error_caught @with_bellatrix_and_later @spec_state_test def test_validate_merge_block_success(spec, state): pow_chain = prepare_random_pow_chain(spec, 2) pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = pow_chain.head().block_hash block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) run_validate_merge_block(spec, pow_chain, block) @with_bellatrix_and_later @spec_state_test def test_validate_merge_block_fail_block_lookup(spec, state): pow_chain = prepare_random_pow_chain(spec, 2) pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY block = build_empty_block_for_next_slot(spec, state) run_validate_merge_block(spec, pow_chain, block, valid=False) @with_bellatrix_and_later @spec_state_test def test_validate_merge_block_fail_parent_block_lookup(spec, state): pow_chain = prepare_random_pow_chain(spec, 1) pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = pow_chain.head().block_hash block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) run_validate_merge_block(spec, pow_chain, block, valid=False) @with_bellatrix_and_later @spec_state_test def test_validate_merge_block_fail_after_terminal(spec, state): pow_chain = prepare_random_pow_chain(spec, 2) pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY + uint256(1) block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = pow_chain.head().block_hash block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) run_validate_merge_block(spec, pow_chain, block, valid=False) @with_bellatrix_and_later @spec_configured_state_test({ 'TERMINAL_BLOCK_HASH': TERMINAL_BLOCK_HASH_CONFIG_VAR, 'TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH': '0' }) def test_validate_merge_block_tbh_override_success(spec, state): pow_chain = prepare_random_pow_chain(spec, 2) # should fail if TTD check is reached pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(2) pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) pow_chain.head().block_hash = TERMINAL_BLOCK_HASH block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = pow_chain.head().block_hash block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) run_validate_merge_block(spec, pow_chain, block) @with_bellatrix_and_later @spec_configured_state_test({ 'TERMINAL_BLOCK_HASH': TERMINAL_BLOCK_HASH_CONFIG_VAR, 'TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH': '0' }) def test_validate_merge_block_fail_parent_hash_is_not_tbh(spec, state): pow_chain = prepare_random_pow_chain(spec, 2) # shouldn't fail if TTD check is reached pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = pow_chain.head().block_hash block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) run_validate_merge_block(spec, pow_chain, block, valid=False) @with_bellatrix_and_later @spec_configured_state_test({ 'TERMINAL_BLOCK_HASH': TERMINAL_BLOCK_HASH_CONFIG_VAR, 'TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH': '1' }) def test_validate_merge_block_terminal_block_hash_fail_activation_not_reached(spec, state): pow_chain = prepare_random_pow_chain(spec, 2) # shouldn't fail if TTD check is reached pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY pow_chain.head().block_hash = TERMINAL_BLOCK_HASH block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = pow_chain.head().block_hash block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) run_validate_merge_block(spec, pow_chain, block, valid=False) @with_bellatrix_and_later @spec_configured_state_test({ 'TERMINAL_BLOCK_HASH': TERMINAL_BLOCK_HASH_CONFIG_VAR, 'TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH': '1' }) def test_validate_merge_block_fail_activation_not_reached_parent_hash_is_not_tbh(spec, state): pow_chain = prepare_random_pow_chain(spec, 2) # shouldn't fail if TTD check is reached pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - uint256(1) pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY block = build_empty_block_for_next_slot(spec, state) block.body.execution_payload.parent_hash = pow_chain.head().block_hash block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) run_validate_merge_block(spec, pow_chain, block, valid=False)
7,130
42.481707
103
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/unittests/validator/test_validator.py
from copy import deepcopy from typing import Optional from eth2spec.test.helpers.pow_block import ( prepare_random_pow_chain, ) from eth2spec.test.helpers.constants import ( BELLATRIX, ) from eth2spec.test.context import ( spec_state_test, with_phases, ) # For test_get_pow_block_at_terminal_total_difficulty IS_HEAD_BLOCK = 'is_head_block' IS_HEAD_PARENT_BLOCK = 'is_head_parent_block' # NOTE: The following parameter names are in the view of the head block (the second block) # 'block_reached_ttd', 'block_parent_hash_is_empty', 'parent_reached_ttd', 'return_block' expected_results = [ (False, False, False, None), (False, False, True, IS_HEAD_PARENT_BLOCK), (False, True, False, None), (False, True, True, IS_HEAD_PARENT_BLOCK), (True, False, False, IS_HEAD_BLOCK), (True, False, True, IS_HEAD_PARENT_BLOCK), (True, True, False, IS_HEAD_BLOCK), (True, True, True, IS_HEAD_PARENT_BLOCK), ] # NOTE: since the first block's `parent_hash` is set to `Hash32()` in test, if `parent_reached_ttd is True`, # it would return the first block (IS_HEAD_PARENT_BLOCK). @with_phases([BELLATRIX]) @spec_state_test def test_get_pow_block_at_terminal_total_difficulty(spec, state): for result in expected_results: ( block_reached_ttd, block_parent_hash_is_empty, parent_reached_ttd, return_block ) = result pow_chain = prepare_random_pow_chain(spec, 2) pow_chain.head(-1).parent_hash = spec.Hash32() if block_reached_ttd: pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY else: pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - 1 if parent_reached_ttd: pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY else: pow_chain.head(-1).total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - 1 if block_parent_hash_is_empty: pow_chain.head().parent_hash = spec.Hash32() pow_block = spec.get_pow_block_at_terminal_total_difficulty(pow_chain.to_dict()) if return_block == IS_HEAD_BLOCK: assert pow_block == pow_chain.head() elif return_block == IS_HEAD_PARENT_BLOCK: assert pow_block == pow_chain.head(-1) elif return_block is None: assert pow_block is None else: raise Exception('Something is wrong') SAMPLE_PAYLOAD_ID = b'\x12' * 8 # ('is_merge_complete', 'is_terminal_block_hash_set', 'is_activation_epoch_reached', # 'terminal_pow_block_is_none', 'result_payload_id') prepare_execution_payload_expected_results = [ (False, False, False, False, SAMPLE_PAYLOAD_ID), (False, False, False, True, None), (False, False, True, False, SAMPLE_PAYLOAD_ID), (False, False, True, True, None), (False, True, False, False, None), (False, True, False, True, None), (False, True, True, False, SAMPLE_PAYLOAD_ID), (False, True, True, True, None), (True, False, False, False, SAMPLE_PAYLOAD_ID), (True, False, False, True, SAMPLE_PAYLOAD_ID), (True, False, True, False, SAMPLE_PAYLOAD_ID), (True, False, True, True, SAMPLE_PAYLOAD_ID), (True, True, False, False, SAMPLE_PAYLOAD_ID), (True, True, False, True, SAMPLE_PAYLOAD_ID), (True, True, True, False, SAMPLE_PAYLOAD_ID), (True, True, True, True, SAMPLE_PAYLOAD_ID), ] @with_phases([BELLATRIX]) @spec_state_test def test_prepare_execution_payload(spec, state): for result in prepare_execution_payload_expected_results: ( is_merge_complete, is_terminal_block_hash_set, is_activation_epoch_reached, terminal_pow_block_is_none, result_payload_id, ) = result # 1. Handle `is_merge_complete` if is_merge_complete: state.latest_execution_payload_header = spec.ExecutionPayloadHeader(prev_randao=b'\x12' * 32) else: state.latest_execution_payload_header = spec.ExecutionPayloadHeader() # 2. `is_terminal_block_hash_set` and `is_activation_epoch_reached` require mocking configs in runtime config_overrides = {} _mock_terminal_block_hash = b'\x34' * 32 if is_terminal_block_hash_set: config_overrides['TERMINAL_BLOCK_HASH'] = _mock_terminal_block_hash else: config_overrides['TERMINAL_BLOCK_HASH'] = spec.Hash32() # Default `TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH` is too big and too close to overflow _mock_terminal_block_hash_activation_epoch = 3 config_overrides['TERMINAL_BLOCK_HASH_ACTIVATION_EPOCH'] = _mock_terminal_block_hash_activation_epoch if is_activation_epoch_reached: state.slot = _mock_terminal_block_hash_activation_epoch * spec.SLOTS_PER_EPOCH else: state.slot = (_mock_terminal_block_hash_activation_epoch - 1) * spec.SLOTS_PER_EPOCH # Logic from `with_config_overrides` old_config = spec.config tmp_config = deepcopy(old_config._asdict()) tmp_config.update(config_overrides) config_types = spec.Configuration.__annotations__ test_config = {k: config_types[k](v) for k, v in tmp_config.items()} spec.config = spec.Configuration(**test_config) # 3. Handle `terminal_pow_block_is_none` pow_chain = prepare_random_pow_chain(spec, 2) if terminal_pow_block_is_none: pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY - 1 else: if is_terminal_block_hash_set: pow_chain.head().block_hash = _mock_terminal_block_hash pow_chain.head().total_difficulty = spec.config.TERMINAL_TOTAL_DIFFICULTY # Dummy arguments finalized_block_hash = b'\x56' * 32 safe_block_hash = b'\x58' * 32 suggested_fee_recipient = b'\x78' * 20 # Mock execution_engine class TestEngine(spec.NoopExecutionEngine): def notify_forkchoice_updated(self, head_block_hash, safe_block_hash, finalized_block_hash, payload_attributes) -> Optional[spec.PayloadId]: return SAMPLE_PAYLOAD_ID payload_id = spec.prepare_execution_payload( state=state, safe_block_hash=safe_block_hash, finalized_block_hash=finalized_block_hash, suggested_fee_recipient=suggested_fee_recipient, execution_engine=TestEngine(), pow_chain=pow_chain.to_dict(), ) assert payload_id == result_payload_id # Restore config spec.config = old_config
6,855
38.630058
110
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/fork/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/fork/test_bellatrix_fork_random.py
from random import Random from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( ALTAIR, BELLATRIX, MINIMAL, ) from eth2spec.test.helpers.bellatrix.fork import ( BELLATRIX_FORK_TEST_META_TAGS, run_fork_test, ) from eth2spec.test.helpers.random import randomize_state @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_bellatrix_fork_random_0(spec, phases, state): randomize_state(spec, state, rng=Random(1010)) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_bellatrix_fork_random_1(spec, phases, state): randomize_state(spec, state, rng=Random(2020)) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_bellatrix_fork_random_2(spec, phases, state): randomize_state(spec, state, rng=Random(3030)) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_bellatrix_fork_random_3(spec, phases, state): randomize_state(spec, state, rng=Random(4040)) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_bellatrix_fork_random_low_balances(spec, phases, state): randomize_state(spec, state, rng=Random(5050)) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_bellatrix_fork_random_misc_balances(spec, phases, state): randomize_state(spec, state, rng=Random(6060)) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @spec_test @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_bellatrix_fork_random_large_validator_set(spec, phases, state): randomize_state(spec, state, rng=Random(7070)) yield from run_fork_test(phases[BELLATRIX], state)
2,980
34.070588
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/bellatrix/fork/test_bellatrix_fork_basic.py
from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( ALTAIR, BELLATRIX, MINIMAL, ) from eth2spec.test.helpers.state import ( next_epoch, next_epoch_via_block, ) from eth2spec.test.helpers.bellatrix.fork import ( BELLATRIX_FORK_TEST_META_TAGS, run_fork_test, ) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_fork_base_state(spec, phases, state): yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_fork_next_epoch(spec, phases, state): next_epoch(spec, state) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_fork_next_epoch_with_block(spec, phases, state): next_epoch_via_block(spec, state) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_state @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_fork_many_next_epoch(spec, phases, state): for _ in range(3): next_epoch(spec, state) yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_fork_random_low_balances(spec, phases, state): yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_fork_random_misc_balances(spec, phases, state): yield from run_fork_test(phases[BELLATRIX], state) @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(BELLATRIX_FORK_TEST_META_TAGS) def test_fork_random_large_validator_set(spec, phases, state): yield from run_fork_test(phases[BELLATRIX], state)
2,700
31.542169
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/sharding/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/sharding/unittests/test_get_start_shard.py
from eth2spec.test.context import ( with_phases, spec_state_test, ) from eth2spec.test.helpers.constants import SHARDING from eth2spec.test.helpers.state import next_epoch @with_phases([SHARDING]) @spec_state_test def test_get_committee_count_delta(spec, state): assert spec.get_committee_count_delta(state, 0, 0) == 0 assert spec.get_committee_count_per_slot(state, 0) != 0 assert spec.get_committee_count_delta(state, 0, 1) == spec.get_committee_count_per_slot(state, 0) assert spec.get_committee_count_delta(state, 1, 2) == spec.get_committee_count_per_slot(state, 0) assert spec.get_committee_count_delta(state, 0, 2) == spec.get_committee_count_per_slot(state, 0) * 2 assert spec.get_committee_count_delta(state, 0, spec.SLOTS_PER_EPOCH) == ( spec.get_committee_count_per_slot(state, 0) * spec.SLOTS_PER_EPOCH ) assert spec.get_committee_count_delta(state, 0, 2 * spec.SLOTS_PER_EPOCH) == ( spec.get_committee_count_per_slot(state, 0) * spec.SLOTS_PER_EPOCH + spec.get_committee_count_per_slot(state, 1) * spec.SLOTS_PER_EPOCH ) @with_phases([SHARDING]) @spec_state_test def test_get_start_shard_current_epoch_start(spec, state): assert state.current_epoch_start_shard == 0 next_epoch(spec, state) active_shard_count = spec.get_active_shard_count(state) assert state.current_epoch_start_shard == ( spec.get_committee_count_delta(state, 0, spec.SLOTS_PER_EPOCH) % active_shard_count ) current_epoch_start_slot = spec.compute_start_slot_at_epoch(spec.get_current_epoch(state)) slot = current_epoch_start_slot start_shard = spec.get_start_shard(state, slot) assert start_shard == state.current_epoch_start_shard @with_phases([SHARDING]) @spec_state_test def test_get_start_shard_next_slot(spec, state): next_epoch(spec, state) active_shard_count = spec.get_active_shard_count(state) current_epoch_start_slot = spec.compute_start_slot_at_epoch(spec.get_current_epoch(state)) slot = current_epoch_start_slot + 1 start_shard = spec.get_start_shard(state, slot) current_epoch_start_slot = spec.compute_start_slot_at_epoch(spec.get_current_epoch(state)) expected_start_shard = ( state.current_epoch_start_shard + spec.get_committee_count_delta(state, start_slot=current_epoch_start_slot, stop_slot=slot) ) % active_shard_count assert start_shard == expected_start_shard @with_phases([SHARDING]) @spec_state_test def test_get_start_shard_previous_slot(spec, state): next_epoch(spec, state) active_shard_count = spec.get_active_shard_count(state) current_epoch_start_slot = spec.compute_start_slot_at_epoch(spec.get_current_epoch(state)) slot = current_epoch_start_slot - 1 start_shard = spec.get_start_shard(state, slot) current_epoch_start_slot = spec.compute_start_slot_at_epoch(spec.get_current_epoch(state)) expected_start_shard = ( state.current_epoch_start_shard + spec.MAX_COMMITTEES_PER_SLOT * spec.SLOTS_PER_EPOCH * active_shard_count - spec.get_committee_count_delta(state, start_slot=slot, stop_slot=current_epoch_start_slot) ) % active_shard_count assert start_shard == expected_start_shard @with_phases([SHARDING]) @spec_state_test def test_get_start_shard_far_past_epoch(spec, state): initial_epoch = spec.get_current_epoch(state) initial_start_slot = spec.compute_start_slot_at_epoch(initial_epoch) initial_start_shard = state.current_epoch_start_shard for _ in range(spec.MAX_SHARDS + 2): next_epoch(spec, state) assert spec.get_start_shard(state, initial_start_slot) == initial_start_shard
3,672
39.811111
105
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/sharding/unittests/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/random/test_random.py
""" This module is generated from the ``random`` test generator. Please do not edit this file manually. See the README for that generator for more information. """ from eth2spec.test.helpers.constants import ALTAIR from eth2spec.test.context import ( misc_balances_in_default_range_with_many_validators, with_phases, zero_activation_threshold, only_generator, ) from eth2spec.test.context import ( always_bls, spec_test, with_custom_state, single_phase, ) from eth2spec.test.utils.randomized_block_tests import ( run_generated_randomized_test, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_0(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_1(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_2(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_3(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_4(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_5(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_6(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_7(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_8(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_9(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_10(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_11(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_12(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_13(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_14(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([ALTAIR]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_15(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_altair_with_cycling_sync_committee_participation scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_altair_with_cycling_sync_committee_participation', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_altair'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, )
30,877
69.33713
1,020
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/random/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/block_processing/test_process_deposit.py
from eth2spec.test.context import ( spec_state_test, always_bls, with_phases, with_altair_and_later, ) from eth2spec.test.helpers.constants import ( ALTAIR, ) from eth2spec.test.helpers.deposits import ( run_deposit_processing_with_specific_fork_version, ) @with_phases([ALTAIR]) @spec_state_test @always_bls def test_effective_deposit_with_previous_fork_version(spec, state): assert state.fork.previous_version != state.fork.current_version # It's only effective in Altair because the default `fork_version` of `compute_domain` is `GENESIS_FORK_VERSION`. # Therefore it's just a normal `DepositMessage`. yield from run_deposit_processing_with_specific_fork_version( spec, state, fork_version=state.fork.previous_version, ) @with_altair_and_later @spec_state_test @always_bls def test_ineffective_deposit_with_current_fork_version(spec, state): yield from run_deposit_processing_with_specific_fork_version( spec, state, fork_version=state.fork.current_version, effective=False, )
1,095
25.095238
117
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/block_processing/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/block_processing/sync_aggregate/test_process_sync_aggregate_random.py
import random from eth2spec.test.helpers.constants import ( MAINNET, MINIMAL, ) from eth2spec.test.helpers.random import ( randomize_state, ) from eth2spec.test.helpers.state import ( has_active_balance_differential, ) from eth2spec.test.helpers.sync_committee import ( compute_committee_indices, run_successful_sync_committee_test, ) from eth2spec.test.helpers.voluntary_exits import ( get_unslashed_exited_validators, ) from eth2spec.test.context import ( with_altair_and_later, spec_state_test, default_activation_threshold, misc_balances, single_phase, with_custom_state, with_presets, spec_test, ) def _test_harness_for_randomized_test_case(spec, state, expect_duplicates=False, participation_fn=None): committee_indices = compute_committee_indices(state) if participation_fn: participating_indices = participation_fn(committee_indices) else: participating_indices = committee_indices committee_bits = [index in participating_indices for index in committee_indices] committee_size = len(committee_indices) if expect_duplicates: assert committee_size > len(set(committee_indices)) else: assert committee_size == len(set(committee_indices)) yield from run_successful_sync_committee_test(spec, state, committee_indices, committee_bits) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_random_only_one_participant_with_duplicates(spec, state): rng = random.Random(101) yield from _test_harness_for_randomized_test_case( spec, state, expect_duplicates=True, participation_fn=lambda comm: [rng.choice(comm)], ) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_random_low_participation_with_duplicates(spec, state): rng = random.Random(201) yield from _test_harness_for_randomized_test_case( spec, state, expect_duplicates=True, participation_fn=lambda comm: rng.sample(comm, int(len(comm) * 0.25)), ) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_random_high_participation_with_duplicates(spec, state): rng = random.Random(301) yield from _test_harness_for_randomized_test_case( spec, state, expect_duplicates=True, participation_fn=lambda comm: rng.sample(comm, int(len(comm) * 0.75)), ) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_random_all_but_one_participating_with_duplicates(spec, state): rng = random.Random(401) yield from _test_harness_for_randomized_test_case( spec, state, expect_duplicates=True, participation_fn=lambda comm: rng.sample(comm, len(comm) - 1), ) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_test @with_custom_state(balances_fn=misc_balances, threshold_fn=default_activation_threshold) @single_phase def test_random_misc_balances_and_half_participation_with_duplicates(spec, state): rng = random.Random(1401) yield from _test_harness_for_randomized_test_case( spec, state, expect_duplicates=True, participation_fn=lambda comm: rng.sample(comm, len(comm) // 2), ) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test @single_phase def test_random_with_exits_with_duplicates(spec, state): rng = random.Random(1402) randomize_state(spec, state, rng=rng, exit_fraction=0.1, slash_fraction=0.0) target_validators = get_unslashed_exited_validators(spec, state) assert len(target_validators) != 0 assert has_active_balance_differential(spec, state) yield from _test_harness_for_randomized_test_case( spec, state, expect_duplicates=True, participation_fn=lambda comm: rng.sample(comm, len(comm) // 2), ) @with_altair_and_later @with_presets([MINIMAL], reason="to create nonduplicate committee") @spec_state_test def test_random_only_one_participant_without_duplicates(spec, state): rng = random.Random(501) yield from _test_harness_for_randomized_test_case( spec, state, participation_fn=lambda comm: [rng.choice(comm)], ) @with_altair_and_later @with_presets([MINIMAL], reason="to create nonduplicate committee") @spec_state_test def test_random_low_participation_without_duplicates(spec, state): rng = random.Random(601) yield from _test_harness_for_randomized_test_case( spec, state, participation_fn=lambda comm: rng.sample(comm, int(len(comm) * 0.25)), ) @with_altair_and_later @with_presets([MINIMAL], reason="to create nonduplicate committee") @spec_state_test def test_random_high_participation_without_duplicates(spec, state): rng = random.Random(701) yield from _test_harness_for_randomized_test_case( spec, state, participation_fn=lambda comm: rng.sample(comm, int(len(comm) * 0.75)), ) @with_altair_and_later @with_presets([MINIMAL], reason="to create nonduplicate committee") @spec_state_test def test_random_all_but_one_participating_without_duplicates(spec, state): rng = random.Random(801) yield from _test_harness_for_randomized_test_case( spec, state, participation_fn=lambda comm: rng.sample(comm, len(comm) - 1), ) @with_altair_and_later @with_presets([MINIMAL], reason="to create nonduplicate committee") @spec_test @with_custom_state(balances_fn=misc_balances, threshold_fn=default_activation_threshold) @single_phase def test_random_misc_balances_and_half_participation_without_duplicates(spec, state): rng = random.Random(1501) yield from _test_harness_for_randomized_test_case( spec, state, participation_fn=lambda comm: rng.sample(comm, len(comm) // 2), ) @with_altair_and_later @with_presets([MINIMAL], reason="to create nonduplicate committee") @spec_state_test @single_phase def test_random_with_exits_without_duplicates(spec, state): rng = random.Random(1502) randomize_state(spec, state, rng=rng, exit_fraction=0.1, slash_fraction=0.0) target_validators = get_unslashed_exited_validators(spec, state) assert len(target_validators) != 0 assert has_active_balance_differential(spec, state) yield from _test_harness_for_randomized_test_case( spec, state, participation_fn=lambda comm: rng.sample(comm, len(comm) // 2), )
6,697
30.895238
104
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/block_processing/sync_aggregate/test_process_sync_aggregate.py
import random from eth2spec.test.helpers.block import ( build_empty_block_for_next_slot, ) from eth2spec.test.helpers.state import ( state_transition_and_sign_block, transition_to, next_epoch_via_block, ) from eth2spec.test.helpers.constants import ( MAINNET, MINIMAL, ) from eth2spec.test.helpers.sync_committee import ( compute_aggregate_sync_committee_signature, compute_committee_indices, run_sync_committee_processing, run_successful_sync_committee_test, ) from eth2spec.test.helpers.voluntary_exits import ( get_unslashed_exited_validators, ) from eth2spec.test.context import ( with_altair_and_later, with_presets, spec_state_test, always_bls, ) @with_altair_and_later @spec_state_test @always_bls def test_invalid_signature_bad_domain(spec, state): committee_indices = compute_committee_indices(state) block = build_empty_block_for_next_slot(spec, state) block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, # full committee signs block_root=block.parent_root, domain_type=spec.DOMAIN_BEACON_ATTESTER, # Incorrect domain ) ) yield from run_sync_committee_processing(spec, state, block, expect_exception=True) @with_altair_and_later @spec_state_test @always_bls def test_invalid_signature_missing_participant(spec, state): committee_indices = compute_committee_indices(state) rng = random.Random(2020) random_participant = rng.choice(committee_indices) block = build_empty_block_for_next_slot(spec, state) # Exclude one participant whose signature was included. block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[index != random_participant for index in committee_indices], sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, # full committee signs block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block, expect_exception=True) @with_altair_and_later @spec_state_test @always_bls def test_invalid_signature_no_participants(spec, state): block = build_empty_block_for_next_slot(spec, state) # No participants is an allowed case, but needs a specific signature, not the full-zeroed signature. block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[False] * len(block.body.sync_aggregate.sync_committee_bits), sync_committee_signature=b'\x00' * 96 ) yield from run_sync_committee_processing(spec, state, block, expect_exception=True) # No-participants, with valid signature, is tested in test_sync_committee_rewards_empty_participants already. @with_altair_and_later @spec_state_test @always_bls def test_invalid_signature_infinite_signature_with_all_participants(spec, state): block = build_empty_block_for_next_slot(spec, state) # Include all participants, try the special-case signature for no-participants block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(block.body.sync_aggregate.sync_committee_bits), sync_committee_signature=spec.G2_POINT_AT_INFINITY ) yield from run_sync_committee_processing(spec, state, block, expect_exception=True) @with_altair_and_later @spec_state_test @always_bls def test_invalid_signature_infinite_signature_with_single_participant(spec, state): block = build_empty_block_for_next_slot(spec, state) # Try include a single participant with the special-case signature for no-participants. block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] + ([False] * (len(block.body.sync_aggregate.sync_committee_bits) - 1)), sync_committee_signature=spec.G2_POINT_AT_INFINITY ) yield from run_sync_committee_processing(spec, state, block, expect_exception=True) @with_altair_and_later @spec_state_test @always_bls def test_invalid_signature_extra_participant(spec, state): committee_indices = compute_committee_indices(state) rng = random.Random(3030) random_participant = rng.choice(committee_indices) block = build_empty_block_for_next_slot(spec, state) # Exclude one signature even though the block claims the entire committee participated. block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, [index for index in committee_indices if index != random_participant], block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block, expect_exception=True) def is_duplicate_sync_committee(committee_indices): dup = {v for v in committee_indices if committee_indices.count(v) > 1} return len(dup) > 0 @with_altair_and_later @with_presets([MINIMAL], reason="to create nonduplicate committee") @spec_state_test def test_sync_committee_rewards_nonduplicate_committee(spec, state): committee_indices = compute_committee_indices(state) # Preconditions of this test case assert not is_duplicate_sync_committee(committee_indices) committee_size = len(committee_indices) committee_bits = [True] * committee_size yield from run_successful_sync_committee_test(spec, state, committee_indices, committee_bits) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_sync_committee_rewards_duplicate_committee_no_participation(spec, state): committee_indices = compute_committee_indices(state) # Preconditions of this test case assert is_duplicate_sync_committee(committee_indices) committee_size = len(committee_indices) committee_bits = [False] * committee_size yield from run_successful_sync_committee_test(spec, state, committee_indices, committee_bits) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_sync_committee_rewards_duplicate_committee_half_participation(spec, state): committee_indices = compute_committee_indices(state) # Preconditions of this test case assert is_duplicate_sync_committee(committee_indices) committee_size = len(committee_indices) committee_bits = [True] * (committee_size // 2) + [False] * (committee_size // 2) assert len(committee_bits) == committee_size yield from run_successful_sync_committee_test(spec, state, committee_indices, committee_bits) @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_sync_committee_rewards_duplicate_committee_full_participation(spec, state): committee_indices = compute_committee_indices(state) # Preconditions of this test case assert is_duplicate_sync_committee(committee_indices) committee_size = len(committee_indices) committee_bits = [True] * committee_size yield from run_successful_sync_committee_test(spec, state, committee_indices, committee_bits) def _run_sync_committee_selected_twice( spec, state, pre_balance, participate_first_position, participate_second_position, skip_reward_validation=False): committee_indices = compute_committee_indices(state) # Preconditions of this test case assert is_duplicate_sync_committee(committee_indices) committee_size = len(committee_indices) committee_bits = [False] * committee_size # Find duplicate indices that get selected twice dup = {v for v in committee_indices if committee_indices.count(v) == 2} assert len(dup) > 0 validator_index = dup.pop() positions = [i for i, v in enumerate(committee_indices) if v == validator_index] committee_bits[positions[0]] = participate_first_position committee_bits[positions[1]] = participate_second_position # Set validator's balance state.balances[validator_index] = pre_balance state.validators[validator_index].effective_balance = min( pre_balance - pre_balance % spec.EFFECTIVE_BALANCE_INCREMENT, spec.MAX_EFFECTIVE_BALANCE, ) yield from run_successful_sync_committee_test( spec, state, committee_indices, committee_bits, skip_reward_validation=skip_reward_validation) return validator_index @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_sync_committee_rewards_duplicate_committee_zero_balance_only_participate_first_one(spec, state): validator_index = yield from _run_sync_committee_selected_twice( spec, state, pre_balance=0, participate_first_position=True, participate_second_position=False, ) # The validator gets reward first (balance > 0) and then gets the same amount of penalty (balance == 0) assert state.balances[validator_index] == 0 @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_sync_committee_rewards_duplicate_committee_zero_balance_only_participate_second_one(spec, state): # Skip `validate_sync_committee_rewards` because it doesn't handle the balance computation order # inside the for loop validator_index = yield from _run_sync_committee_selected_twice( spec, state, pre_balance=0, participate_first_position=False, participate_second_position=True, skip_reward_validation=True, ) # The validator gets penalty first (balance is still 0) and then gets reward (balance > 0) assert state.balances[validator_index] > 0 @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_sync_committee_rewards_duplicate_committee_max_effective_balance_only_participate_first_one(spec, state): validator_index = yield from _run_sync_committee_selected_twice( spec, state, pre_balance=spec.MAX_EFFECTIVE_BALANCE, participate_first_position=True, participate_second_position=False, ) assert state.balances[validator_index] == spec.MAX_EFFECTIVE_BALANCE @with_altair_and_later @with_presets([MAINNET], reason="to create duplicate committee") @spec_state_test def test_sync_committee_rewards_duplicate_committee_max_effective_balance_only_participate_second_one(spec, state): validator_index = yield from _run_sync_committee_selected_twice( spec, state, pre_balance=spec.MAX_EFFECTIVE_BALANCE, participate_first_position=False, participate_second_position=True, ) assert state.balances[validator_index] == spec.MAX_EFFECTIVE_BALANCE @with_altair_and_later @spec_state_test @always_bls def test_sync_committee_rewards_not_full_participants(spec, state): committee_indices = compute_committee_indices(state) rng = random.Random(1010) committee_bits = [rng.choice([True, False]) for _ in committee_indices] yield from run_successful_sync_committee_test(spec, state, committee_indices, committee_bits) @with_altair_and_later @spec_state_test @always_bls def test_sync_committee_rewards_empty_participants(spec, state): committee_indices = compute_committee_indices(state) committee_bits = [False for _ in committee_indices] yield from run_successful_sync_committee_test(spec, state, committee_indices, committee_bits) @with_altair_and_later @spec_state_test @always_bls def test_invalid_signature_past_block(spec, state): committee_indices = compute_committee_indices(state) for _ in range(2): # NOTE: need to transition twice to move beyond the degenerate case at genesis block = build_empty_block_for_next_slot(spec, state) # Valid sync committee signature here... block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, block_root=block.parent_root, ) ) state_transition_and_sign_block(spec, state, block) invalid_block = build_empty_block_for_next_slot(spec, state) # Invalid signature from a slot other than the previous invalid_block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, invalid_block.slot - 2, committee_indices, ) ) yield from run_sync_committee_processing(spec, state, invalid_block, expect_exception=True) @with_altair_and_later @with_presets([MINIMAL], reason="to produce different committee sets") @spec_state_test @always_bls def test_invalid_signature_previous_committee(spec, state): # NOTE: the `state` provided is at genesis and the process to select # sync committees currently returns the same committee for the first and second # periods at genesis. # To get a distinct committee so we can generate an "old" signature, we need to advance # 2 EPOCHS_PER_SYNC_COMMITTEE_PERIOD periods. current_epoch = spec.get_current_epoch(state) old_sync_committee = state.next_sync_committee epoch_in_future_sync_commitee_period = current_epoch + 2 * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD slot_in_future_sync_committee_period = epoch_in_future_sync_commitee_period * spec.SLOTS_PER_EPOCH transition_to(spec, state, slot_in_future_sync_committee_period) # Use the previous sync committee to produce the signature. # Ensure that the pubkey sets are different. assert set(old_sync_committee.pubkeys) != set(state.current_sync_committee.pubkeys) committee_indices = compute_committee_indices(state, old_sync_committee) block = build_empty_block_for_next_slot(spec, state) block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block, expect_exception=True) @with_altair_and_later @spec_state_test @always_bls @with_presets([MINIMAL], reason="too slow") def test_valid_signature_future_committee(spec, state): # NOTE: the `state` provided is at genesis and the process to select # sync committees currently returns the same committee for the first and second # periods at genesis. # To get a distinct committee so we can generate an "old" signature, we need to advance # 2 EPOCHS_PER_SYNC_COMMITTEE_PERIOD periods. current_epoch = spec.get_current_epoch(state) old_current_sync_committee = state.current_sync_committee old_next_sync_committee = state.next_sync_committee epoch_in_future_sync_committee_period = current_epoch + 2 * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD slot_in_future_sync_committee_period = epoch_in_future_sync_committee_period * spec.SLOTS_PER_EPOCH transition_to(spec, state, slot_in_future_sync_committee_period) sync_committee = state.current_sync_committee next_sync_committee = state.next_sync_committee assert next_sync_committee != sync_committee assert sync_committee != old_current_sync_committee assert sync_committee != old_next_sync_committee committee_indices = compute_committee_indices(state, sync_committee) block = build_empty_block_for_next_slot(spec, state) block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block) @with_altair_and_later @spec_state_test @always_bls @with_presets([MINIMAL], reason="prefer short search to find matching proposer") def test_proposer_in_committee_without_participation(spec, state): committee_indices = compute_committee_indices(state, state.current_sync_committee) # NOTE: seem to reliably be getting a matching proposer in the first epoch w/ ``MINIMAL`` preset. for _ in range(spec.SLOTS_PER_EPOCH): block = build_empty_block_for_next_slot(spec, state) proposer_index = block.proposer_index proposer_pubkey = state.validators[proposer_index].pubkey proposer_is_in_sync_committee = proposer_pubkey in state.current_sync_committee.pubkeys if proposer_is_in_sync_committee: participation = [index != proposer_index for index in committee_indices] participants = [index for index in committee_indices if index != proposer_index] else: participation = [True for _ in committee_indices] participants = committee_indices # Valid sync committee signature here... block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=participation, sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, participants, block_root=block.parent_root, ) ) if proposer_is_in_sync_committee: assert state.validators[block.proposer_index].pubkey in state.current_sync_committee.pubkeys yield from run_sync_committee_processing(spec, state, block) break else: state_transition_and_sign_block(spec, state, block) else: raise AssertionError("failed to find a proposer in the sync committee set; check test setup") @with_altair_and_later @spec_state_test @always_bls @with_presets([MINIMAL], reason="prefer short search to find matching proposer") def test_proposer_in_committee_with_participation(spec, state): committee_indices = compute_committee_indices(state, state.current_sync_committee) participation = [True for _ in committee_indices] # NOTE: seem to reliably be getting a matching proposer in the first epoch w/ ``MINIMAL`` preset. for _ in range(spec.SLOTS_PER_EPOCH): block = build_empty_block_for_next_slot(spec, state) proposer_index = block.proposer_index proposer_pubkey = state.validators[proposer_index].pubkey proposer_is_in_sync_committee = proposer_pubkey in state.current_sync_committee.pubkeys # Valid sync committee signature here... block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=participation, sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, block_root=block.parent_root, ) ) if proposer_is_in_sync_committee: assert state.validators[block.proposer_index].pubkey in state.current_sync_committee.pubkeys yield from run_sync_committee_processing(spec, state, block) return else: state_transition_and_sign_block(spec, state, block) raise AssertionError("failed to find a proposer in the sync committee set; check test setup") def _exit_validator_from_committee_and_transition_state(spec, state, committee_indices, rng, target_epoch_provider, withdrawable_offset=1): exited_validator_index = rng.sample(committee_indices, 1)[0] validator = state.validators[exited_validator_index] current_epoch = spec.get_current_epoch(state) validator.exit_epoch = current_epoch validator.withdrawable_epoch = validator.exit_epoch + withdrawable_offset target_epoch = target_epoch_provider(state.validators[exited_validator_index]) target_slot = target_epoch * spec.SLOTS_PER_EPOCH transition_to(spec, state, target_slot) exited_validator_indices = get_unslashed_exited_validators(spec, state) assert exited_validator_index in exited_validator_indices exited_pubkey = state.validators[exited_validator_index].pubkey assert exited_pubkey in state.current_sync_committee.pubkeys return exited_validator_index @with_altair_and_later @spec_state_test @always_bls def test_sync_committee_with_participating_exited_member(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH # move forward via some blocks for _ in range(3): next_epoch_via_block(spec, state) committee_indices = compute_committee_indices(state) rng = random.Random(1010) exited_index = _exit_validator_from_committee_and_transition_state( spec, state, committee_indices, rng, lambda v: v.exit_epoch, ) current_epoch = spec.get_current_epoch(state) assert current_epoch < state.validators[exited_index].withdrawable_epoch block = build_empty_block_for_next_slot(spec, state) block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, # full committee signs block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block) @with_altair_and_later @spec_state_test @always_bls def test_sync_committee_with_nonparticipating_exited_member(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH # move forward via some blocks for _ in range(3): next_epoch_via_block(spec, state) committee_indices = compute_committee_indices(state) rng = random.Random(1010) exited_index = _exit_validator_from_committee_and_transition_state( spec, state, committee_indices, rng, lambda v: v.exit_epoch, ) exited_pubkey = state.validators[exited_index].pubkey current_epoch = spec.get_current_epoch(state) assert current_epoch < state.validators[exited_index].withdrawable_epoch exited_committee_index = state.current_sync_committee.pubkeys.index(exited_pubkey) block = build_empty_block_for_next_slot(spec, state) committee_bits = [i != exited_committee_index for i in committee_indices] committee_indices = [index for index in committee_indices if index != exited_committee_index] block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=committee_bits, sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, # with exited validator removed block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block) @with_altair_and_later @spec_state_test @always_bls def test_sync_committee_with_participating_withdrawable_member(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH # move forward via some blocks for _ in range(3): next_epoch_via_block(spec, state) committee_indices = compute_committee_indices(state) rng = random.Random(1010) exited_index = _exit_validator_from_committee_and_transition_state( spec, state, committee_indices, rng, lambda v: v.withdrawable_epoch + 1, ) current_epoch = spec.get_current_epoch(state) assert current_epoch > state.validators[exited_index].withdrawable_epoch block = build_empty_block_for_next_slot(spec, state) block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=[True] * len(committee_indices), sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, # full committee signs block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block) @with_altair_and_later @spec_state_test @always_bls def test_sync_committee_with_nonparticipating_withdrawable_member(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH # move forward via some blocks for _ in range(3): next_epoch_via_block(spec, state) committee_indices = compute_committee_indices(state) rng = random.Random(1010) exited_index = _exit_validator_from_committee_and_transition_state( spec, state, committee_indices, rng, lambda v: v.withdrawable_epoch + 1, ) exited_pubkey = state.validators[exited_index].pubkey current_epoch = spec.get_current_epoch(state) assert current_epoch > state.validators[exited_index].withdrawable_epoch target_committee_index = state.current_sync_committee.pubkeys.index(exited_pubkey) block = build_empty_block_for_next_slot(spec, state) committee_bits = [i != target_committee_index for i in committee_indices] committee_indices = [index for index in committee_indices if index != target_committee_index] block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=committee_bits, sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, committee_indices, # with withdrawable validator removed block_root=block.parent_root, ) ) yield from run_sync_committee_processing(spec, state, block)
26,923
37.190071
115
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/block_processing/sync_aggregate/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/sanity/test_blocks.py
from random import Random from eth2spec.test.helpers.state import ( state_transition_and_sign_block, next_epoch, set_full_participation_previous_epoch, ) from eth2spec.test.helpers.block import ( build_empty_block_for_next_slot, build_empty_block, ) from eth2spec.test.helpers.sync_committee import ( compute_aggregate_sync_committee_signature, ) from eth2spec.test.context import ( with_altair_and_later, spec_state_test, ) from eth2spec.test.helpers.rewards import leaking from eth2spec.test.helpers.inactivity_scores import randomize_inactivity_scores def run_sync_committee_sanity_test(spec, state, fraction_full=1.0, rng=Random(454545)): all_pubkeys = [v.pubkey for v in state.validators] committee = [all_pubkeys.index(pubkey) for pubkey in state.current_sync_committee.pubkeys] selected_indices = rng.sample(range(len(committee)), int(len(committee) * fraction_full)) sync_committee_bits = [i in selected_indices for i in range(len(committee))] participants = [ validator_index for i, validator_index in enumerate(committee) if sync_committee_bits[i] ] yield 'pre', state block = build_empty_block_for_next_slot(spec, state) block.body.sync_aggregate = spec.SyncAggregate( sync_committee_bits=sync_committee_bits, sync_committee_signature=compute_aggregate_sync_committee_signature( spec, state, block.slot - 1, participants, ) ) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state @with_altair_and_later @spec_state_test def test_sync_committee_committee__full(spec, state): next_epoch(spec, state) yield from run_sync_committee_sanity_test(spec, state, fraction_full=1.0) @with_altair_and_later @spec_state_test def test_sync_committee_committee__half(spec, state): next_epoch(spec, state) yield from run_sync_committee_sanity_test(spec, state, fraction_full=0.5, rng=Random(1212)) @with_altair_and_later @spec_state_test def test_sync_committee_committee__empty(spec, state): next_epoch(spec, state) yield from run_sync_committee_sanity_test(spec, state, fraction_full=0.0) @with_altair_and_later @spec_state_test def test_sync_committee_committee_genesis__full(spec, state): yield from run_sync_committee_sanity_test(spec, state, fraction_full=1.0) @with_altair_and_later @spec_state_test def test_sync_committee_committee_genesis__half(spec, state): yield from run_sync_committee_sanity_test(spec, state, fraction_full=0.5, rng=Random(2323)) @with_altair_and_later @spec_state_test def test_sync_committee_committee_genesis__empty(spec, state): yield from run_sync_committee_sanity_test(spec, state, fraction_full=0.0) @with_altair_and_later @spec_state_test @leaking() def test_inactivity_scores_leaking(spec, state): assert spec.is_in_inactivity_leak(state) randomize_inactivity_scores(spec, state, rng=Random(5252)) assert len(set(state.inactivity_scores)) > 1 previous_inactivity_scores = state.inactivity_scores.copy() yield 'pre', state # Block transition to next epoch block = build_empty_block(spec, state, slot=state.slot + spec.SLOTS_PER_EPOCH) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state # No participation during a leak so all scores should increase for pre, post in zip(previous_inactivity_scores, state.inactivity_scores): assert post == pre + spec.config.INACTIVITY_SCORE_BIAS @with_altair_and_later @spec_state_test @leaking() def test_inactivity_scores_full_participation_leaking(spec, state): randomize_inactivity_scores(spec, state, rng=Random(5252)) assert len(set(state.inactivity_scores)) > 1 # Only set full participation for previous epoch to remain in leak set_full_participation_previous_epoch(spec, state) previous_inactivity_scores = state.inactivity_scores.copy() yield 'pre', state # Block transition to next epoch block = build_empty_block(spec, state, slot=state.slot + spec.SLOTS_PER_EPOCH) signed_block = state_transition_and_sign_block(spec, state, block) assert spec.is_in_inactivity_leak(state) yield 'blocks', [signed_block] yield 'post', state # Full participation during a leak so all scores should decrease by 1 for pre, post in zip(previous_inactivity_scores, state.inactivity_scores): assert post == pre - 1
4,574
31.21831
95
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/sanity/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/test_config_override.py
from eth2spec.test.context import ( spec_configured_state_test, spec_state_test_with_matching_config, spec_test, with_all_phases, with_config_overrides, with_matching_spec_config, with_phases, with_state, ) from eth2spec.test.helpers.constants import ( PHASE0, ALTAIR, BELLATRIX, ALL_PHASES, ) from eth2spec.test.helpers.forks import is_post_fork @with_phases([ALTAIR]) @spec_configured_state_test({ 'GENESIS_FORK_VERSION': '0x12345678', 'ALTAIR_FORK_VERSION': '0x11111111', 'ALTAIR_FORK_EPOCH': 4 }) def test_config_override(spec, state): assert spec.config.ALTAIR_FORK_EPOCH == 4 assert spec.config.GENESIS_FORK_VERSION != spec.Version('0x00000000') assert spec.config.GENESIS_FORK_VERSION == spec.Version('0x12345678') assert spec.config.ALTAIR_FORK_VERSION == spec.Version('0x11111111') assert state.fork.current_version == spec.Version('0x11111111') # TODO: it would be nice if the create_genesis_state actually outputs a state # for the fork with a slot that matches at least the fork boundary. # assert spec.get_current_epoch(state) >= 4 @with_all_phases @spec_state_test_with_matching_config def test_config_override_matching_fork_epochs(spec, state): # Fork schedule must be consistent with state fork epoch = spec.get_current_epoch(state) if is_post_fork(spec.fork, ALTAIR): assert state.fork.current_version == spec.compute_fork_version(epoch) else: assert state.fork.current_version == spec.config.GENESIS_FORK_VERSION # Identify state fork state_fork = None for fork in [fork for fork in ALL_PHASES if is_post_fork(spec.fork, fork)]: if fork == PHASE0: fork_version_field = 'GENESIS_FORK_VERSION' else: fork_version_field = fork.upper() + '_FORK_VERSION' if state.fork.current_version == getattr(spec.config, fork_version_field): state_fork = fork break assert state_fork is not None # Check that all prior forks have already been triggered for fork in [fork for fork in ALL_PHASES if is_post_fork(state_fork, fork)]: if fork == PHASE0: continue fork_epoch_field = fork.upper() + '_FORK_EPOCH' assert getattr(spec.config, fork_epoch_field) <= epoch @with_phases(phases=[ALTAIR], other_phases=[BELLATRIX]) @spec_test @with_config_overrides({ 'ALTAIR_FORK_VERSION': '0x11111111', 'BELLATRIX_FORK_EPOCH': 4, }, emit=False) @with_state @with_matching_spec_config(emitted_fork=BELLATRIX) def test_config_override_across_phases(spec, phases, state): assert state.fork.current_version == spec.config.ALTAIR_FORK_VERSION assert spec.config.ALTAIR_FORK_VERSION == spec.Version('0x11111111') assert spec.config.ALTAIR_FORK_EPOCH == 0 assert not hasattr(spec.config, 'BELLATRIX_FORK_EPOCH') assert phases[ALTAIR].config.ALTAIR_FORK_VERSION == spec.Version('0x11111111') assert phases[ALTAIR].config.ALTAIR_FORK_EPOCH == 0 assert not hasattr(phases[ALTAIR].config, 'BELLATRIX_FORK_EPOCH') assert phases[ALTAIR].config.ALTAIR_FORK_VERSION == spec.Version('0x11111111') assert phases[BELLATRIX].config.ALTAIR_FORK_EPOCH == 0 assert phases[BELLATRIX].config.BELLATRIX_FORK_EPOCH == 4
3,290
36.827586
82
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/test_config_invariants.py
from eth2spec.test.context import ( spec_state_test, with_altair_and_later, ) @with_altair_and_later @spec_state_test def test_weight_denominator(spec, state): assert ( spec.TIMELY_HEAD_WEIGHT + spec.TIMELY_SOURCE_WEIGHT + spec.TIMELY_TARGET_WEIGHT + spec.SYNC_REWARD_WEIGHT + spec.PROPOSER_WEIGHT ) == spec.WEIGHT_DENOMINATOR @with_altair_and_later @spec_state_test def test_inactivity_score(spec, state): assert spec.config.INACTIVITY_SCORE_BIAS <= spec.config.INACTIVITY_SCORE_RECOVERY_RATE
558
23.304348
90
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/validator/test_validator.py
import random from collections import defaultdict from eth2spec.utils.ssz.ssz_typing import Bitvector from eth2spec.utils import bls from eth2spec.test.helpers.block import build_empty_block from eth2spec.test.helpers.keys import pubkey_to_privkey, privkeys, pubkeys from eth2spec.test.helpers.state import transition_to from eth2spec.test.helpers.sync_committee import compute_sync_committee_signature from eth2spec.test.context import ( always_bls, spec_state_test, with_altair_and_later, with_presets, ) from eth2spec.test.helpers.constants import ( MAINNET, MINIMAL, ) rng = random.Random(1337) def ensure_assignments_in_sync_committee( spec, state, epoch, sync_committee, active_pubkeys ): assert len(sync_committee.pubkeys) >= 3 some_pubkeys = rng.sample(sync_committee.pubkeys, 3) for pubkey in some_pubkeys: validator_index = active_pubkeys.index(pubkey) assert spec.is_assigned_to_sync_committee(state, epoch, validator_index) @with_altair_and_later @spec_state_test def test_is_assigned_to_sync_committee(spec, state): epoch = spec.get_current_epoch(state) validator_indices = spec.get_active_validator_indices(state, epoch) validator_count = len(validator_indices) query_epoch = epoch + 1 next_query_epoch = query_epoch + spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD active_pubkeys = [state.validators[index].pubkey for index in validator_indices] ensure_assignments_in_sync_committee( spec, state, query_epoch, state.current_sync_committee, active_pubkeys ) ensure_assignments_in_sync_committee( spec, state, next_query_epoch, state.next_sync_committee, active_pubkeys ) sync_committee_pubkeys = set( list(state.current_sync_committee.pubkeys) + list(state.next_sync_committee.pubkeys) ) disqualified_pubkeys = set( filter(lambda key: key not in sync_committee_pubkeys, active_pubkeys) ) # NOTE: only check `disqualified_pubkeys` if SYNC_COMMITTEE_SIZE < validator count if disqualified_pubkeys: sample_size = 3 assert validator_count >= sample_size some_pubkeys = rng.sample(sorted(disqualified_pubkeys), sample_size) for pubkey in some_pubkeys: validator_index = active_pubkeys.index(pubkey) is_current = spec.is_assigned_to_sync_committee( state, query_epoch, validator_index ) is_next = spec.is_assigned_to_sync_committee( state, next_query_epoch, validator_index ) is_current_or_next = is_current or is_next assert not is_current_or_next def _get_sync_committee_signature( spec, state, target_slot, target_block_root, subcommittee_index, index_in_subcommittee, ): subcommittee_size = spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT sync_committee_index = ( subcommittee_index * subcommittee_size + index_in_subcommittee ) pubkey = state.current_sync_committee.pubkeys[sync_committee_index] privkey = pubkey_to_privkey[pubkey] return compute_sync_committee_signature( spec, state, target_slot, privkey, block_root=target_block_root ) @with_altair_and_later @with_presets([MINIMAL], reason="too slow") @spec_state_test @always_bls def test_process_sync_committee_contributions(spec, state): # skip over slots at genesis transition_to(spec, state, state.slot + 3) # build a block and attempt to assemble a sync aggregate # from some sync committee contributions block = build_empty_block(spec, state) previous_slot = state.slot - 1 target_block_root = spec.get_block_root_at_slot(state, previous_slot) aggregation_bits = Bitvector[ spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT ]() aggregation_index = 0 aggregation_bits[aggregation_index] = True contributions = [ spec.SyncCommitteeContribution( slot=block.slot, beacon_block_root=target_block_root, subcommittee_index=i, aggregation_bits=aggregation_bits, signature=_get_sync_committee_signature( spec, state, previous_slot, target_block_root, i, aggregation_index ), ) for i in range(spec.SYNC_COMMITTEE_SUBNET_COUNT) ] # ensure the block has an empty sync aggregate... empty_sync_aggregate = spec.SyncAggregate() empty_sync_aggregate.sync_committee_signature = spec.G2_POINT_AT_INFINITY assert block.body.sync_aggregate == empty_sync_aggregate spec.process_sync_committee_contributions(block, set(contributions)) # and that after processing, it is no longer empty assert len(block.body.sync_aggregate.sync_committee_bits) != 0 assert ( block.body.sync_aggregate.sync_committee_signature != spec.G2_POINT_AT_INFINITY ) # moreover, ensure the sync aggregate is valid if the block is accepted spec.process_block(state, block) @with_altair_and_later @spec_state_test @always_bls def test_get_sync_committee_message(spec, state): validator_index = 0 block_root = spec.Root(b'\x12' * 32) sync_committee_message = spec.get_sync_committee_message( state=state, block_root=block_root, validator_index=validator_index, privkey=privkeys[validator_index], ) assert sync_committee_message.slot == state.slot assert sync_committee_message.beacon_block_root == block_root assert sync_committee_message.validator_index == validator_index epoch = spec.get_current_epoch(state) domain = spec.get_domain(state, spec.DOMAIN_SYNC_COMMITTEE, epoch) signing_root = spec.compute_signing_root(block_root, domain) signature = bls.Sign(privkeys[validator_index], signing_root) assert sync_committee_message.signature == signature def _validator_index_for_pubkey(state, pubkey): return list(map(lambda v: v.pubkey, state.validators)).index(pubkey) def _subnet_for_sync_committee_index(spec, i): return i // (spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT) def _get_expected_subnets_by_pubkey(sync_committee_members): # Build deduplicated set for each pubkey expected_subnets_by_pubkey = defaultdict(set) for (subnet, pubkey) in sync_committee_members: expected_subnets_by_pubkey[pubkey].add(subnet) return expected_subnets_by_pubkey @with_altair_and_later @with_presets([MINIMAL], reason="too slow") @spec_state_test def test_compute_subnets_for_sync_committee(state, spec): # Transition to the head of the next period transition_to(spec, state, spec.SLOTS_PER_EPOCH * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD) next_slot_epoch = spec.compute_epoch_at_slot(state.slot + 1) assert ( spec.compute_sync_committee_period(spec.get_current_epoch(state)) == spec.compute_sync_committee_period(next_slot_epoch) ) some_sync_committee_members = list( ( _subnet_for_sync_committee_index(spec, i), pubkey, ) # use current_sync_committee for i, pubkey in enumerate(state.current_sync_committee.pubkeys) ) expected_subnets_by_pubkey = _get_expected_subnets_by_pubkey(some_sync_committee_members) for _, pubkey in some_sync_committee_members: validator_index = _validator_index_for_pubkey(state, pubkey) subnets = spec.compute_subnets_for_sync_committee(state, validator_index) expected_subnets = expected_subnets_by_pubkey[pubkey] assert subnets == expected_subnets @with_altair_and_later @with_presets([MINIMAL], reason="too slow") @spec_state_test def test_compute_subnets_for_sync_committee_slot_period_boundary(state, spec): # Transition to the end of the period transition_to(spec, state, spec.SLOTS_PER_EPOCH * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD - 1) next_slot_epoch = spec.compute_epoch_at_slot(state.slot + 1) assert ( spec.compute_sync_committee_period(spec.get_current_epoch(state)) != spec.compute_sync_committee_period(next_slot_epoch) ) some_sync_committee_members = list( ( _subnet_for_sync_committee_index(spec, i), pubkey, ) # use next_sync_committee for i, pubkey in enumerate(state.next_sync_committee.pubkeys) ) expected_subnets_by_pubkey = _get_expected_subnets_by_pubkey(some_sync_committee_members) for _, pubkey in some_sync_committee_members: validator_index = _validator_index_for_pubkey(state, pubkey) subnets = spec.compute_subnets_for_sync_committee(state, validator_index) expected_subnets = expected_subnets_by_pubkey[pubkey] assert subnets == expected_subnets @with_altair_and_later @spec_state_test @always_bls def test_get_sync_committee_selection_proof(spec, state): slot = 1 subcommittee_index = 0 privkey = privkeys[1] sync_committee_selection_proof = spec.get_sync_committee_selection_proof( state, slot, subcommittee_index, privkey, ) domain = spec.get_domain(state, spec.DOMAIN_SYNC_COMMITTEE_SELECTION_PROOF, spec.compute_epoch_at_slot(slot)) signing_data = spec.SyncAggregatorSelectionData( slot=slot, subcommittee_index=subcommittee_index, ) signing_root = spec.compute_signing_root(signing_data, domain) pubkey = pubkeys[1] assert bls.Verify(pubkey, signing_root, sync_committee_selection_proof) @with_altair_and_later @spec_state_test @with_presets([MAINNET], reason="to test against the mainnet SYNC_COMMITTEE_SIZE") def test_is_sync_committee_aggregator(spec, state): sample_count = int(spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT) * 100 is_aggregator_count = 0 for i in range(sample_count): signature = spec.hash(i.to_bytes(32, byteorder="little")) if spec.is_sync_committee_aggregator(signature): is_aggregator_count += 1 # Accept ~10% deviation assert ( spec.TARGET_AGGREGATORS_PER_SYNC_SUBCOMMITTEE * 100 * 0.9 <= is_aggregator_count <= spec.TARGET_AGGREGATORS_PER_SYNC_SUBCOMMITTEE * 100 * 1.1 ) @with_altair_and_later @spec_state_test def test_get_contribution_and_proof(spec, state): aggregator_index = 10 privkey = privkeys[3] contribution = spec.SyncCommitteeContribution( slot=10, beacon_block_root=b'\x12' * 32, subcommittee_index=1, aggregation_bits=spec.Bitvector[spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT](), signature=b'\x32' * 96, ) selection_proof = spec.get_sync_committee_selection_proof( state, contribution.slot, contribution.subcommittee_index, privkey, ) contribution_and_proof = spec.get_contribution_and_proof( state, aggregator_index, contribution, privkey, ) assert contribution_and_proof == spec.ContributionAndProof( aggregator_index=aggregator_index, contribution=contribution, selection_proof=selection_proof, ) @with_altair_and_later @spec_state_test @always_bls def test_get_contribution_and_proof_signature(spec, state): privkey = privkeys[3] pubkey = pubkeys[3] contribution_and_proof = spec.ContributionAndProof( aggregator_index=10, contribution=spec.SyncCommitteeContribution( slot=10, beacon_block_root=b'\x12' * 32, subcommittee_index=1, aggregation_bits=spec.Bitvector[spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT](), signature=b'\x34' * 96, ), selection_proof=b'\x56' * 96, ) contribution_and_proof_signature = spec.get_contribution_and_proof_signature( state, contribution_and_proof, privkey, ) contribution = contribution_and_proof.contribution domain = spec.get_domain(state, spec.DOMAIN_CONTRIBUTION_AND_PROOF, spec.compute_epoch_at_slot(contribution.slot)) signing_root = spec.compute_signing_root(contribution_and_proof, domain) assert bls.Verify(pubkey, signing_root, contribution_and_proof_signature)
12,237
35.100295
118
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/validator/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/networking/test_networking.py
from eth2spec.test.context import ( spec_state_test, with_altair_and_later, ) from eth2spec.test.helpers.state import ( transition_to, ) @with_altair_and_later @spec_state_test def test_get_sync_subcommittee_pubkeys_current_sync_committee(state, spec): # Transition to the head of the next period transition_to(spec, state, spec.SLOTS_PER_EPOCH * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD) next_slot_epoch = spec.compute_epoch_at_slot(state.slot + 1) assert ( spec.compute_sync_committee_period(spec.get_current_epoch(state)) == spec.compute_sync_committee_period(next_slot_epoch) ) sync_committee = state.current_sync_committee sync_subcommittee_size = spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT subcommittee_index = 1 i = subcommittee_index * sync_subcommittee_size expect = sync_committee.pubkeys[i:i + sync_subcommittee_size] assert spec.get_sync_subcommittee_pubkeys(state, subcommittee_index) == expect @with_altair_and_later @spec_state_test def test_get_sync_subcommittee_pubkeys_next_sync_committee(state, spec): # Transition to the end of the current period transition_to(spec, state, spec.SLOTS_PER_EPOCH * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD - 1) next_slot_epoch = spec.compute_epoch_at_slot(state.slot + 1) assert ( spec.compute_sync_committee_period(spec.get_current_epoch(state)) != spec.compute_sync_committee_period(next_slot_epoch) ) sync_committee = state.next_sync_committee sync_subcommittee_size = spec.SYNC_COMMITTEE_SIZE // spec.SYNC_COMMITTEE_SUBNET_COUNT subcommittee_index = 1 i = subcommittee_index * sync_subcommittee_size expect = sync_committee.pubkeys[i:i + sync_subcommittee_size] assert spec.get_sync_subcommittee_pubkeys(state, subcommittee_index) == expect
1,849
37.541667
96
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/networking/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/light_client/test_sync_protocol.py
from copy import deepcopy from eth2spec.test.context import ( spec_state_test_with_matching_config, with_presets, with_light_client, ) from eth2spec.test.helpers.attestations import ( next_epoch_with_attestations, state_transition_with_full_block, ) from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.helpers.light_client import ( create_update, ) from eth2spec.test.helpers.state import ( next_slots, ) def setup_test(spec, state): trusted_block = spec.SignedBeaconBlock() trusted_block.message.state_root = state.hash_tree_root() trusted_block_root = trusted_block.message.hash_tree_root() bootstrap = spec.create_light_client_bootstrap(state, trusted_block) store = spec.initialize_light_client_store(trusted_block_root, bootstrap) store.next_sync_committee = state.next_sync_committee return (trusted_block, store) @with_light_client @spec_state_test_with_matching_config def test_process_light_client_update_not_timeout(spec, state): genesis_block, store = setup_test(spec, state) # Block at slot 1 doesn't increase sync committee period, so it won't force update store.finalized_header attested_block = state_transition_with_full_block(spec, state, False, False) signature_slot = state.slot + 1 # Ensure that finality checkpoint is genesis assert state.finalized_checkpoint.epoch == 0 update = create_update( spec, attested_state=state, attested_block=attested_block, finalized_block=genesis_block, with_next=False, with_finality=False, participation_rate=1.0, ) pre_store = deepcopy(store) spec.process_light_client_update(store, update, signature_slot, state.genesis_validators_root) assert store.finalized_header == pre_store.finalized_header assert store.best_valid_update == update assert store.optimistic_header == update.attested_header assert store.current_max_active_participants > 0 @with_light_client @spec_state_test_with_matching_config @with_presets([MINIMAL], reason="too slow") def test_process_light_client_update_at_period_boundary(spec, state): genesis_block, store = setup_test(spec, state) # Forward to slot before next sync committee period so that next block is final one in period next_slots(spec, state, spec.UPDATE_TIMEOUT - 2) store_period = spec.compute_sync_committee_period_at_slot(store.optimistic_header.beacon.slot) update_period = spec.compute_sync_committee_period_at_slot(state.slot) assert store_period == update_period attested_block = state_transition_with_full_block(spec, state, False, False) signature_slot = state.slot + 1 update = create_update( spec, attested_state=state, attested_block=attested_block, finalized_block=genesis_block, with_next=False, with_finality=False, participation_rate=1.0, ) pre_store = deepcopy(store) spec.process_light_client_update(store, update, signature_slot, state.genesis_validators_root) assert store.finalized_header == pre_store.finalized_header assert store.best_valid_update == update assert store.optimistic_header == update.attested_header assert store.current_max_active_participants > 0 @with_light_client @spec_state_test_with_matching_config @with_presets([MINIMAL], reason="too slow") def test_process_light_client_update_timeout(spec, state): genesis_block, store = setup_test(spec, state) # Forward to next sync committee period next_slots(spec, state, spec.UPDATE_TIMEOUT) store_period = spec.compute_sync_committee_period_at_slot(store.optimistic_header.beacon.slot) update_period = spec.compute_sync_committee_period_at_slot(state.slot) assert store_period + 1 == update_period attested_block = state_transition_with_full_block(spec, state, False, False) signature_slot = state.slot + 1 update = create_update( spec, attested_state=state, attested_block=attested_block, finalized_block=genesis_block, with_next=True, with_finality=False, participation_rate=1.0, ) pre_store = deepcopy(store) spec.process_light_client_update(store, update, signature_slot, state.genesis_validators_root) assert store.finalized_header == pre_store.finalized_header assert store.best_valid_update == update assert store.optimistic_header == update.attested_header assert store.current_max_active_participants > 0 @with_light_client @spec_state_test_with_matching_config @with_presets([MINIMAL], reason="too slow") def test_process_light_client_update_finality_updated(spec, state): _, store = setup_test(spec, state) # Change finality blocks = [] next_slots(spec, state, spec.SLOTS_PER_EPOCH * 2) for epoch in range(3): prev_state, new_blocks, state = next_epoch_with_attestations(spec, state, True, True) blocks += new_blocks # Ensure that finality checkpoint has changed assert state.finalized_checkpoint.epoch == 3 # Ensure that it's same period store_period = spec.compute_sync_committee_period_at_slot(store.optimistic_header.beacon.slot) update_period = spec.compute_sync_committee_period_at_slot(state.slot) assert store_period == update_period attested_block = blocks[-1] signature_slot = state.slot + 1 # Updated finality finalized_block = blocks[spec.SLOTS_PER_EPOCH - 1] assert finalized_block.message.slot == spec.compute_start_slot_at_epoch(state.finalized_checkpoint.epoch) assert finalized_block.message.hash_tree_root() == state.finalized_checkpoint.root update = create_update( spec, attested_state=state, attested_block=attested_block, finalized_block=finalized_block, with_next=False, with_finality=True, participation_rate=1.0, ) spec.process_light_client_update(store, update, signature_slot, state.genesis_validators_root) assert store.finalized_header == update.finalized_header assert store.best_valid_update is None assert store.optimistic_header == update.attested_header assert store.current_max_active_participants > 0
6,261
34.378531
109
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/unittests/light_client/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/epoch_processing/test_process_inactivity_updates.py
from random import Random from eth2spec.test.context import spec_state_test, with_altair_and_later from eth2spec.test.helpers.inactivity_scores import ( randomize_inactivity_scores, zero_inactivity_scores, ) from eth2spec.test.helpers.state import ( next_epoch, next_epoch_via_block, set_full_participation, set_empty_participation, ) from eth2spec.test.helpers.voluntary_exits import ( exit_validators, get_exited_validators ) from eth2spec.test.helpers.epoch_processing import ( run_epoch_processing_with ) from eth2spec.test.helpers.random import ( randomize_attestation_participation, randomize_previous_epoch_participation, randomize_state, ) from eth2spec.test.helpers.rewards import leaking def run_process_inactivity_updates(spec, state): yield from run_epoch_processing_with(spec, state, 'process_inactivity_updates') @with_altair_and_later @spec_state_test def test_genesis(spec, state): yield from run_process_inactivity_updates(spec, state) @with_altair_and_later @spec_state_test def test_genesis_random_scores(spec, state): rng = Random(10102) state.inactivity_scores = [rng.randint(0, 100) for _ in state.inactivity_scores] pre_scores = state.inactivity_scores.copy() yield from run_process_inactivity_updates(spec, state) assert state.inactivity_scores == pre_scores # # Genesis epoch processing is skipped # Thus all of following tests all go past genesis epoch to test core functionality # def run_inactivity_scores_test(spec, state, participation_fn=None, inactivity_scores_fn=None, rng=Random(10101)): while True: try: next_epoch_via_block(spec, state) except AssertionError: # If the proposer is slashed, we skip this epoch and try to propose block at the next epoch next_epoch(spec, state) else: break if participation_fn is not None: participation_fn(spec, state, rng=rng) if inactivity_scores_fn is not None: inactivity_scores_fn(spec, state, rng=rng) yield from run_process_inactivity_updates(spec, state) @with_altair_and_later @spec_state_test def test_all_zero_inactivity_scores_empty_participation(spec, state): yield from run_inactivity_scores_test(spec, state, set_empty_participation, zero_inactivity_scores) assert set(state.inactivity_scores) == set([0]) @with_altair_and_later @spec_state_test @leaking() def test_all_zero_inactivity_scores_empty_participation_leaking(spec, state): yield from run_inactivity_scores_test(spec, state, set_empty_participation, zero_inactivity_scores) # Should still in be leak assert spec.is_in_inactivity_leak(state) for score in state.inactivity_scores: assert score > 0 @with_altair_and_later @spec_state_test def test_all_zero_inactivity_scores_random_participation(spec, state): yield from run_inactivity_scores_test( spec, state, randomize_attestation_participation, zero_inactivity_scores, rng=Random(5555), ) assert set(state.inactivity_scores) == set([0]) @with_altair_and_later @spec_state_test @leaking() def test_all_zero_inactivity_scores_random_participation_leaking(spec, state): # Only randomize participation in previous epoch to remain in leak yield from run_inactivity_scores_test( spec, state, randomize_previous_epoch_participation, zero_inactivity_scores, rng=Random(5555), ) # Check still in leak assert spec.is_in_inactivity_leak(state) assert 0 in state.inactivity_scores assert len(set(state.inactivity_scores)) > 1 @with_altair_and_later @spec_state_test def test_all_zero_inactivity_scores_full_participation(spec, state): yield from run_inactivity_scores_test( spec, state, set_full_participation, zero_inactivity_scores, ) assert set(state.inactivity_scores) == set([0]) @with_altair_and_later @spec_state_test @leaking() def test_all_zero_inactivity_scores_full_participation_leaking(spec, state): # Only set full participation in previous epoch to remain in leak yield from run_inactivity_scores_test( spec, state, set_full_participation, zero_inactivity_scores, ) # Check still in leak assert spec.is_in_inactivity_leak(state) assert set(state.inactivity_scores) == set([0]) @with_altair_and_later @spec_state_test def test_random_inactivity_scores_empty_participation(spec, state): yield from run_inactivity_scores_test( spec, state, set_empty_participation, randomize_inactivity_scores, Random(9999), ) @with_altair_and_later @spec_state_test @leaking() def test_random_inactivity_scores_empty_participation_leaking(spec, state): yield from run_inactivity_scores_test( spec, state, set_empty_participation, randomize_inactivity_scores, Random(9999), ) # Check still in leak assert spec.is_in_inactivity_leak(state) @with_altair_and_later @spec_state_test def test_random_inactivity_scores_random_participation(spec, state): yield from run_inactivity_scores_test( spec, state, randomize_attestation_participation, randomize_inactivity_scores, Random(22222), ) @with_altair_and_later @spec_state_test @leaking() def test_random_inactivity_scores_random_participation_leaking(spec, state): # Only randompize participation in previous epoch to remain in leak yield from run_inactivity_scores_test( spec, state, randomize_previous_epoch_participation, randomize_inactivity_scores, Random(22222), ) # Check still in leak assert spec.is_in_inactivity_leak(state) @with_altair_and_later @spec_state_test def test_random_inactivity_scores_full_participation(spec, state): yield from run_inactivity_scores_test( spec, state, set_full_participation, randomize_inactivity_scores, Random(33333), ) @with_altair_and_later @spec_state_test @leaking() def test_random_inactivity_scores_full_participation_leaking(spec, state): # Only set full participation in previous epoch to remain in leak yield from run_inactivity_scores_test( spec, state, set_full_participation, randomize_inactivity_scores, Random(33333), ) # Check still in leak assert spec.is_in_inactivity_leak(state) def slash_some_validators_for_inactivity_scores_test(spec, state, rng=Random(40404040)): # ``run_inactivity_scores_test`` runs at the next epoch from `state`. # We retrieve the proposer of this future state to avoid # accidentally slashing that validator future_state = state.copy() next_epoch_via_block(spec, future_state) proposer_index = spec.get_beacon_proposer_index(future_state) # Slash ~1/4 of validators for validator_index in range(len(state.validators)): if rng.choice(range(4)) == 0 and validator_index != proposer_index: spec.slash_validator(state, validator_index) @with_altair_and_later @spec_state_test def test_some_slashed_zero_scores_full_participation(spec, state): slash_some_validators_for_inactivity_scores_test(spec, state, rng=Random(33429)) yield from run_inactivity_scores_test( spec, state, set_full_participation, zero_inactivity_scores, ) assert set(state.inactivity_scores) == set([0]) @with_altair_and_later @spec_state_test @leaking() def test_some_slashed_zero_scores_full_participation_leaking(spec, state): slash_some_validators_for_inactivity_scores_test(spec, state, rng=Random(332243)) yield from run_inactivity_scores_test( spec, state, set_full_participation, zero_inactivity_scores, ) # Check still in leak assert spec.is_in_inactivity_leak(state) # Ensure some zero scores (non-slashed values) and non-zero scores (slashed vals) in there for score, validator in zip(state.inactivity_scores, state.validators): if validator.slashed: assert score > 0 else: assert score == 0 @with_altair_and_later @spec_state_test def test_some_slashed_full_random(spec, state): rng = Random(1010222) slash_some_validators_for_inactivity_scores_test(spec, state, rng=rng) yield from run_inactivity_scores_test( spec, state, randomize_attestation_participation, randomize_inactivity_scores, rng=rng, ) @with_altair_and_later @spec_state_test @leaking() def test_some_slashed_full_random_leaking(spec, state): rng = Random(1102233) slash_some_validators_for_inactivity_scores_test(spec, state, rng=rng) yield from run_inactivity_scores_test( spec, state, randomize_previous_epoch_participation, randomize_inactivity_scores, rng=rng, ) # Check still in leak assert spec.is_in_inactivity_leak(state) @with_altair_and_later @spec_state_test @leaking() def test_some_exited_full_random_leaking(spec, state): rng = Random(1102233) exit_count = 3 # randomize ahead of time to check exited validators do not have # mutations applied to their inactivity scores randomize_inactivity_scores(spec, state, rng=rng) assert not any(get_exited_validators(spec, state)) exited_indices = exit_validators(spec, state, exit_count, rng=rng) assert not any(get_exited_validators(spec, state)) # advance the state to effect the exits target_epoch = max(state.validators[index].exit_epoch for index in exited_indices) # validators that have exited in the previous epoch or earlier will not # have their inactivity scores modified, the test advances the state past this point # to confirm this invariant: previous_epoch = spec.get_previous_epoch(state) for _ in range(target_epoch - previous_epoch): next_epoch(spec, state) assert len(get_exited_validators(spec, state)) == exit_count previous_scores = state.inactivity_scores.copy() yield from run_inactivity_scores_test( spec, state, randomize_previous_epoch_participation, rng=rng, ) # ensure exited validators have their score "frozen" at exit # but otherwise there was a change some_changed = False for index in range(len(state.validators)): if index in exited_indices: assert previous_scores[index] == state.inactivity_scores[index] else: previous_score = previous_scores[index] current_score = state.inactivity_scores[index] if previous_score != current_score: some_changed = True assert some_changed # Check still in leak assert spec.is_in_inactivity_leak(state) def _run_randomized_state_test_for_inactivity_updates(spec, state, rng=Random(13377331)): randomize_inactivity_scores(spec, state, rng=rng) randomize_state(spec, state, rng=rng) exited_validators = get_exited_validators(spec, state) exited_but_not_slashed = [] for index in exited_validators: validator = state.validators[index] if validator.slashed: continue exited_but_not_slashed.append(index) assert len(exited_but_not_slashed) > 0 some_exited_validator = exited_but_not_slashed[0] pre_score_for_exited_validator = state.inactivity_scores[some_exited_validator] assert pre_score_for_exited_validator != 0 assert len(set(state.inactivity_scores)) > 1 yield from run_inactivity_scores_test(spec, state) post_score_for_exited_validator = state.inactivity_scores[some_exited_validator] assert pre_score_for_exited_validator == post_score_for_exited_validator @with_altair_and_later @spec_state_test def test_randomized_state(spec, state): """ This test ensures that once a validator has exited, their inactivity score does not change. """ rng = Random(10011001) yield from _run_randomized_state_test_for_inactivity_updates(spec, state, rng=rng) @with_altair_and_later @spec_state_test @leaking() def test_randomized_state_leaking(spec, state): """ This test ensures that once a validator has exited, their inactivity score does not change, even during a leak. Note that slashed validators are still subject to mutations (refer ``get_eligible_validator_indices`). """ rng = Random(10011002) yield from _run_randomized_state_test_for_inactivity_updates(spec, state, rng=rng) # Check still in leak assert spec.is_in_inactivity_leak(state)
12,434
30.803069
113
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/epoch_processing/test_process_sync_committee_updates.py
from eth2spec.test.context import ( always_bls, spec_state_test, spec_test, with_altair_and_later, with_presets, with_custom_state, single_phase, misc_balances, ) from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.helpers.state import transition_to from eth2spec.test.helpers.epoch_processing import ( run_epoch_processing_with, ) # # Note: # Calculating sync committees requires pubkey aggregation, thus all tests are generated with `always_bls` # def run_sync_committees_progress_test(spec, state): first_sync_committee = state.current_sync_committee.copy() second_sync_committee = state.next_sync_committee.copy() current_period = spec.compute_sync_committee_period(spec.get_current_epoch(state)) next_period = current_period + 1 next_period_start_epoch = next_period * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD next_period_start_slot = next_period_start_epoch * spec.SLOTS_PER_EPOCH end_slot_of_current_period = next_period_start_slot - 1 transition_to(spec, state, end_slot_of_current_period) # Ensure assignments have not changed: assert state.current_sync_committee == first_sync_committee assert state.next_sync_committee == second_sync_committee yield from run_epoch_processing_with(spec, state, 'process_sync_committee_updates') # Can compute the third committee having computed final balances in the last epoch # of this `EPOCHS_PER_SYNC_COMMITTEE_PERIOD` third_sync_committee = spec.get_next_sync_committee(state) # Ensure assignments have changed: assert state.next_sync_committee != second_sync_committee if current_period > 0: assert state.current_sync_committee != first_sync_committee else: # Current and next are duplicated in genesis period so remain stable assert state.current_sync_committee == first_sync_committee # Ensure expected committees were calculated assert state.current_sync_committee == second_sync_committee assert state.next_sync_committee == third_sync_committee @with_altair_and_later @spec_state_test @always_bls @with_presets([MINIMAL], reason="too slow") def test_sync_committees_progress_genesis(spec, state): # Genesis epoch period has an exceptional case assert spec.get_current_epoch(state) == spec.GENESIS_EPOCH yield from run_sync_committees_progress_test(spec, state) @with_altair_and_later @spec_state_test @always_bls @with_presets([MINIMAL], reason="too slow") def test_sync_committees_progress_not_genesis(spec, state): # Transition out of the genesis epoch period to test non-exceptional case assert spec.get_current_epoch(state) == spec.GENESIS_EPOCH slot_in_next_period = state.slot + spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH transition_to(spec, state, slot_in_next_period) yield from run_sync_committees_progress_test(spec, state) @with_altair_and_later @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase @always_bls @with_presets([MINIMAL], reason="too slow") def test_sync_committees_progress_misc_balances_genesis(spec, state): # Genesis epoch period has an exceptional case assert spec.get_current_epoch(state) == spec.GENESIS_EPOCH yield from run_sync_committees_progress_test(spec, state) @with_altair_and_later @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase @always_bls @with_presets([MINIMAL], reason="too slow") def test_sync_committees_progress_misc_balances_not_genesis(spec, state): # Transition out of the genesis epoch period to test non-exceptional case assert spec.get_current_epoch(state) == spec.GENESIS_EPOCH slot_in_next_period = state.slot + spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH transition_to(spec, state, slot_in_next_period) yield from run_sync_committees_progress_test(spec, state) @with_altair_and_later @spec_state_test @always_bls @with_presets([MINIMAL], reason="too slow") def test_sync_committees_no_progress_not_at_period_boundary(spec, state): assert spec.get_current_epoch(state) == spec.GENESIS_EPOCH slot_not_at_period_boundary = state.slot + spec.SLOTS_PER_EPOCH transition_to(spec, state, slot_not_at_period_boundary) first_sync_committee = state.current_sync_committee.copy() second_sync_committee = state.next_sync_committee.copy() yield from run_epoch_processing_with(spec, state, 'process_sync_committee_updates') # Ensure assignments have not changed: assert state.current_sync_committee == first_sync_committee assert state.next_sync_committee == second_sync_committee
4,758
36.769841
105
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/epoch_processing/test_process_participation_flag_updates.py
from random import Random from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.context import ( with_altair_and_later, with_custom_state, spec_test, spec_state_test, with_presets, single_phase, ) from eth2spec.test.helpers.state import next_epoch_via_block from eth2spec.test.helpers.epoch_processing import run_epoch_processing_with def get_full_flags(spec): full_flags = spec.ParticipationFlags(0) for flag_index in range(len(spec.PARTICIPATION_FLAG_WEIGHTS)): full_flags = spec.add_flag(full_flags, flag_index) return full_flags def run_process_participation_flag_updates(spec, state): old = state.current_epoch_participation.copy() yield from run_epoch_processing_with(spec, state, 'process_participation_flag_updates') assert state.current_epoch_participation == [0] * len(state.validators) assert state.previous_epoch_participation == old @with_altair_and_later @spec_state_test def test_all_zeroed(spec, state): next_epoch_via_block(spec, state) state.current_epoch_participation = [0] * len(state.validators) state.previous_epoch_participation = [0] * len(state.validators) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_filled(spec, state): next_epoch_via_block(spec, state) state.previous_epoch_participation = [get_full_flags(spec)] * len(state.validators) state.current_epoch_participation = [get_full_flags(spec)] * len(state.validators) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_previous_filled(spec, state): next_epoch_via_block(spec, state) state.previous_epoch_participation = [get_full_flags(spec)] * len(state.validators) state.current_epoch_participation = [0] * len(state.validators) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_current_filled(spec, state): next_epoch_via_block(spec, state) state.previous_epoch_participation = [0] * len(state.validators) state.current_epoch_participation = [get_full_flags(spec)] * len(state.validators) yield from run_process_participation_flag_updates(spec, state) def random_flags(spec, state, seed: int, previous=True, current=True): rng = Random(seed) count = len(state.validators) max_flag_value_excl = 2**len(spec.PARTICIPATION_FLAG_WEIGHTS) if previous: state.previous_epoch_participation = [rng.randrange(0, max_flag_value_excl) for _ in range(count)] if current: state.current_epoch_participation = [rng.randrange(0, max_flag_value_excl) for _ in range(count)] @with_altair_and_later @spec_state_test def test_random_0(spec, state): next_epoch_via_block(spec, state) random_flags(spec, state, 100) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_random_1(spec, state): next_epoch_via_block(spec, state) random_flags(spec, state, 101) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_random_2(spec, state): next_epoch_via_block(spec, state) random_flags(spec, state, 102) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_random_genesis(spec, state): random_flags(spec, state, 11) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_current_epoch_zeroed(spec, state): next_epoch_via_block(spec, state) random_flags(spec, state, 12, current=False) state.current_epoch_participation = [0] * len(state.validators) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @spec_state_test def test_previous_epoch_zeroed(spec, state): next_epoch_via_block(spec, state) random_flags(spec, state, 13, previous=False) state.previous_epoch_participation = [0] * len(state.validators) yield from run_process_participation_flag_updates(spec, state) def custom_validator_count(factor: float): def initializer(spec): num_validators = spec.SLOTS_PER_EPOCH * spec.MAX_COMMITTEES_PER_SLOT * spec.TARGET_COMMITTEE_SIZE return [spec.MAX_EFFECTIVE_BALANCE] * int(float(int(num_validators)) * factor) return initializer @with_altair_and_later @with_presets([MINIMAL], reason="mainnet config requires too many pre-generated public/private keys") @spec_test @with_custom_state(balances_fn=custom_validator_count(1.3), threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @single_phase def test_slightly_larger_random(spec, state): next_epoch_via_block(spec, state) random_flags(spec, state, 14) yield from run_process_participation_flag_updates(spec, state) @with_altair_and_later @with_presets([MINIMAL], reason="mainnet config requires too many pre-generated public/private keys") @spec_test @with_custom_state(balances_fn=custom_validator_count(2.6), threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @single_phase def test_large_random(spec, state): next_epoch_via_block(spec, state) random_flags(spec, state, 15) yield from run_process_participation_flag_updates(spec, state)
5,351
33.089172
115
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/epoch_processing/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/transition/test_leaking.py
from eth2spec.test.context import ( ForkMeta, with_fork_metas, ) from eth2spec.test.helpers.constants import ( ALL_PRE_POST_FORKS, ) from eth2spec.test.helpers.fork_transition import ( do_fork, transition_until_fork, transition_to_next_epoch_and_append_blocks, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=7) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_leaking_pre_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Leaking starts at epoch 6 (MIN_EPOCHS_TO_INACTIVITY_PENALTY + 2). The leaking starts before the fork transition in this case. """ transition_until_fork(spec, state, fork_epoch) assert spec.is_in_inactivity_leak(state) assert spec.get_current_epoch(state) < fork_epoch yield "pre", state # irregular state transition to handle fork: blocks = [] state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # check post transition state assert spec.is_in_inactivity_leak(state) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks, only_last_block=True) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=6) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_leaking_at_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Leaking starts at epoch 6 (MIN_EPOCHS_TO_INACTIVITY_PENALTY + 2). The leaking starts at the fork transition in this case. """ transition_until_fork(spec, state, fork_epoch) assert not spec.is_in_inactivity_leak(state) assert spec.get_current_epoch(state) < fork_epoch yield "pre", state # irregular state transition to handle fork: blocks = [] state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # check post transition state assert spec.is_in_inactivity_leak(state) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks, only_last_block=True) yield "blocks", blocks yield "post", state
2,318
32.608696
118
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/transition/test_activations_and_exits.py
import random from eth2spec.test.context import ( ForkMeta, ALTAIR, with_presets, with_fork_metas, ) from eth2spec.test.helpers.constants import ( ALL_PRE_POST_FORKS, MINIMAL, ) from eth2spec.test.helpers.fork_transition import ( do_fork, transition_until_fork, transition_to_next_epoch_and_append_blocks, ) from eth2spec.test.helpers.random import ( exit_random_validators, set_some_activations, set_some_new_deposits, ) # # Exit # @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) @with_presets([MINIMAL], reason="only test with enough validators such that at least one exited index is not in sync committee") def test_transition_with_one_fourth_exiting_validators_exit_post_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ 1/4 validators initiated voluntary exit before the fork, and are exiting but still active *after* the fork transition. """ exited_indices = exit_random_validators( spec, state, rng=random.Random(5566), fraction=0.25, exit_epoch=10, from_epoch=spec.get_current_epoch(state), ) transition_until_fork(spec, state, fork_epoch) # check pre state assert len(exited_indices) > 0 for index in exited_indices: validator = state.validators[index] assert not validator.slashed assert fork_epoch < validator.exit_epoch < spec.FAR_FUTURE_EPOCH assert spec.is_active_validator(validator, spec.get_current_epoch(state)) assert not spec.is_in_inactivity_leak(state) assert spec.get_current_epoch(state) < fork_epoch yield "pre", state # irregular state transition to handle fork: blocks = [] state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # ensure that some of the current sync committee members are exiting exited_pubkeys = [state.validators[index].pubkey for index in exited_indices] assert any(set(exited_pubkeys).intersection(list(state.current_sync_committee.pubkeys))) assert any(set(exited_pubkeys).difference(list(state.current_sync_committee.pubkeys))) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks, only_last_block=True) # check state for index in exited_indices: validator = state.validators[index] assert not validator.slashed assert post_spec.is_active_validator(validator, post_spec.get_current_epoch(state)) assert not post_spec.is_in_inactivity_leak(state) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_one_fourth_exiting_validators_exit_at_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ 1/4 validators initiated voluntary exit before the fork, and being exited and inactive *right after* the fork transition. """ exited_indices = exit_random_validators( spec, state, rng=random.Random(5566), fraction=0.25, exit_epoch=fork_epoch, from_epoch=spec.get_current_epoch(state), ) transition_until_fork(spec, state, fork_epoch) # check pre state assert len(exited_indices) > 0 for index in exited_indices: validator = state.validators[index] assert not validator.slashed assert fork_epoch == validator.exit_epoch < spec.FAR_FUTURE_EPOCH assert spec.is_active_validator(validator, spec.get_current_epoch(state)) assert not spec.is_in_inactivity_leak(state) assert spec.get_current_epoch(state) < fork_epoch yield "pre", state # irregular state transition to handle fork: blocks = [] state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # check post transition state for index in exited_indices: validator = state.validators[index] assert not validator.slashed assert not post_spec.is_active_validator(validator, post_spec.get_current_epoch(state)) assert not post_spec.is_in_inactivity_leak(state) exited_pubkeys = [state.validators[index].pubkey for index in exited_indices] some_sync_committee_exited = any(set(exited_pubkeys).intersection(list(state.current_sync_committee.pubkeys))) if post_spec.fork == ALTAIR: # in Altair fork, the sync committee members would be set with only active validators assert not some_sync_committee_exited else: assert some_sync_committee_exited # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks, only_last_block=True) yield "blocks", blocks yield "post", state # # Activation # @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_non_empty_activation_queue(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create some deposits before the transition """ transition_until_fork(spec, state, fork_epoch) deposited_indices = set_some_new_deposits(spec, state, rng=random.Random(5566)) assert spec.get_current_epoch(state) < fork_epoch assert len(deposited_indices) > 0 for validator_index in deposited_indices: assert not spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) yield "pre", state # irregular state transition to handle fork: blocks = [] state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks, only_last_block=True) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_activation_at_fork_epoch(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create some deposits before the transition """ transition_until_fork(spec, state, fork_epoch) selected_indices = set_some_activations(spec, state, rng=random.Random(5566), activation_epoch=fork_epoch) assert spec.get_current_epoch(state) < fork_epoch assert len(selected_indices) > 0 for validator_index in selected_indices: validator = state.validators[validator_index] assert not spec.is_active_validator(validator, spec.get_current_epoch(state)) assert validator.activation_epoch == fork_epoch yield "pre", state # irregular state transition to handle fork: blocks = [] state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks, only_last_block=True) # now they are active for validator_index in selected_indices: validator = state.validators[validator_index] assert post_spec.is_active_validator(validator, post_spec.get_current_epoch(state)) yield "blocks", blocks yield "post", state
8,192
37.106977
118
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/transition/test_slashing.py
import random from eth2spec.test.context import ( ForkMeta, with_fork_metas, with_presets, ) from eth2spec.test.helpers.constants import ( ALL_PRE_POST_FORKS, MINIMAL, ) from eth2spec.test.helpers.fork_transition import ( do_fork, transition_to_next_epoch_and_append_blocks, transition_until_fork, ) from eth2spec.test.helpers.random import ( slash_random_validators, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=1) for pre, post in ALL_PRE_POST_FORKS]) @with_presets([MINIMAL], reason="only test with enough validators such that at least one exited index is not in sync committee") def test_transition_with_one_fourth_slashed_active_validators_pre_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ 1/4 validators are slashed but still active at the fork transition. """ # slash 1/4 validators slashed_indices = slash_random_validators(spec, state, rng=random.Random(5566), fraction=0.25) assert len(slashed_indices) > 0 # check if some validators are slashed but still active for validator_index in slashed_indices: validator = state.validators[validator_index] assert validator.slashed assert spec.is_active_validator(validator, spec.get_current_epoch(state)) assert not spec.is_in_inactivity_leak(state) transition_until_fork(spec, state, fork_epoch) assert spec.get_current_epoch(state) < fork_epoch yield "pre", state # irregular state transition to handle fork: state, _ = do_fork(state, spec, post_spec, fork_epoch, with_block=False) # ensure that some of the current sync committee members are slashed slashed_pubkeys = [state.validators[index].pubkey for index in slashed_indices] assert any(set(slashed_pubkeys).intersection(list(state.current_sync_committee.pubkeys))) assert any(set(slashed_pubkeys).difference(list(state.current_sync_committee.pubkeys))) # continue regular state transition with new spec into next epoch # since the proposer might have been slashed, here we only create blocks with non-slashed proposers blocks = [] transition_to_next_epoch_and_append_blocks( post_spec, state, post_tag, blocks, only_last_block=True, ignoring_proposers=slashed_indices, ) # check post state for validator in state.validators: assert post_spec.is_active_validator(validator, post_spec.get_current_epoch(state)) assert not post_spec.is_in_inactivity_leak(state) yield "blocks", blocks yield "post", state
2,975
37.649351
118
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/transition/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/transition/test_operations.py
from eth2spec.test.context import ( ForkMeta, always_bls, with_fork_metas, with_presets, ) from eth2spec.test.helpers.constants import ( ALL_PRE_POST_FORKS, MINIMAL, ) from eth2spec.test.helpers.fork_transition import ( OperationType, run_transition_with_operation, ) # # PROPOSER_SLASHING # @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) @always_bls def test_transition_with_proposer_slashing_right_after_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create an attester slashing right *after* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.PROPOSER_SLASHING, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) @always_bls def test_transition_with_proposer_slashing_right_before_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create an attester slashing right *before* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.PROPOSER_SLASHING, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH - 1, ) # # ATTESTER_SLASHING # @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) @always_bls def test_transition_with_attester_slashing_right_after_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create an attester slashing right *after* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.ATTESTER_SLASHING, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) @always_bls def test_transition_with_attester_slashing_right_before_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create an attester slashing right *after* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.ATTESTER_SLASHING, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH - 1, ) # # DEPOSIT # @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_deposit_right_after_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create a deposit right *after* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.DEPOSIT, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_deposit_right_before_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create a deposit right *before* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.DEPOSIT, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH - 1, ) # # VOLUNTARY_EXIT # @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=66) for pre, post in ALL_PRE_POST_FORKS]) @with_presets([MINIMAL], reason="too slow") def test_transition_with_voluntary_exit_right_after_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create a voluntary exit right *after* the transition. fork_epoch=66 because minimal preset `SHARD_COMMITTEE_PERIOD` is 64 epochs. """ # Fast forward to the future epoch so that validator can do voluntary exit state.slot = spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.VOLUNTARY_EXIT, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=66) for pre, post in ALL_PRE_POST_FORKS]) @with_presets([MINIMAL], reason="too slow") def test_transition_with_voluntary_exit_right_before_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create a voluntary exit right *before* the transition. fork_epoch=66 because minimal preset `SHARD_COMMITTEE_PERIOD` is 64 epochs. """ # Fast forward to the future epoch so that validator can do voluntary exit state.slot = spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.VOLUNTARY_EXIT, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH - 1, )
5,629
29.597826
119
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/transition/test_transition.py
import random from eth2spec.test.context import ( ForkMeta, with_fork_metas, ) from eth2spec.test.helpers.random import ( randomize_state, ) from eth2spec.test.helpers.constants import ( ALL_PRE_POST_FORKS, ) from eth2spec.test.helpers.state import ( next_epoch_via_signed_block, ) from eth2spec.test.helpers.attestations import next_slots_with_attestations from eth2spec.test.helpers.fork_transition import ( do_fork, no_blocks, only_at, skip_slots, state_transition_across_slots, transition_to_next_epoch_and_append_blocks, transition_until_fork, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_simple_transition(state, fork_epoch, spec, post_spec, pre_tag, post_tag): transition_until_fork(spec, state, fork_epoch) # check pre state assert spec.get_current_epoch(state) < fork_epoch yield "pre", state # irregular state transition to handle fork: blocks = [] state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks, only_last_block=True) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_normal_transition(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Transition from the initial ``state`` to the epoch after the ``fork_epoch``, producing blocks for every slot along the way. """ yield "pre", state assert spec.get_current_epoch(state) < fork_epoch # regular state transition until fork: to_slot = fork_epoch * spec.SLOTS_PER_EPOCH - 1 blocks = [] blocks.extend([ pre_tag(block) for block in state_transition_across_slots(spec, state, to_slot) ]) # irregular state transition to handle fork: state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks) assert state.slot % post_spec.SLOTS_PER_EPOCH == 0 assert post_spec.get_current_epoch(state) == fork_epoch + 1 slots_with_blocks = [block.message.slot for block in blocks] assert len(set(slots_with_blocks)) == len(slots_with_blocks) assert set(range(1, state.slot + 1)) == set(slots_with_blocks) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=8) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_randomized_state(state, fork_epoch, spec, post_spec, pre_tag, post_tag): randomize_state(spec, state) transition_until_fork(spec, state, fork_epoch) # check pre state assert spec.get_current_epoch(state) < fork_epoch yield "pre", state # irregular state transition to handle fork: blocks = [] # since there are slashed validators, set with_block=False here state, _ = do_fork(state, spec, post_spec, fork_epoch, with_block=False) slashed_indices = [index for index, validator in enumerate(state.validators) if validator.slashed] # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks( post_spec, state, post_tag, blocks, only_last_block=True, ignoring_proposers=slashed_indices, ) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_missing_first_post_block(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Transition from the initial ``state`` to the epoch after the ``fork_epoch``, producing blocks for every slot along the way except for the first block of the new fork. """ yield "pre", state assert spec.get_current_epoch(state) < fork_epoch # regular state transition until fork: to_slot = fork_epoch * spec.SLOTS_PER_EPOCH - 1 blocks = [] blocks.extend([ pre_tag(block) for block in state_transition_across_slots(spec, state, to_slot) ]) # irregular state transition to handle fork: state, _ = do_fork(state, spec, post_spec, fork_epoch, with_block=False) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks) assert state.slot % post_spec.SLOTS_PER_EPOCH == 0 assert post_spec.get_current_epoch(state) == fork_epoch + 1 slots_with_blocks = [block.message.slot for block in blocks] assert len(set(slots_with_blocks)) == len(slots_with_blocks) expected_slots = set(range(1, state.slot + 1)).difference(set([fork_epoch * spec.SLOTS_PER_EPOCH])) assert expected_slots == set(slots_with_blocks) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_missing_last_pre_fork_block(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Transition from the initial ``state`` to the epoch after the ``fork_epoch``, producing blocks for every slot along the way except for the last block of the old fork. """ yield "pre", state assert spec.get_current_epoch(state) < fork_epoch # regular state transition until fork: last_slot_of_pre_fork = fork_epoch * spec.SLOTS_PER_EPOCH - 1 to_slot = last_slot_of_pre_fork blocks = [] blocks.extend([ pre_tag(block) for block in state_transition_across_slots(spec, state, to_slot, block_filter=skip_slots(last_slot_of_pre_fork)) ]) # irregular state transition to handle fork: state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # continue regular state transition with new spec into next epoch transition_to_next_epoch_and_append_blocks(post_spec, state, post_tag, blocks) assert state.slot % post_spec.SLOTS_PER_EPOCH == 0 assert post_spec.get_current_epoch(state) == fork_epoch + 1 slots_with_blocks = [block.message.slot for block in blocks] assert len(set(slots_with_blocks)) == len(slots_with_blocks) expected_slots = set(range(1, state.slot + 1)).difference(set([last_slot_of_pre_fork])) assert expected_slots == set(slots_with_blocks) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_only_blocks_post_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Transition from the initial ``state`` to the epoch after the ``fork_epoch``, skipping blocks for every slot along the way except for the first block in the ending epoch. """ yield "pre", state assert spec.get_current_epoch(state) < fork_epoch # regular state transition until fork: last_slot_of_pre_fork = fork_epoch * spec.SLOTS_PER_EPOCH - 1 to_slot = last_slot_of_pre_fork blocks = [] blocks.extend([ pre_tag(block) for block in state_transition_across_slots(spec, state, to_slot, block_filter=no_blocks) ]) # irregular state transition to handle fork: state, _ = do_fork(state, spec, post_spec, fork_epoch, with_block=False) # continue regular state transition with new spec into next epoch to_slot = post_spec.SLOTS_PER_EPOCH + state.slot last_slot = (fork_epoch + 1) * post_spec.SLOTS_PER_EPOCH blocks.extend([ post_tag(block) for block in state_transition_across_slots(post_spec, state, to_slot, block_filter=only_at(last_slot)) ]) assert state.slot % post_spec.SLOTS_PER_EPOCH == 0 assert post_spec.get_current_epoch(state) == fork_epoch + 1 slots_with_blocks = [block.message.slot for block in blocks] assert len(slots_with_blocks) == 1 assert slots_with_blocks[0] == last_slot yield "blocks", blocks yield "post", state def _run_transition_test_with_attestations(state, fork_epoch, spec, post_spec, pre_tag, post_tag, participation_fn=None, expect_finality=True): yield "pre", state current_epoch = spec.get_current_epoch(state) assert current_epoch < fork_epoch assert current_epoch == spec.GENESIS_EPOCH # skip genesis epoch to avoid dealing with some edge cases... block = next_epoch_via_signed_block(spec, state) # regular state transition until fork: fill_cur_epoch = False fill_prev_epoch = True blocks = [pre_tag(block)] current_epoch = spec.get_current_epoch(state) for _ in range(current_epoch, fork_epoch - 1): _, blocks_in_epoch, state = next_slots_with_attestations( spec, state, spec.SLOTS_PER_EPOCH, fill_cur_epoch, fill_prev_epoch, participation_fn=participation_fn, ) blocks.extend([pre_tag(block) for block in blocks_in_epoch]) _, blocks_in_epoch, state = next_slots_with_attestations( spec, state, spec.SLOTS_PER_EPOCH - 1, fill_cur_epoch, fill_prev_epoch, participation_fn=participation_fn, ) blocks.extend([pre_tag(block) for block in blocks_in_epoch]) assert spec.get_current_epoch(state) == fork_epoch - 1 assert (state.slot + 1) % spec.SLOTS_PER_EPOCH == 0 # irregular state transition to handle fork: state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # continue regular state transition with new spec into next epoch for _ in range(4): _, blocks_in_epoch, state = next_slots_with_attestations( post_spec, state, post_spec.SLOTS_PER_EPOCH, fill_cur_epoch, fill_prev_epoch, participation_fn=participation_fn, ) blocks.extend([post_tag(block) for block in blocks_in_epoch]) assert state.slot % post_spec.SLOTS_PER_EPOCH == 0 assert post_spec.get_current_epoch(state) == fork_epoch + 4 if expect_finality: assert state.current_justified_checkpoint.epoch == fork_epoch + 2 assert state.finalized_checkpoint.epoch == fork_epoch else: assert state.current_justified_checkpoint.epoch == spec.GENESIS_EPOCH assert state.finalized_checkpoint.epoch == spec.GENESIS_EPOCH assert len(blocks) == (fork_epoch + 3) * post_spec.SLOTS_PER_EPOCH + 1 assert len(blocks) == len(set(blocks)) blocks_without_attestations = [block for block in blocks if len(block.message.body.attestations) == 0] assert len(blocks_without_attestations) == 2 slots_without_attestations = [b.message.slot for b in blocks_without_attestations] assert set(slots_without_attestations) == set([spec.SLOTS_PER_EPOCH, fork_epoch * spec.SLOTS_PER_EPOCH]) yield "blocks", blocks yield "post", state @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=3) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_finality(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Transition from the initial ``state`` to the epoch after the ``fork_epoch``, including attestations so as to produce finality through the fork boundary. """ yield from _run_transition_test_with_attestations(state, fork_epoch, spec, post_spec, pre_tag, post_tag) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=3) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_random_three_quarters_participation(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Transition from the initial ``state`` to the epoch after the ``fork_epoch``, including attestations so as to produce finality through the fork boundary. """ rng = random.Random(1337) def _drop_random_quarter(_slot, _index, indices): # still finalize, but drop some attestations committee_len = len(indices) assert committee_len >= 4 filter_len = committee_len // 4 participant_count = committee_len - filter_len return rng.sample(sorted(indices), participant_count) yield from _run_transition_test_with_attestations( state, fork_epoch, spec, post_spec, pre_tag, post_tag, participation_fn=_drop_random_quarter ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=3) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_random_half_participation(state, fork_epoch, spec, post_spec, pre_tag, post_tag): rng = random.Random(2020) def _drop_random_half(_slot, _index, indices): # drop enough attestations to not finalize committee_len = len(indices) assert committee_len >= 2 filter_len = committee_len // 2 participant_count = committee_len - filter_len return rng.sample(sorted(indices), participant_count) yield from _run_transition_test_with_attestations( state, fork_epoch, spec, post_spec, pre_tag, post_tag, participation_fn=_drop_random_half, expect_finality=False ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=3) for pre, post in ALL_PRE_POST_FORKS]) def test_transition_with_no_attestations_until_after_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Transition from the initial ``state`` to the ``fork_epoch`` with no attestations, then transition forward with enough attestations to finalize the fork epoch. """ yield "pre", state assert spec.get_current_epoch(state) < fork_epoch # regular state transition until fork: to_slot = fork_epoch * spec.SLOTS_PER_EPOCH - 1 blocks = [] blocks.extend([ pre_tag(block) for block in state_transition_across_slots(spec, state, to_slot) ]) # irregular state transition to handle fork: state, block = do_fork(state, spec, post_spec, fork_epoch) blocks.append(post_tag(block)) # continue regular state transition but add attestations # for enough epochs to finalize the ``fork_epoch`` block = next_epoch_via_signed_block(post_spec, state) blocks.append(post_tag(block)) for _ in range(4): _, blocks_in_epoch, state = next_slots_with_attestations( post_spec, state, post_spec.SLOTS_PER_EPOCH, False, True, ) blocks.extend([post_tag(block) for block in blocks_in_epoch]) assert state.slot % post_spec.SLOTS_PER_EPOCH == 0 assert post_spec.get_current_epoch(state) == fork_epoch + 5 assert state.current_justified_checkpoint.epoch == fork_epoch + 3 assert state.finalized_checkpoint.epoch == fork_epoch + 1 yield "blocks", blocks yield "post", state
15,580
36.009501
118
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/rewards/test_inactivity_scores.py
from random import Random from eth2spec.test.context import ( with_altair_and_later, spec_test, spec_state_test, with_custom_state, single_phase, low_balances, misc_balances, ) from eth2spec.test.helpers.inactivity_scores import randomize_inactivity_scores from eth2spec.test.helpers.rewards import leaking import eth2spec.test.helpers.rewards as rewards_helpers @with_altair_and_later @spec_state_test def test_random_inactivity_scores_0(spec, state): randomize_inactivity_scores(spec, state, rng=Random(9999)) yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(9999)) @with_altair_and_later @spec_state_test def test_random_inactivity_scores_1(spec, state): randomize_inactivity_scores(spec, state, rng=Random(10000)) yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(10000)) @with_altair_and_later @spec_state_test def test_half_zero_half_random_inactivity_scores(spec, state): randomize_inactivity_scores(spec, state, rng=Random(10101)) half_val_point = len(state.validators) // 2 state.inactivity_scores = [0] * half_val_point + state.inactivity_scores[half_val_point:] yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(10101)) @with_altair_and_later @spec_state_test def test_random_high_inactivity_scores(spec, state): randomize_inactivity_scores(spec, state, minimum=500000, maximum=5000000, rng=Random(9998)) yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(9998)) @with_altair_and_later @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase def test_random_inactivity_scores_low_balances_0(spec, state): randomize_inactivity_scores(spec, state, rng=Random(11111)) yield from rewards_helpers.run_test_full_random(spec, state) @with_altair_and_later @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase def test_random_inactivity_scores_low_balances_1(spec, state): randomize_inactivity_scores(spec, state, rng=Random(22222)) yield from rewards_helpers.run_test_full_random(spec, state) @with_altair_and_later @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase def test_full_random_misc_balances(spec, state): randomize_inactivity_scores(spec, state, rng=Random(33333)) yield from rewards_helpers.run_test_full_random(spec, state) # # Leaking variants # @with_altair_and_later @spec_state_test @leaking() def test_random_inactivity_scores_leaking_0(spec, state): randomize_inactivity_scores(spec, state, rng=Random(9999)) yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(9999)) @with_altair_and_later @spec_state_test @leaking() def test_random_inactivity_scores_leaking_1(spec, state): randomize_inactivity_scores(spec, state, rng=Random(10000)) yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(10000)) @with_altair_and_later @spec_state_test @leaking() def test_half_zero_half_random_inactivity_scores_leaking(spec, state): randomize_inactivity_scores(spec, state, rng=Random(10101)) half_val_point = len(state.validators) // 2 state.inactivity_scores = [0] * half_val_point + state.inactivity_scores[half_val_point:] yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(10101)) @with_altair_and_later @spec_state_test @leaking() def test_random_high_inactivity_scores_leaking(spec, state): randomize_inactivity_scores(spec, state, minimum=500000, maximum=5000000, rng=Random(9998)) yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(9998)) @with_altair_and_later @spec_state_test @leaking(epochs=8) def test_random_high_inactivity_scores_leaking_8_epochs(spec, state): randomize_inactivity_scores(spec, state, minimum=500000, maximum=5000000, rng=Random(9998)) yield from rewards_helpers.run_test_full_random(spec, state, rng=Random(9998))
4,110
33.546218
101
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/fork/test_altair_fork_basic.py
from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( PHASE0, ALTAIR, MINIMAL, ) from eth2spec.test.helpers.state import ( next_epoch, next_epoch_via_block, ) from eth2spec.test.helpers.altair.fork import ( ALTAIR_FORK_TEST_META_TAGS, run_fork_test, ) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_fork_base_state(spec, phases, state): yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_fork_next_epoch(spec, phases, state): next_epoch(spec, state) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_fork_next_epoch_with_block(spec, phases, state): next_epoch_via_block(spec, state) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_fork_many_next_epoch(spec, phases, state): for _ in range(3): next_epoch(spec, state) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_fork_random_low_balances(spec, phases, state): yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_fork_random_misc_balances(spec, phases, state): yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_fork_random_large_validator_set(spec, phases, state): yield from run_fork_test(phases[ALTAIR], state)
2,628
30.674699
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/fork/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/fork/test_altair_fork_random.py
from random import Random from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( PHASE0, ALTAIR, MINIMAL, ) from eth2spec.test.helpers.altair.fork import ( ALTAIR_FORK_TEST_META_TAGS, run_fork_test, ) from eth2spec.test.helpers.random import ( randomize_state, randomize_attestation_participation, ) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_0(spec, phases, state): randomize_state(spec, state, rng=Random(1010)) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_1(spec, phases, state): randomize_state(spec, state, rng=Random(2020)) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_2(spec, phases, state): randomize_state(spec, state, rng=Random(3030)) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_3(spec, phases, state): randomize_state(spec, state, rng=Random(4040)) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_duplicate_attestations(spec, phases, state): randomize_state(spec, state, rng=Random(1111)) # Note: `run_fork_test` empties `current_epoch_attestations` state.previous_epoch_attestations = state.previous_epoch_attestations + state.previous_epoch_attestations yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_state @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_mismatched_attestations(spec, phases, state): # Create a random state randomize_state(spec, state, rng=Random(2222)) # Now make two copies state_0 = state.copy() state_1 = state.copy() # Randomize attestation participation of both randomize_attestation_participation(spec, state_0, rng=Random(3333)) randomize_attestation_participation(spec, state_1, rng=Random(4444)) # Note: `run_fork_test` empties `current_epoch_attestations` # Use pending attestations from both random states in a single state for testing state_0.previous_epoch_attestations = state_0.previous_epoch_attestations + state_1.previous_epoch_attestations yield from run_fork_test(phases[ALTAIR], state_0) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_low_balances(spec, phases, state): randomize_state(spec, state, rng=Random(5050)) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @spec_test @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_misc_balances(spec, phases, state): randomize_state(spec, state, rng=Random(6060)) yield from run_fork_test(phases[ALTAIR], state) @with_phases(phases=[PHASE0], other_phases=[ALTAIR]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @spec_test @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(ALTAIR_FORK_TEST_META_TAGS) def test_altair_fork_random_large_validator_set(spec, phases, state): randomize_state(spec, state, rng=Random(7070)) yield from run_fork_test(phases[ALTAIR], state)
4,284
34.413223
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/light_client/test_sync.py
from typing import (Any, Dict, List) from eth_utils import encode_hex from eth2spec.test.context import ( spec_state_test_with_matching_config, spec_test, with_config_overrides, with_matching_spec_config, with_phases, with_presets, with_state, with_light_client, ) from eth2spec.test.helpers.attestations import ( next_slots_with_attestations, state_transition_with_full_block, ) from eth2spec.test.helpers.constants import ( PHASE0, ALTAIR, BELLATRIX, CAPELLA, DENEB, MINIMAL, ALL_PHASES, ) from eth2spec.test.helpers.fork_transition import ( do_fork, ) from eth2spec.test.helpers.forks import ( is_post_capella, is_post_deneb, is_post_fork, ) from eth2spec.test.helpers.light_client import ( get_sync_aggregate, ) from eth2spec.test.helpers.state import ( next_slots, transition_to, ) def get_spec_for_fork_version(spec, fork_version, phases): if phases is None: return spec for fork in [fork for fork in ALL_PHASES if is_post_fork(spec.fork, fork)]: if fork == PHASE0: fork_version_field = 'GENESIS_FORK_VERSION' else: fork_version_field = fork.upper() + '_FORK_VERSION' if fork_version == getattr(spec.config, fork_version_field): return phases[fork] raise ValueError("Unknown fork version %s" % fork_version) def needs_upgrade_to_capella(d_spec, s_spec): return is_post_capella(s_spec) and not is_post_capella(d_spec) def needs_upgrade_to_deneb(d_spec, s_spec): return is_post_deneb(s_spec) and not is_post_deneb(d_spec) def check_lc_header_equal(d_spec, s_spec, data, upgraded): assert upgraded.beacon.slot == data.beacon.slot assert upgraded.beacon.hash_tree_root() == data.beacon.hash_tree_root() if is_post_capella(s_spec): if is_post_capella(d_spec): assert s_spec.get_lc_execution_root(upgraded) == d_spec.get_lc_execution_root(data) else: assert s_spec.get_lc_execution_root(upgraded) == s_spec.Root() def check_lc_bootstrap_equal(d_spec, s_spec, data, upgraded): check_lc_header_equal(d_spec, s_spec, data.header, upgraded.header) assert upgraded.current_sync_committee == data.current_sync_committee assert upgraded.current_sync_committee_branch == data.current_sync_committee_branch def upgrade_lc_bootstrap_to_store(d_spec, s_spec, data): upgraded = data if needs_upgrade_to_capella(d_spec, s_spec): upgraded = s_spec.upgrade_lc_bootstrap_to_capella(upgraded) check_lc_bootstrap_equal(d_spec, s_spec, data, upgraded) if needs_upgrade_to_deneb(d_spec, s_spec): upgraded = s_spec.upgrade_lc_bootstrap_to_deneb(upgraded) check_lc_bootstrap_equal(d_spec, s_spec, data, upgraded) return upgraded def check_lc_update_equal(d_spec, s_spec, data, upgraded): check_lc_header_equal(d_spec, s_spec, data.attested_header, upgraded.attested_header) assert upgraded.next_sync_committee == data.next_sync_committee assert upgraded.next_sync_committee_branch == data.next_sync_committee_branch check_lc_header_equal(d_spec, s_spec, data.finalized_header, upgraded.finalized_header) assert upgraded.sync_aggregate == data.sync_aggregate assert upgraded.signature_slot == data.signature_slot def upgrade_lc_update_to_store(d_spec, s_spec, data): upgraded = data if needs_upgrade_to_capella(d_spec, s_spec): upgraded = s_spec.upgrade_lc_update_to_capella(upgraded) check_lc_update_equal(d_spec, s_spec, data, upgraded) if needs_upgrade_to_deneb(d_spec, s_spec): upgraded = s_spec.upgrade_lc_update_to_deneb(upgraded) check_lc_update_equal(d_spec, s_spec, data, upgraded) return upgraded def check_lc_store_equal(d_spec, s_spec, data, upgraded): check_lc_header_equal(d_spec, s_spec, data.finalized_header, upgraded.finalized_header) assert upgraded.current_sync_committee == data.current_sync_committee assert upgraded.next_sync_committee == data.next_sync_committee if upgraded.best_valid_update is None: assert data.best_valid_update is None else: check_lc_update_equal(d_spec, s_spec, data.best_valid_update, upgraded.best_valid_update) check_lc_header_equal(d_spec, s_spec, data.optimistic_header, upgraded.optimistic_header) assert upgraded.previous_max_active_participants == data.previous_max_active_participants assert upgraded.current_max_active_participants == data.current_max_active_participants def upgrade_lc_store_to_new_spec(d_spec, s_spec, data): upgraded = data if needs_upgrade_to_capella(d_spec, s_spec): upgraded = s_spec.upgrade_lc_store_to_capella(upgraded) check_lc_store_equal(d_spec, s_spec, data, upgraded) if needs_upgrade_to_deneb(d_spec, s_spec): upgraded = s_spec.upgrade_lc_store_to_deneb(upgraded) check_lc_store_equal(d_spec, s_spec, data, upgraded) return upgraded class LightClientSyncTest(object): steps: List[Dict[str, Any]] genesis_validators_root: Any s_spec: Any store: Any def get_store_fork_version(s_spec): if is_post_deneb(s_spec): return s_spec.config.DENEB_FORK_VERSION if is_post_capella(s_spec): return s_spec.config.CAPELLA_FORK_VERSION return s_spec.config.ALTAIR_FORK_VERSION def setup_test(spec, state, s_spec=None, phases=None): test = LightClientSyncTest() test.steps = [] if s_spec is None: s_spec = spec test.s_spec = s_spec yield "genesis_validators_root", "meta", "0x" + state.genesis_validators_root.hex() test.genesis_validators_root = state.genesis_validators_root next_slots(spec, state, spec.SLOTS_PER_EPOCH * 2 - 1) trusted_block = state_transition_with_full_block(spec, state, True, True) trusted_block_root = trusted_block.message.hash_tree_root() yield "trusted_block_root", "meta", "0x" + trusted_block_root.hex() data_fork_version = spec.compute_fork_version(spec.compute_epoch_at_slot(trusted_block.message.slot)) data_fork_digest = spec.compute_fork_digest(data_fork_version, test.genesis_validators_root) d_spec = get_spec_for_fork_version(spec, data_fork_version, phases) data = d_spec.create_light_client_bootstrap(state, trusted_block) yield "bootstrap_fork_digest", "meta", encode_hex(data_fork_digest) yield "bootstrap", data upgraded = upgrade_lc_bootstrap_to_store(d_spec, test.s_spec, data) test.store = test.s_spec.initialize_light_client_store(trusted_block_root, upgraded) store_fork_version = get_store_fork_version(test.s_spec) store_fork_digest = test.s_spec.compute_fork_digest(store_fork_version, test.genesis_validators_root) yield "store_fork_digest", "meta", encode_hex(store_fork_digest) return test def finish_test(test): yield "steps", test.steps def get_update_file_name(d_spec, update): if d_spec.is_sync_committee_update(update): suffix1 = "s" else: suffix1 = "x" if d_spec.is_finality_update(update): suffix2 = "f" else: suffix2 = "x" return f"update_{encode_hex(update.attested_header.beacon.hash_tree_root())}_{suffix1}{suffix2}" def get_checks(s_spec, store): if is_post_capella(s_spec): return { "finalized_header": { 'slot': int(store.finalized_header.beacon.slot), 'beacon_root': encode_hex(store.finalized_header.beacon.hash_tree_root()), 'execution_root': encode_hex(s_spec.get_lc_execution_root(store.finalized_header)), }, "optimistic_header": { 'slot': int(store.optimistic_header.beacon.slot), 'beacon_root': encode_hex(store.optimistic_header.beacon.hash_tree_root()), 'execution_root': encode_hex(s_spec.get_lc_execution_root(store.optimistic_header)), }, } return { "finalized_header": { 'slot': int(store.finalized_header.beacon.slot), 'beacon_root': encode_hex(store.finalized_header.beacon.hash_tree_root()), }, "optimistic_header": { 'slot': int(store.optimistic_header.beacon.slot), 'beacon_root': encode_hex(store.optimistic_header.beacon.hash_tree_root()), }, } def emit_force_update(test, spec, state): current_slot = state.slot test.s_spec.process_light_client_store_force_update(test.store, current_slot) yield from [] # Consistently enable `yield from` syntax in calling tests test.steps.append({ "force_update": { "current_slot": int(current_slot), "checks": get_checks(test.s_spec, test.store), } }) def emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, with_next=True, phases=None): data_fork_version = spec.compute_fork_version(spec.compute_epoch_at_slot(attested_block.message.slot)) data_fork_digest = spec.compute_fork_digest(data_fork_version, test.genesis_validators_root) d_spec = get_spec_for_fork_version(spec, data_fork_version, phases) data = d_spec.create_light_client_update(state, block, attested_state, attested_block, finalized_block) if not with_next: data.next_sync_committee = spec.SyncCommittee() data.next_sync_committee_branch = \ [spec.Bytes32() for _ in range(spec.floorlog2(spec.NEXT_SYNC_COMMITTEE_INDEX))] current_slot = state.slot upgraded = upgrade_lc_update_to_store(d_spec, test.s_spec, data) test.s_spec.process_light_client_update(test.store, upgraded, current_slot, test.genesis_validators_root) yield get_update_file_name(d_spec, data), data test.steps.append({ "process_update": { "update_fork_digest": encode_hex(data_fork_digest), "update": get_update_file_name(d_spec, data), "current_slot": int(current_slot), "checks": get_checks(test.s_spec, test.store), } }) return upgraded def emit_upgrade_store(test, new_s_spec, phases=None): test.store = upgrade_lc_store_to_new_spec(test.s_spec, new_s_spec, test.store) test.s_spec = new_s_spec store_fork_version = get_store_fork_version(test.s_spec) store_fork_digest = test.s_spec.compute_fork_digest(store_fork_version, test.genesis_validators_root) yield from [] # Consistently enable `yield from` syntax in calling tests test.steps.append({ "upgrade_store": { "store_fork_digest": encode_hex(store_fork_digest), "checks": get_checks(test.s_spec, test.store), } }) def compute_start_slot_at_sync_committee_period(spec, sync_committee_period): return spec.compute_start_slot_at_epoch(sync_committee_period * spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD) def compute_start_slot_at_next_sync_committee_period(spec, state): sync_committee_period = spec.compute_sync_committee_period_at_slot(state.slot) return compute_start_slot_at_sync_committee_period(spec, sync_committee_period + 1) @with_light_client @spec_state_test_with_matching_config @with_presets([MINIMAL], reason="too slow") def test_light_client_sync(spec, state): # Start test test = yield from setup_test(spec, state) # Initial `LightClientUpdate`, populating `store.next_sync_committee` # ``` # | # +-----------+ +----------+ +-----------+ | # | finalized | <-- (2 epochs) -- | attested | <-- | signature | | # +-----------+ +----------+ +-----------+ | # | # | # sync committee # period boundary # ``` next_slots(spec, state, spec.SLOTS_PER_EPOCH - 1) finalized_block = state_transition_with_full_block(spec, state, True, True) finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Advance to next sync committee period # ``` # | # +-----------+ +----------+ +-----------+ | # | finalized | <-- (2 epochs) -- | attested | <-- | signature | | # +-----------+ +----------+ +-----------+ | # | # | # sync committee # period boundary # ``` transition_to(spec, state, compute_start_slot_at_next_sync_committee_period(spec, state)) next_slots(spec, state, spec.SLOTS_PER_EPOCH - 1) finalized_block = state_transition_with_full_block(spec, state, True, True) finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Edge case: Signature in next period # ``` # | # +-----------+ +----------+ | +-----------+ # | finalized | <-- (2 epochs) -- | attested | <-- | signature | # +-----------+ +----------+ | +-----------+ # | # | # sync committee # period boundary # ``` next_slots(spec, state, spec.SLOTS_PER_EPOCH - 2) finalized_block = state_transition_with_full_block(spec, state, True, True) finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() transition_to(spec, state, compute_start_slot_at_next_sync_committee_period(spec, state)) sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Edge case: Finalized header not included # ``` # | # + - - - - - + | +----------+ +-----------+ # ¦ finalized ¦ <-- (2 epochs) -- | attested | <-- | signature | # + - - - - - + | +----------+ +-----------+ # | # | # sync committee # period boundary # ``` attested_block = block.copy() attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) update = yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block=None) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Non-finalized case: Attested `next_sync_committee` is not finalized # ``` # | # +-----------+ | +----------+ +-----------+ # | finalized | <-- (2 epochs) -- | attested | <-- | signature | # +-----------+ | +----------+ +-----------+ # | # | # sync committee # period boundary # ``` attested_block = block.copy() attested_state = state.copy() store_state = attested_state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) update = yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Force-update using timeout # ``` # | # +-----------+ | +----------+ # | finalized | <-- (2 epochs) -- | attested | # +-----------+ | +----------+ # | ^ # | \ # sync committee `--- store.finalized_header # period boundary # ``` attested_block = block.copy() attested_state = state.copy() next_slots(spec, state, spec.UPDATE_TIMEOUT - 1) yield from emit_force_update(test, spec, state) assert test.store.finalized_header.beacon.slot == store_state.slot assert test.store.next_sync_committee == store_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == store_state.slot # Edge case: Finalized header not included, after force-update # ``` # | | # + - - - - - + | +--+ +----------+ | +-----------+ # ¦ finalized ¦ <-- (2 epochs) -- | | <-- | attested | <-- | signature | # + - - - - - + | +--+ +----------+ | +-----------+ # | / | # | store.fin | # sync committee sync committee # period boundary period boundary # ``` sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) update = yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block=None) assert test.store.finalized_header.beacon.slot == store_state.slot assert test.store.next_sync_committee == store_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Edge case: Finalized header older than store # ``` # | | # +-----------+ | +--+ | +----------+ +-----------+ # | finalized | <-- (2 epochs) -- | | <-- | attested | <-- | signature | # +-----------+ | +--+ | +----------+ +-----------+ # | / | # | store.fin | # sync committee sync committee # period boundary period boundary # ``` attested_block = block.copy() attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) update = yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == store_state.slot assert test.store.next_sync_committee == store_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot yield from emit_force_update(test, spec, state) assert test.store.finalized_header.beacon.slot == attested_state.slot assert test.store.next_sync_committee == attested_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Advance to next sync committee period # ``` # | # +-----------+ +----------+ +-----------+ | # | finalized | <-- (2 epochs) -- | attested | <-- | signature | | # +-----------+ +----------+ +-----------+ | # | # | # sync committee # period boundary # ``` transition_to(spec, state, compute_start_slot_at_next_sync_committee_period(spec, state)) next_slots(spec, state, spec.SLOTS_PER_EPOCH - 1) finalized_block = state_transition_with_full_block(spec, state, True, True) finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Finish test yield from finish_test(test) @with_light_client @spec_state_test_with_matching_config @with_presets([MINIMAL], reason="too slow") def test_supply_sync_committee_from_past_update(spec, state): # Advance the chain, so that a `LightClientUpdate` from the past is available next_slots(spec, state, spec.SLOTS_PER_EPOCH * 2 - 1) finalized_block = state_transition_with_full_block(spec, state, True, True) finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) past_state = state.copy() # Start test test = yield from setup_test(spec, state) assert not spec.is_next_sync_committee_known(test.store) # Apply `LightClientUpdate` from the past, populating `store.next_sync_committee` yield from emit_update(test, spec, past_state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == state.slot # Finish test yield from finish_test(test) @with_light_client @spec_state_test_with_matching_config @with_presets([MINIMAL], reason="too slow") def test_advance_finality_without_sync_committee(spec, state): # Start test test = yield from setup_test(spec, state) # Initial `LightClientUpdate`, populating `store.next_sync_committee` next_slots(spec, state, spec.SLOTS_PER_EPOCH - 1) finalized_block = state_transition_with_full_block(spec, state, True, True) finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Advance finality into next sync committee period, but omit `next_sync_committee` transition_to(spec, state, compute_start_slot_at_next_sync_committee_period(spec, state)) next_slots(spec, state, spec.SLOTS_PER_EPOCH - 1) finalized_block = state_transition_with_full_block(spec, state, True, True) finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, spec.SLOTS_PER_EPOCH - 1, True, True) justified_block = state_transition_with_full_block(spec, state, True, True) justified_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, with_next=False) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert not spec.is_next_sync_committee_known(test.store) assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Advance finality once more, with `next_sync_committee` still unknown past_state = finalized_state finalized_block = justified_block finalized_state = justified_state _, _, state = next_slots_with_attestations(spec, state, spec.SLOTS_PER_EPOCH - 2, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) # Apply `LightClientUpdate` without `finalized_header` nor `next_sync_committee` update = yield from emit_update(test, spec, state, block, attested_state, attested_block, None, with_next=False) assert test.store.finalized_header.beacon.slot == past_state.slot assert not spec.is_next_sync_committee_known(test.store) assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Apply `LightClientUpdate` with `finalized_header` but no `next_sync_committee` yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, with_next=False) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert not spec.is_next_sync_committee_known(test.store) assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Apply full `LightClientUpdate`, supplying `next_sync_committee` yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Finish test yield from finish_test(test) def run_test_single_fork(spec, phases, state, fork): # Start test test = yield from setup_test(spec, state, phases=phases) # Initial `LightClientUpdate` finalized_block = spec.SignedBeaconBlock() finalized_block.message.state_root = state.hash_tree_root() finalized_state = state.copy() attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Jump to two slots before fork fork_epoch = getattr(phases[fork].config, fork.upper() + '_FORK_EPOCH') transition_to(spec, state, spec.compute_start_slot_at_epoch(fork_epoch) - 4) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) update = yield from emit_update( test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Perform `LightClientStore` upgrade yield from emit_upgrade_store(test, phases[fork], phases=phases) update = test.store.best_valid_update # Final slot before fork, check that importing the pre-fork format still works attested_block = block.copy() attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Upgrade to post-fork spec, attested block is still before the fork attested_block = block.copy() attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(phases[fork], state) state, block = do_fork(state, spec, phases[fork], fork_epoch, sync_aggregate=sync_aggregate) spec = phases[fork] yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Another block after the fork, this time attested block is after the fork attested_block = block.copy() attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Jump to next epoch transition_to(spec, state, spec.compute_start_slot_at_epoch(fork_epoch + 1) - 2) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update == update assert test.store.optimistic_header.beacon.slot == attested_state.slot # Finalize the fork finalized_block = block.copy() finalized_state = state.copy() _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Finish test yield from finish_test(test) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_config_overrides({ 'CAPELLA_FORK_EPOCH': 3, # `setup_test` advances to epoch 2 }, emit=False) @with_state @with_matching_spec_config(emitted_fork=CAPELLA) @with_presets([MINIMAL], reason="too slow") def test_capella_fork(spec, phases, state): yield from run_test_single_fork(spec, phases, state, CAPELLA) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_config_overrides({ 'DENEB_FORK_EPOCH': 3, # `setup_test` advances to epoch 2 }, emit=False) @with_state @with_matching_spec_config(emitted_fork=DENEB) @with_presets([MINIMAL], reason="too slow") def test_deneb_fork(spec, phases, state): yield from run_test_single_fork(spec, phases, state, DENEB) def run_test_multi_fork(spec, phases, state, fork_1, fork_2): # Start test test = yield from setup_test(spec, state, phases[fork_2], phases) # Set up so that finalized is from `spec`, ... finalized_block = spec.SignedBeaconBlock() finalized_block.message.state_root = state.hash_tree_root() finalized_state = state.copy() # ..., attested is from `fork_1`, ... fork_1_epoch = getattr(phases[fork_1].config, fork_1.upper() + '_FORK_EPOCH') transition_to(spec, state, spec.compute_start_slot_at_epoch(fork_1_epoch) - 1) state, attested_block = do_fork(state, spec, phases[fork_1], fork_1_epoch) spec = phases[fork_1] attested_state = state.copy() # ..., and signature is from `fork_2` fork_2_epoch = getattr(phases[fork_2].config, fork_2.upper() + '_FORK_EPOCH') transition_to(spec, state, spec.compute_start_slot_at_epoch(fork_2_epoch) - 1) sync_aggregate, _ = get_sync_aggregate(phases[fork_2], state) state, block = do_fork(state, spec, phases[fork_2], fork_2_epoch, sync_aggregate=sync_aggregate) spec = phases[fork_2] # Check that update applies yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Finish test yield from finish_test(test) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA, DENEB]) @spec_test @with_config_overrides({ 'CAPELLA_FORK_EPOCH': 3, # `setup_test` advances to epoch 2 'DENEB_FORK_EPOCH': 4, }, emit=False) @with_state @with_matching_spec_config(emitted_fork=DENEB) @with_presets([MINIMAL], reason="too slow") def test_capella_deneb_fork(spec, phases, state): yield from run_test_multi_fork(spec, phases, state, CAPELLA, DENEB) def run_test_upgraded_store_with_legacy_data(spec, phases, state, fork): # Start test (Legacy bootstrap with an upgraded store) test = yield from setup_test(spec, state, phases[fork], phases) # Initial `LightClientUpdate` (check that the upgraded store can process it) finalized_block = spec.SignedBeaconBlock() finalized_block.message.state_root = state.hash_tree_root() finalized_state = state.copy() attested_block = state_transition_with_full_block(spec, state, True, True) attested_state = state.copy() sync_aggregate, _ = get_sync_aggregate(spec, state) block = state_transition_with_full_block(spec, state, True, True, sync_aggregate=sync_aggregate) yield from emit_update(test, spec, state, block, attested_state, attested_block, finalized_block, phases=phases) assert test.store.finalized_header.beacon.slot == finalized_state.slot assert test.store.next_sync_committee == finalized_state.next_sync_committee assert test.store.best_valid_update is None assert test.store.optimistic_header.beacon.slot == attested_state.slot # Finish test yield from finish_test(test) @with_phases(phases=[ALTAIR, BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_matching_spec_config(emitted_fork=CAPELLA) @with_presets([MINIMAL], reason="too slow") def test_capella_store_with_legacy_data(spec, phases, state): yield from run_test_upgraded_store_with_legacy_data(spec, phases, state, CAPELLA) @with_phases(phases=[ALTAIR, BELLATRIX, CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_matching_spec_config(emitted_fork=DENEB) @with_presets([MINIMAL], reason="too slow") def test_deneb_store_with_legacy_data(spec, phases, state): yield from run_test_upgraded_store_with_legacy_data(spec, phases, state, DENEB)
40,178
47.408434
120
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/light_client/test_update_ranking.py
from eth2spec.test.context import ( spec_state_test, with_presets, with_light_client, ) from eth2spec.test.helpers.attestations import ( next_slots_with_attestations, state_transition_with_full_block, ) from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.helpers.light_client import ( create_update, ) from eth2spec.test.helpers.state import ( next_slots, ) def create_test_update(spec, test, with_next, with_finality, participation_rate): attested_state, attested_block, finalized_block = test return create_update( spec, attested_state, attested_block, finalized_block, with_next, with_finality, participation_rate, ) @with_light_client @spec_state_test @with_presets([MINIMAL], reason="too slow") def test_update_ranking(spec, state): # Set up blocks and states: # - `sig_finalized` / `sig_attested` --> Only signature in next sync committee period # - `att_finalized` / `att_attested` --> Attested header also in next sync committee period # - `fin_finalized` / `fin_attested` --> Finalized header also in next sync committee period # - `lat_finalized` / `lat_attested` --> Like `fin`, but at a later `attested_header.beacon.slot` next_slots(spec, state, spec.compute_start_slot_at_epoch(spec.EPOCHS_PER_SYNC_COMMITTEE_PERIOD - 3) - 1) sig_finalized_block = state_transition_with_full_block(spec, state, True, True) _, _, state = next_slots_with_attestations(spec, state, spec.SLOTS_PER_EPOCH - 1, True, True) att_finalized_block = state_transition_with_full_block(spec, state, True, True) _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 2, True, True) sig_attested_block = state_transition_with_full_block(spec, state, True, True) sig_attested_state = state.copy() att_attested_block = state_transition_with_full_block(spec, state, True, True) att_attested_state = state.copy() fin_finalized_block = att_attested_block _, _, state = next_slots_with_attestations(spec, state, 2 * spec.SLOTS_PER_EPOCH - 1, True, True) fin_attested_block = state_transition_with_full_block(spec, state, True, True) fin_attested_state = state.copy() lat_finalized_block = fin_finalized_block lat_attested_block = state_transition_with_full_block(spec, state, True, True) lat_attested_state = state.copy() sig = (sig_attested_state, sig_attested_block, sig_finalized_block) att = (att_attested_state, att_attested_block, att_finalized_block) fin = (fin_attested_state, fin_attested_block, fin_finalized_block) lat = (lat_attested_state, lat_attested_block, lat_finalized_block) # Create updates (in descending order of quality) updates = [ # Updates with sync committee finality create_test_update(spec, fin, with_next=1, with_finality=1, participation_rate=1.0), create_test_update(spec, lat, with_next=1, with_finality=1, participation_rate=1.0), create_test_update(spec, fin, with_next=1, with_finality=1, participation_rate=0.8), create_test_update(spec, lat, with_next=1, with_finality=1, participation_rate=0.8), # Updates without sync committee finality create_test_update(spec, att, with_next=1, with_finality=1, participation_rate=1.0), create_test_update(spec, att, with_next=1, with_finality=1, participation_rate=0.8), # Updates without indication of any finality create_test_update(spec, att, with_next=1, with_finality=0, participation_rate=1.0), create_test_update(spec, fin, with_next=1, with_finality=0, participation_rate=1.0), create_test_update(spec, lat, with_next=1, with_finality=0, participation_rate=1.0), create_test_update(spec, att, with_next=1, with_finality=0, participation_rate=0.8), create_test_update(spec, fin, with_next=1, with_finality=0, participation_rate=0.8), create_test_update(spec, lat, with_next=1, with_finality=0, participation_rate=0.8), # Updates with sync committee finality but no `next_sync_committee` create_test_update(spec, sig, with_next=0, with_finality=1, participation_rate=1.0), create_test_update(spec, fin, with_next=0, with_finality=1, participation_rate=1.0), create_test_update(spec, lat, with_next=0, with_finality=1, participation_rate=1.0), create_test_update(spec, sig, with_next=0, with_finality=1, participation_rate=0.8), create_test_update(spec, fin, with_next=0, with_finality=1, participation_rate=0.8), create_test_update(spec, lat, with_next=0, with_finality=1, participation_rate=0.8), # Updates without sync committee finality and also no `next_sync_committee` create_test_update(spec, att, with_next=0, with_finality=1, participation_rate=1.0), create_test_update(spec, att, with_next=0, with_finality=1, participation_rate=0.8), # Updates without indication of any finality nor `next_sync_committee` create_test_update(spec, sig, with_next=0, with_finality=0, participation_rate=1.0), create_test_update(spec, att, with_next=0, with_finality=0, participation_rate=1.0), create_test_update(spec, fin, with_next=0, with_finality=0, participation_rate=1.0), create_test_update(spec, lat, with_next=0, with_finality=0, participation_rate=1.0), create_test_update(spec, sig, with_next=0, with_finality=0, participation_rate=0.8), create_test_update(spec, att, with_next=0, with_finality=0, participation_rate=0.8), create_test_update(spec, fin, with_next=0, with_finality=0, participation_rate=0.8), create_test_update(spec, lat, with_next=0, with_finality=0, participation_rate=0.8), # Updates with low sync committee participation create_test_update(spec, fin, with_next=1, with_finality=1, participation_rate=0.4), create_test_update(spec, lat, with_next=1, with_finality=1, participation_rate=0.4), create_test_update(spec, att, with_next=1, with_finality=1, participation_rate=0.4), create_test_update(spec, att, with_next=1, with_finality=0, participation_rate=0.4), create_test_update(spec, fin, with_next=1, with_finality=0, participation_rate=0.4), create_test_update(spec, lat, with_next=1, with_finality=0, participation_rate=0.4), create_test_update(spec, sig, with_next=0, with_finality=1, participation_rate=0.4), create_test_update(spec, fin, with_next=0, with_finality=1, participation_rate=0.4), create_test_update(spec, lat, with_next=0, with_finality=1, participation_rate=0.4), create_test_update(spec, att, with_next=0, with_finality=1, participation_rate=0.4), create_test_update(spec, sig, with_next=0, with_finality=0, participation_rate=0.4), create_test_update(spec, att, with_next=0, with_finality=0, participation_rate=0.4), create_test_update(spec, fin, with_next=0, with_finality=0, participation_rate=0.4), create_test_update(spec, lat, with_next=0, with_finality=0, participation_rate=0.4), # Updates with very low sync committee participation create_test_update(spec, fin, with_next=1, with_finality=1, participation_rate=0.2), create_test_update(spec, lat, with_next=1, with_finality=1, participation_rate=0.2), create_test_update(spec, att, with_next=1, with_finality=1, participation_rate=0.2), create_test_update(spec, att, with_next=1, with_finality=0, participation_rate=0.2), create_test_update(spec, fin, with_next=1, with_finality=0, participation_rate=0.2), create_test_update(spec, lat, with_next=1, with_finality=0, participation_rate=0.2), create_test_update(spec, sig, with_next=0, with_finality=1, participation_rate=0.2), create_test_update(spec, fin, with_next=0, with_finality=1, participation_rate=0.2), create_test_update(spec, lat, with_next=0, with_finality=1, participation_rate=0.2), create_test_update(spec, att, with_next=0, with_finality=1, participation_rate=0.2), create_test_update(spec, sig, with_next=0, with_finality=0, participation_rate=0.2), create_test_update(spec, att, with_next=0, with_finality=0, participation_rate=0.2), create_test_update(spec, fin, with_next=0, with_finality=0, participation_rate=0.2), create_test_update(spec, lat, with_next=0, with_finality=0, participation_rate=0.2), ] yield "updates", updates for i in range(len(updates) - 1): assert spec.is_better_update(updates[i], updates[i + 1])
8,647
60.771429
108
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/light_client/test_single_merkle_proof.py
from eth2spec.test.context import ( spec_state_test, with_light_client, with_test_suite_name, ) @with_test_suite_name("BeaconState") @with_light_client @spec_state_test def test_current_sync_committee_merkle_proof(spec, state): yield "object", state current_sync_committee_branch = spec.compute_merkle_proof_for_state( state, spec.CURRENT_SYNC_COMMITTEE_INDEX) yield "proof", { "leaf": "0x" + state.current_sync_committee.hash_tree_root().hex(), "leaf_index": spec.CURRENT_SYNC_COMMITTEE_INDEX, "branch": ['0x' + root.hex() for root in current_sync_committee_branch] } assert spec.is_valid_merkle_branch( leaf=state.current_sync_committee.hash_tree_root(), branch=current_sync_committee_branch, depth=spec.floorlog2(spec.CURRENT_SYNC_COMMITTEE_INDEX), index=spec.get_subtree_index(spec.CURRENT_SYNC_COMMITTEE_INDEX), root=state.hash_tree_root(), ) @with_test_suite_name("BeaconState") @with_light_client @spec_state_test def test_next_sync_committee_merkle_proof(spec, state): yield "object", state next_sync_committee_branch = spec.compute_merkle_proof_for_state( state, spec.NEXT_SYNC_COMMITTEE_INDEX) yield "proof", { "leaf": "0x" + state.next_sync_committee.hash_tree_root().hex(), "leaf_index": spec.NEXT_SYNC_COMMITTEE_INDEX, "branch": ['0x' + root.hex() for root in next_sync_committee_branch] } assert spec.is_valid_merkle_branch( leaf=state.next_sync_committee.hash_tree_root(), branch=next_sync_committee_branch, depth=spec.floorlog2(spec.NEXT_SYNC_COMMITTEE_INDEX), index=spec.get_subtree_index(spec.NEXT_SYNC_COMMITTEE_INDEX), root=state.hash_tree_root(), ) @with_test_suite_name("BeaconState") @with_light_client @spec_state_test def test_finality_root_merkle_proof(spec, state): yield "object", state finality_branch = spec.compute_merkle_proof_for_state( state, spec.FINALIZED_ROOT_INDEX) yield "proof", { "leaf": "0x" + state.finalized_checkpoint.root.hex(), "leaf_index": spec.FINALIZED_ROOT_INDEX, "branch": ['0x' + root.hex() for root in finality_branch] } assert spec.is_valid_merkle_branch( leaf=state.finalized_checkpoint.root, branch=finality_branch, depth=spec.floorlog2(spec.FINALIZED_ROOT_INDEX), index=spec.get_subtree_index(spec.FINALIZED_ROOT_INDEX), root=state.hash_tree_root(), )
2,518
34.985714
79
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/altair/light_client/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/random/test_random.py
""" This module is generated from the ``random`` test generator. Please do not edit this file manually. See the README for that generator for more information. """ from eth2spec.test.helpers.constants import DENEB from eth2spec.test.context import ( misc_balances_in_default_range_with_many_validators, with_phases, zero_activation_threshold, only_generator, ) from eth2spec.test.context import ( always_bls, spec_test, with_custom_state, single_phase, ) from eth2spec.test.utils.randomized_block_tests import ( run_generated_randomized_test, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_0(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_1(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_2(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_3(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_4(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_5(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_6(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_7(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_8(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_9(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_10(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_11(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_12(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_13(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_14(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([DENEB]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_15(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_deneb scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_deneb', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_deneb'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, )
28,092
62.993166
933
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/random/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/block_processing/test_process_voluntary_exit.py
from eth2spec.test.context import ( always_bls, spec_state_test, with_deneb_and_later, ) from eth2spec.test.helpers.constants import ( DENEB, ) from eth2spec.test.bellatrix.block_processing.test_process_voluntary_exit import ( run_voluntary_exit_processing_test, ) @with_deneb_and_later @spec_state_test @always_bls def test_invalid_voluntary_exit_with_current_fork_version_not_is_before_fork_epoch(spec, state): """ Since Deneb, the VoluntaryExit domain is fixed to `CAPELLA_FORK_VERSION` """ assert state.fork.current_version != spec.config.CAPELLA_FORK_VERSION yield from run_voluntary_exit_processing_test( spec, state, fork_version=state.fork.current_version, is_before_fork_epoch=False, valid=False, ) @with_deneb_and_later @spec_state_test @always_bls def test_voluntary_exit_with_previous_fork_version_not_is_before_fork_epoch(spec, state): """ Since Deneb, the VoluntaryExit domain is fixed to `CAPELLA_FORK_VERSION` Note: This test is valid for ``spec.fork == DENEB`` and invalid for subsequent forks """ assert state.fork.previous_version != state.fork.current_version if spec.fork == DENEB: assert state.fork.previous_version == spec.config.CAPELLA_FORK_VERSION yield from run_voluntary_exit_processing_test( spec, state, fork_version=state.fork.previous_version, is_before_fork_epoch=False, ) else: assert state.fork.previous_version != spec.config.CAPELLA_FORK_VERSION yield from run_voluntary_exit_processing_test( spec, state, fork_version=state.fork.previous_version, is_before_fork_epoch=False, valid=False, ) @with_deneb_and_later @spec_state_test @always_bls def test_voluntary_exit_with_previous_fork_version_is_before_fork_epoch(spec, state): """ Since Deneb, the VoluntaryExit domain is fixed to `CAPELLA_FORK_VERSION` Note: This test is valid for ``spec.fork == DENEB`` and invalid for subsequent forks """ assert state.fork.previous_version != state.fork.current_version if spec.fork == DENEB: assert state.fork.previous_version == spec.config.CAPELLA_FORK_VERSION yield from run_voluntary_exit_processing_test( spec, state, fork_version=state.fork.previous_version, is_before_fork_epoch=True, ) else: assert state.fork.previous_version != spec.config.CAPELLA_FORK_VERSION yield from run_voluntary_exit_processing_test( spec, state, fork_version=state.fork.previous_version, is_before_fork_epoch=True, valid=False, )
2,804
30.516854
96
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/block_processing/test_process_execution_payload.py
from random import Random from eth2spec.test.helpers.execution_payload import ( build_empty_execution_payload, compute_el_block_hash, get_execution_payload_header, ) from eth2spec.test.context import ( spec_state_test, expect_assertion_error, with_deneb_and_later ) from eth2spec.test.helpers.sharding import ( get_sample_opaque_tx, ) def run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments, valid=True, execution_valid=True): """ Run ``process_execution_payload``, yielding: - pre-state ('pre') - execution payload ('execution_payload') - execution details, to mock EVM execution ('execution.yml', a dict with 'execution_valid' key and boolean value) - post-state ('post'). If ``valid == False``, run expecting ``AssertionError`` """ # Before Deneb, only `body.execution_payload` matters. `BeaconBlockBody` is just a wrapper. body = spec.BeaconBlockBody( blob_kzg_commitments=blob_kzg_commitments, execution_payload=execution_payload ) yield 'pre', state yield 'execution', {'execution_valid': execution_valid} yield 'body', body called_new_block = False class TestEngine(spec.NoopExecutionEngine): def verify_and_notify_new_payload(self, new_payload_request) -> bool: nonlocal called_new_block, execution_valid called_new_block = True assert new_payload_request.execution_payload == body.execution_payload return execution_valid if not valid: expect_assertion_error(lambda: spec.process_execution_payload(state, body, TestEngine())) yield 'post', None return spec.process_execution_payload(state, body, TestEngine()) # Make sure we called the engine assert called_new_block yield 'post', state assert state.latest_execution_payload_header == get_execution_payload_header(spec, body.execution_payload) @with_deneb_and_later @spec_state_test def test_incorrect_blob_tx_type(spec, state): """ The versioned hashes are wrong, but the testing ExecutionEngine returns VALID by default. """ execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec) opaque_tx = b'\x04' + opaque_tx[1:] # incorrect tx type execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments) @with_deneb_and_later @spec_state_test def test_incorrect_transaction_length_1_byte(spec, state): """ The versioned hashes are wrong, but the testing ExecutionEngine returns VALID by default. """ execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec) opaque_tx = opaque_tx + b'\x12' # incorrect tx length execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments) @with_deneb_and_later @spec_state_test def test_incorrect_transaction_length_32_bytes(spec, state): """ The versioned hashes are wrong, but the testing ExecutionEngine returns VALID by default. """ execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec) opaque_tx = opaque_tx + b'\x12' * 32 # incorrect tx length execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments) @with_deneb_and_later @spec_state_test def test_incorrect_commitment(spec, state): """ The versioned hashes are wrong, but the testing ExecutionEngine returns VALID by default. """ execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec) blob_kzg_commitments[0] = b'\x12' * 48 # incorrect commitment execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments) @with_deneb_and_later @spec_state_test def test_incorrect_commitments_order(spec, state): """ The versioned hashes are wrong, but the testing ExecutionEngine returns VALID by default. """ execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec, blob_count=2, rng=Random(1111)) blob_kzg_commitments = [blob_kzg_commitments[1], blob_kzg_commitments[0]] # incorrect order execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments) @with_deneb_and_later @spec_state_test def test_incorrect_block_hash(spec, state): execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec) execution_payload.transactions = [opaque_tx] execution_payload.block_hash = b'\x12' * 32 # incorrect block hash # CL itself doesn't verify EL block hash yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments) @with_deneb_and_later @spec_state_test def test_zeroed_commitment(spec, state): """ The blob is invalid, but the commitment is in correct form. """ execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec, blob_count=1, is_valid_blob=False) assert all(commitment == b'\x00' * 48 for commitment in blob_kzg_commitments) execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments) @with_deneb_and_later @spec_state_test def test_invalid_correct_input__execution_invalid(spec, state): """ The versioned hashes are wrong, but the testing ExecutionEngine returns VALID by default. """ execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec) execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments, valid=False, execution_valid=False) @with_deneb_and_later @spec_state_test def test_invalid_exceed_max_blobs_per_block(spec, state): execution_payload = build_empty_execution_payload(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec, blob_count=spec.MAX_BLOBS_PER_BLOCK + 1) execution_payload.transactions = [opaque_tx] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, blob_kzg_commitments, valid=False)
7,618
35.985437
119
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/block_processing/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/sanity/test_blocks.py
from eth2spec.test.helpers.state import ( state_transition_and_sign_block, next_epoch_via_block, transition_to, ) from eth2spec.test.helpers.block import ( build_empty_block_for_next_slot, ) from eth2spec.test.context import ( DENEB, spec_state_test, spec_configured_state_test, with_deneb_and_later, with_phases, ) from eth2spec.test.helpers.execution_payload import ( compute_el_block_hash, ) from eth2spec.test.helpers.attestations import ( get_valid_attestation, ) from eth2spec.test.helpers.sharding import ( get_sample_opaque_tx, ) def run_block_with_blobs(spec, state, blob_count, data_gas_used=1, excess_data_gas=1, valid=True): yield 'pre', state block = build_empty_block_for_next_slot(spec, state) opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec, blob_count=blob_count) block.body.blob_kzg_commitments = blob_kzg_commitments block.body.execution_payload.transactions = [opaque_tx] block.body.execution_payload.data_gas_used = data_gas_used block.body.execution_payload.excess_data_gas = excess_data_gas block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) if valid: signed_block = state_transition_and_sign_block(spec, state, block) else: signed_block = state_transition_and_sign_block(spec, state, block, expect_fail=True) yield 'blocks', [signed_block] yield 'post', state if valid else None @with_deneb_and_later @spec_state_test def test_zero_blob(spec, state): yield from run_block_with_blobs(spec, state, blob_count=0) @with_deneb_and_later @spec_state_test def test_one_blob(spec, state): yield from run_block_with_blobs(spec, state, blob_count=1) @with_deneb_and_later @spec_state_test def test_max_blobs_per_block(spec, state): yield from run_block_with_blobs(spec, state, blob_count=spec.MAX_BLOBS_PER_BLOCK) @with_deneb_and_later @spec_state_test def test_invalid_exceed_max_blobs_per_block(spec, state): yield from run_block_with_blobs(spec, state, blob_count=spec.MAX_BLOBS_PER_BLOCK + 1, valid=False) @with_phases([DENEB]) @spec_configured_state_test({ 'DENEB_FORK_EPOCH': 2, }) def test_include_attestation_from_previous_fork_with_new_range(spec, state): # Transition to the epoch prior to the fork epoch next_epoch_via_block(spec, state) # Generate an attestation for slot 0 of this epoch attestation = get_valid_attestation(spec, state, signed=True) # Transition to second to last slot in `DENEB_FORK_EPOCH` next_epoch_via_block(spec, state) current_epoch = spec.get_current_epoch(state) assert current_epoch == spec.config.DENEB_FORK_EPOCH penultimate_slot = spec.compute_start_slot_at_epoch(current_epoch + 1) - 2 transition_to(spec, state, penultimate_slot) # Ensure the new state is in the increased EIP-7045 slot inclusion range assert penultimate_slot - attestation.data.slot > spec.SLOTS_PER_EPOCH block = build_empty_block_for_next_slot(spec, state) block.body.attestations.append(attestation) yield 'pre', state signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state
3,258
31.267327
103
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/sanity/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/unittests/test_config_invariants.py
from eth2spec.test.context import ( single_phase, spec_test, with_deneb_and_later, ) @with_deneb_and_later @spec_test @single_phase def test_length(spec): assert spec.MAX_BLOBS_PER_BLOCK < spec.MAX_BLOB_COMMITMENTS_PER_BLOCK @with_deneb_and_later @spec_test @single_phase def test_networking(spec): assert spec.MAX_BLOBS_PER_BLOCK < spec.MAX_BLOB_COMMITMENTS_PER_BLOCK assert spec.config.MAX_REQUEST_BLOB_SIDECARS == spec.config.MAX_REQUEST_BLOCKS_DENEB * spec.MAX_BLOBS_PER_BLOCK # Start with the same size, but `BLOB_SIDECAR_SUBNET_COUNT` could potentially increase later. assert spec.config.BLOB_SIDECAR_SUBNET_COUNT == spec.MAX_BLOBS_PER_BLOCK
684
28.782609
115
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/unittests/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/unittests/validator/test_validator.py
from eth2spec.test.context import ( always_bls, spec_state_test, with_deneb_and_later, ) from eth2spec.test.helpers.execution_payload import ( compute_el_block_hash, ) from eth2spec.test.helpers.sharding import ( get_sample_opaque_tx, ) from eth2spec.test.helpers.block import ( build_empty_block_for_next_slot ) from eth2spec.test.helpers.keys import ( pubkey_to_privkey ) @with_deneb_and_later @spec_state_test def test_blob_sidecar_signature(spec, state): """ Test `get_blob_sidecar_signature` """ blob_count = 4 block = build_empty_block_for_next_slot(spec, state) opaque_tx, blobs, blob_kzg_commitments, proofs = get_sample_opaque_tx(spec, blob_count=blob_count) block.body.blob_kzg_commitments = blob_kzg_commitments block.body.execution_payload.transactions = [opaque_tx] block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) blob_sidecars = spec.get_blob_sidecars(block, blobs, proofs) proposer = state.validators[blob_sidecars[1].proposer_index] privkey = pubkey_to_privkey[proposer.pubkey] sidecar_signature = spec.get_blob_sidecar_signature(state, blob_sidecars[1], privkey) signed_blob_sidecar = spec.SignedBlobSidecar(message=blob_sidecars[1], signature=sidecar_signature) assert spec.verify_blob_sidecar_signature(state, signed_blob_sidecar) @with_deneb_and_later @spec_state_test @always_bls def test_blob_sidecar_signature_incorrect(spec, state): """ Test `get_blob_sidecar_signature` """ blob_count = 4 block = build_empty_block_for_next_slot(spec, state) opaque_tx, blobs, blob_kzg_commitments, proofs = get_sample_opaque_tx(spec, blob_count=blob_count) block.body.blob_kzg_commitments = blob_kzg_commitments block.body.execution_payload.transactions = [opaque_tx] block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) blob_sidecars = spec.get_blob_sidecars(block, blobs, proofs) sidecar_signature = spec.get_blob_sidecar_signature(state, blob_sidecars[1], 123) signed_blob_sidecar = spec.SignedBlobSidecar(message=blob_sidecars[1], signature=sidecar_signature) assert not spec.verify_blob_sidecar_signature(state, signed_blob_sidecar)
2,521
36.088235
103
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/unittests/validator/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/unittests/polynomial_commitments/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/unittests/polynomial_commitments/test_polynomial_commitments.py
import random from eth2spec.test.context import ( spec_test, single_phase, with_deneb_and_later, expect_assertion_error, always_bls ) from eth2spec.test.helpers.sharding import ( get_sample_blob, get_poly_in_both_forms, eval_poly_in_coeff_form, ) from eth2spec.utils import bls from eth2spec.utils.bls import BLS_MODULUS G1 = bls.G1_to_bytes48(bls.G1()) P1_NOT_IN_G1 = bytes.fromhex("8123456789abcdef0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef0123456789abcdef") P1_NOT_ON_CURVE = bytes.fromhex("8123456789abcdef0123456789abcdef0123456789abcdef" + "0123456789abcdef0123456789abcdef0123456789abcde0") def bls_add_one(x): """ Adds "one" (actually bls.G1()) to a compressed group element. Useful to compute definitely incorrect proofs. """ return bls.G1_to_bytes48( bls.add(bls.bytes48_to_G1(x), bls.G1()) ) def field_element_bytes(x): return int.to_bytes(x % BLS_MODULUS, 32, "big") @with_deneb_and_later @spec_test @single_phase def test_verify_kzg_proof(spec): """ Test the wrapper functions (taking bytes arguments) for computing and verifying KZG proofs. """ x = field_element_bytes(3) blob = get_sample_blob(spec) commitment = spec.blob_to_kzg_commitment(blob) proof, y = spec.compute_kzg_proof(blob, x) assert spec.verify_kzg_proof(commitment, x, y, proof) @with_deneb_and_later @spec_test @single_phase def test_verify_kzg_proof_incorrect_proof(spec): """ Test the wrapper function `verify_kzg_proof` fails on an incorrect proof. """ x = field_element_bytes(3465) blob = get_sample_blob(spec) commitment = spec.blob_to_kzg_commitment(blob) proof, y = spec.compute_kzg_proof(blob, x) proof = bls_add_one(proof) assert not spec.verify_kzg_proof(commitment, x, y, proof) @with_deneb_and_later @spec_test @single_phase def test_verify_kzg_proof_impl(spec): """ Test the implementation functions (taking field element arguments) for computing and verifying KZG proofs. """ x = BLS_MODULUS - 1 blob = get_sample_blob(spec) commitment = spec.blob_to_kzg_commitment(blob) polynomial = spec.blob_to_polynomial(blob) proof, y = spec.compute_kzg_proof_impl(polynomial, x) assert spec.verify_kzg_proof_impl(commitment, x, y, proof) @with_deneb_and_later @spec_test @single_phase def test_verify_kzg_proof_impl_incorrect_proof(spec): """ Test the implementation function `verify_kzg_proof` fails on an incorrect proof. """ x = 324561 blob = get_sample_blob(spec) commitment = spec.blob_to_kzg_commitment(blob) polynomial = spec.blob_to_polynomial(blob) proof, y = spec.compute_kzg_proof_impl(polynomial, x) proof = bls_add_one(proof) assert not spec.verify_kzg_proof_impl(commitment, x, y, proof) @with_deneb_and_later @spec_test @single_phase def test_barycentric_outside_domain(spec): """ Test barycentric formula correctness by using it to evaluate a polynomial at a bunch of points outside its domain (the roots of unity). Then make sure that we would get the same result if we evaluated it from coefficient form without using the barycentric formula """ rng = random.Random(5566) poly_coeff, poly_eval = get_poly_in_both_forms(spec) roots_of_unity_brp = spec.bit_reversal_permutation(spec.ROOTS_OF_UNITY) assert len(poly_coeff) == len(poly_eval) == len(roots_of_unity_brp) n_samples = 12 for _ in range(n_samples): # Get a random evaluation point and make sure it's not a root of unity z = rng.randint(0, BLS_MODULUS - 1) while z in roots_of_unity_brp: z = rng.randint(0, BLS_MODULUS - 1) # Get p(z) by evaluating poly in coefficient form p_z_coeff = eval_poly_in_coeff_form(spec, poly_coeff, z) # Get p(z) by evaluating poly in evaluation form p_z_eval = spec.evaluate_polynomial_in_evaluation_form(poly_eval, z) # Both evaluations should agree assert p_z_coeff == p_z_eval @with_deneb_and_later @spec_test @single_phase def test_barycentric_within_domain(spec): """ Test barycentric formula correctness by using it to evaluate a polynomial at all the points of its domain (the roots of unity). Then make sure that we would get the same result if we evaluated it from coefficient form without using the barycentric formula """ poly_coeff, poly_eval = get_poly_in_both_forms(spec) roots_of_unity_brp = spec.bit_reversal_permutation(spec.ROOTS_OF_UNITY) assert len(poly_coeff) == len(poly_eval) == len(roots_of_unity_brp) n = len(poly_coeff) # Iterate over the entire domain for i in range(n): # Grab a root of unity and use it as the evaluation point z = int(roots_of_unity_brp[i]) # Get p(z) by evaluating poly in coefficient form p_z_coeff = eval_poly_in_coeff_form(spec, poly_coeff, z) # Get p(z) by evaluating poly in evaluation form p_z_eval = spec.evaluate_polynomial_in_evaluation_form(poly_eval, z) # The two evaluations should be agree and p(z) should also be the i-th "coefficient" of the polynomial in # evaluation form assert p_z_coeff == p_z_eval == poly_eval[i] @with_deneb_and_later @spec_test @single_phase def test_compute_kzg_proof_within_domain(spec): """ Create and verify KZG proof that p(z) == y where z is in the domain of our KZG scheme (i.e. a relevant root of unity). """ blob = get_sample_blob(spec) commitment = spec.blob_to_kzg_commitment(blob) polynomial = spec.blob_to_polynomial(blob) roots_of_unity_brp = spec.bit_reversal_permutation(spec.ROOTS_OF_UNITY) for i, z in enumerate(roots_of_unity_brp): proof, y = spec.compute_kzg_proof_impl(polynomial, z) assert spec.verify_kzg_proof_impl(commitment, z, y, proof) @with_deneb_and_later @spec_test @single_phase def test_verify_blob_kzg_proof(spec): """ Test the functions to compute and verify a blob KZG proof """ blob = get_sample_blob(spec) commitment = spec.blob_to_kzg_commitment(blob) proof = spec.compute_blob_kzg_proof(blob, commitment) assert spec.verify_blob_kzg_proof(blob, commitment, proof) @with_deneb_and_later @spec_test @single_phase def test_verify_blob_kzg_proof_incorrect_proof(spec): """ Check that `verify_blob_kzg_proof` fails on an incorrect proof """ blob = get_sample_blob(spec) commitment = spec.blob_to_kzg_commitment(blob) proof = spec.compute_blob_kzg_proof(blob, commitment) proof = bls_add_one(proof) assert not spec.verify_blob_kzg_proof(blob, commitment, proof) @with_deneb_and_later @spec_test @single_phase def test_bls_modular_inverse(spec): """ Verify computation of multiplicative inverse """ rng = random.Random(5566) # Should fail for x == 0 expect_assertion_error(lambda: spec.bls_modular_inverse(0)) expect_assertion_error(lambda: spec.bls_modular_inverse(spec.BLS_MODULUS)) expect_assertion_error(lambda: spec.bls_modular_inverse(2 * spec.BLS_MODULUS)) # Test a trivial inversion assert 1 == int(spec.bls_modular_inverse(1)) # Test a random inversion r = rng.randint(0, spec.BLS_MODULUS - 1) r_inv = int(spec.bls_modular_inverse(r)) assert r * r_inv % BLS_MODULUS == 1 @with_deneb_and_later @spec_test @single_phase def test_validate_kzg_g1_generator(spec): """ Verify that `validate_kzg_g1` allows the generator G1 """ spec.validate_kzg_g1(bls.G1_to_bytes48(bls.G1())) @with_deneb_and_later @spec_test @single_phase def test_validate_kzg_g1_neutral_element(spec): """ Verify that `validate_kzg_g1` allows the neutral element in G1 """ spec.validate_kzg_g1(bls.G1_to_bytes48(bls.Z1())) @with_deneb_and_later @spec_test @single_phase @always_bls def test_validate_kzg_g1_not_in_g1(spec): """ Verify that `validate_kzg_g1` fails on point not in G1 """ expect_assertion_error(lambda: spec.validate_kzg_g1(P1_NOT_IN_G1)) @with_deneb_and_later @spec_test @single_phase @always_bls def test_validate_kzg_g1_not_on_curve(spec): """ Verify that `validate_kzg_g1` fails on point not in G1 """ expect_assertion_error(lambda: spec.validate_kzg_g1(P1_NOT_ON_CURVE)) @with_deneb_and_later @spec_test @single_phase def test_bytes_to_bls_field_zero(spec): """ Verify that `bytes_to_bls_field` handles zero """ spec.bytes_to_bls_field(b"\0" * 32) @with_deneb_and_later @spec_test @single_phase def test_bytes_to_bls_field_modulus_minus_one(spec): """ Verify that `bytes_to_bls_field` handles modulus minus one """ spec.bytes_to_bls_field((BLS_MODULUS - 1).to_bytes(spec.BYTES_PER_FIELD_ELEMENT, spec.KZG_ENDIANNESS)) @with_deneb_and_later @spec_test @single_phase def test_bytes_to_bls_field_modulus(spec): """ Verify that `bytes_to_bls_field` fails on BLS modulus """ expect_assertion_error(lambda: spec.bytes_to_bls_field( BLS_MODULUS.to_bytes(spec.BYTES_PER_FIELD_ELEMENT, spec.KZG_ENDIANNESS) )) @with_deneb_and_later @spec_test @single_phase def test_bytes_to_bls_field_max(spec): """ Verify that `bytes_to_bls_field` fails on 2**256 - 1 """ expect_assertion_error(lambda: spec.bytes_to_bls_field(b"\xFF" * 32))
9,455
27.481928
117
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/transition/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/transition/test_operations.py
from eth2spec.test.context import ( ForkMeta, always_bls, with_fork_metas, ) from eth2spec.test.helpers.constants import ( AFTER_DENEB_PRE_POST_FORKS, ) from eth2spec.test.helpers.fork_transition import ( OperationType, run_transition_with_operation, ) # # BLSToExecutionChange # @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in AFTER_DENEB_PRE_POST_FORKS]) @always_bls def test_transition_with_btec_right_after_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create a BLS_TO_EXECUTION_CHANGE right *after* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.BLS_TO_EXECUTION_CHANGE, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH, ) @with_fork_metas([ForkMeta(pre_fork_name=pre, post_fork_name=post, fork_epoch=2) for pre, post in AFTER_DENEB_PRE_POST_FORKS]) @always_bls def test_transition_with_btec_right_before_fork(state, fork_epoch, spec, post_spec, pre_tag, post_tag): """ Create a BLS_TO_EXECUTION_CHANGE right *before* the transition """ yield from run_transition_with_operation( state, fork_epoch, spec, post_spec, pre_tag, post_tag, operation_type=OperationType.BLS_TO_EXECUTION_CHANGE, operation_at_slot=fork_epoch * spec.SLOTS_PER_EPOCH - 1, )
1,555
27.290909
103
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/fork/test_deneb_fork_random.py
from random import Random from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( CAPELLA, DENEB, MINIMAL, ) from eth2spec.test.helpers.deneb.fork import ( DENEB_FORK_TEST_META_TAGS, run_fork_test, ) from eth2spec.test.helpers.random import randomize_state @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_deneb_fork_random_0(spec, phases, state): randomize_state(spec, state, rng=Random(1010)) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_deneb_fork_random_1(spec, phases, state): randomize_state(spec, state, rng=Random(2020)) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_deneb_fork_random_2(spec, phases, state): randomize_state(spec, state, rng=Random(3030)) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_deneb_fork_random_3(spec, phases, state): randomize_state(spec, state, rng=Random(4040)) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_deneb_fork_random_low_balances(spec, phases, state): randomize_state(spec, state, rng=Random(5050)) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_deneb_fork_random_misc_balances(spec, phases, state): randomize_state(spec, state, rng=Random(6060)) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @spec_test @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_deneb_fork_random_large_validator_set(spec, phases, state): randomize_state(spec, state, rng=Random(7070)) yield from run_fork_test(phases[DENEB], state)
2,864
32.705882
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/fork/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/deneb/fork/test_deneb_fork_basic.py
from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( CAPELLA, DENEB, MINIMAL, ) from eth2spec.test.helpers.state import ( next_epoch, next_epoch_via_block, ) from eth2spec.test.helpers.deneb.fork import ( DENEB_FORK_TEST_META_TAGS, run_fork_test, ) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_fork_base_state(spec, phases, state): yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_fork_next_epoch(spec, phases, state): next_epoch(spec, state) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_fork_next_epoch_with_block(spec, phases, state): next_epoch_via_block(spec, state) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @spec_test @with_state @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_fork_many_next_epoch(spec, phases, state): for _ in range(3): next_epoch(spec, state) yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_fork_random_low_balances(spec, phases, state): yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_fork_random_misc_balances(spec, phases, state): yield from run_fork_test(phases[DENEB], state) @with_phases(phases=[CAPELLA], other_phases=[DENEB]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(DENEB_FORK_TEST_META_TAGS) def test_fork_random_large_validator_set(spec, phases, state): yield from run_fork_test(phases[DENEB], state)
2,612
30.481928
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/utils/randomized_block_tests.py
""" Utility code to generate randomized block tests """ import sys import warnings from random import Random from typing import Callable from eth2spec.test.helpers.execution_payload import ( compute_el_block_hash, ) from eth2spec.test.helpers.multi_operations import ( build_random_block_from_state_for_next_slot, get_random_bls_to_execution_changes, get_random_sync_aggregate, prepare_state_and_get_random_deposits, ) from eth2spec.test.helpers.inactivity_scores import ( randomize_inactivity_scores, ) from eth2spec.test.helpers.random import ( randomize_state as randomize_state_helper, patch_state_to_non_leaking, ) from eth2spec.test.helpers.sharding import ( get_sample_opaque_tx, ) from eth2spec.test.helpers.state import ( next_slot, next_epoch, ensure_state_has_validators_across_lifecycle, state_transition_and_sign_block, ) # primitives: # state def _randomize_deposit_state(spec, state, stats): """ To introduce valid, randomized deposits, the ``state`` deposit sub-state must be coordinated with the data that will ultimately go into blocks. This function randomizes the ``state`` in a way that can signal downstream to the block constructors how they should (or should not) make some randomized deposits. """ rng = Random(999) block_count = stats.get("block_count", 0) deposits = [] if block_count > 0: num_deposits = rng.randrange(1, block_count * spec.MAX_DEPOSITS) deposits = prepare_state_and_get_random_deposits(spec, state, rng, num_deposits=num_deposits) return { "deposits": deposits, } def randomize_state(spec, state, stats, exit_fraction=0.1, slash_fraction=0.1): randomize_state_helper(spec, state, exit_fraction=exit_fraction, slash_fraction=slash_fraction) scenario_state = _randomize_deposit_state(spec, state, stats) return scenario_state def randomize_state_altair(spec, state, stats, exit_fraction=0.1, slash_fraction=0.1): scenario_state = randomize_state(spec, state, stats, exit_fraction=exit_fraction, slash_fraction=slash_fraction) randomize_inactivity_scores(spec, state) return scenario_state def randomize_state_bellatrix(spec, state, stats, exit_fraction=0.1, slash_fraction=0.1): scenario_state = randomize_state_altair(spec, state, stats, exit_fraction=exit_fraction, slash_fraction=slash_fraction) # TODO: randomize execution payload, merge status, etc. return scenario_state def randomize_state_capella(spec, state, stats, exit_fraction=0.1, slash_fraction=0.1): scenario_state = randomize_state_bellatrix(spec, state, stats, exit_fraction=exit_fraction, slash_fraction=slash_fraction) # TODO: randomize withdrawals return scenario_state def randomize_state_deneb(spec, state, stats, exit_fraction=0.1, slash_fraction=0.1): scenario_state = randomize_state_capella(spec, state, stats, exit_fraction=exit_fraction, slash_fraction=slash_fraction) # TODO: randomize execution payload return scenario_state # epochs def epochs_until_leak(spec): """ State is "leaking" if the current epoch is at least this value after the last finalized epoch. """ return spec.MIN_EPOCHS_TO_INACTIVITY_PENALTY + 1 def epochs_for_shard_committee_period(spec): return spec.config.SHARD_COMMITTEE_PERIOD # slots def last_slot_in_epoch(spec): return spec.SLOTS_PER_EPOCH - 1 def random_slot_in_epoch(spec, rng=Random(1336)): return rng.randrange(1, spec.SLOTS_PER_EPOCH - 2) def penultimate_slot_in_epoch(spec): return spec.SLOTS_PER_EPOCH - 2 # blocks def no_block(_spec, _pre_state, _signed_blocks, _scenario_state): return None # May need to make several attempts to find a block that does not correspond to a slashed # proposer with the randomization helpers... BLOCK_ATTEMPTS = 32 def _warn_if_empty_operations(block): """ NOTE: a block may be missing deposits depending on how many were created and already inserted into existing blocks in a given scenario. """ if len(block.body.proposer_slashings) == 0: warnings.warn(f"proposer slashings missing in block at slot {block.slot}") if len(block.body.attester_slashings) == 0: warnings.warn(f"attester slashings missing in block at slot {block.slot}") if len(block.body.attestations) == 0: warnings.warn(f"attestations missing in block at slot {block.slot}") if len(block.body.voluntary_exits) == 0: warnings.warn(f"voluntary exits missing in block at slot {block.slot}") def _pull_deposits_from_scenario_state(spec, scenario_state, existing_block_count): all_deposits = scenario_state.get("deposits", []) start = existing_block_count * spec.MAX_DEPOSITS return all_deposits[start:start + spec.MAX_DEPOSITS] def random_block(spec, state, signed_blocks, scenario_state): """ Produce a random block. NOTE: this helper may mutate state, as it will attempt to produce a block over ``BLOCK_ATTEMPTS`` slots in order to find a valid block in the event that the proposer has already been slashed. """ # NOTE: ``state`` has been "randomized" at this point and so will likely # contain a large number of slashed validators. This function needs to return # a valid block so it needs to check that the proposer of the next slot is not # slashed. # To do this, generate a ``temp_state`` to use for checking the propser in the next slot. # This ensures no accidental mutations happen to the ``state`` the caller expects to get back # after this function returns. # Using a copy of the state for proposer sampling is also sound as any inputs used for the # shuffling are fixed a few epochs prior to ``spec.get_current_epoch(state)``. temp_state = state.copy() next_slot(spec, temp_state) for _ in range(BLOCK_ATTEMPTS): proposer_index = spec.get_beacon_proposer_index(temp_state) proposer = state.validators[proposer_index] if proposer.slashed: next_slot(spec, state) next_slot(spec, temp_state) else: deposits_for_block = _pull_deposits_from_scenario_state(spec, scenario_state, len(signed_blocks)) block = build_random_block_from_state_for_next_slot(spec, state, deposits=deposits_for_block) _warn_if_empty_operations(block) return block else: raise AssertionError("could not find a block with an unslashed proposer, check ``state`` input") SYNC_AGGREGATE_PARTICIPATION_BUCKETS = 4 def random_block_altair_with_cycling_sync_committee_participation(spec, state, signed_blocks, scenario_state): block = random_block(spec, state, signed_blocks, scenario_state) block_index = len(signed_blocks) % SYNC_AGGREGATE_PARTICIPATION_BUCKETS fraction_missed = block_index * (1 / SYNC_AGGREGATE_PARTICIPATION_BUCKETS) fraction_participated = 1.0 - fraction_missed previous_root = block.parent_root block.body.sync_aggregate = get_random_sync_aggregate( spec, state, block.slot - 1, block_root=previous_root, fraction_participated=fraction_participated, ) return block def random_block_bellatrix(spec, state, signed_blocks, scenario_state): block = random_block_altair_with_cycling_sync_committee_participation(spec, state, signed_blocks, scenario_state) # TODO: return randomized execution payload return block def random_block_capella(spec, state, signed_blocks, scenario_state, rng=Random(3456)): block = random_block_bellatrix(spec, state, signed_blocks, scenario_state) block.body.bls_to_execution_changes = get_random_bls_to_execution_changes( spec, state, num_address_changes=rng.randint(1, spec.MAX_BLS_TO_EXECUTION_CHANGES) ) return block def random_block_deneb(spec, state, signed_blocks, scenario_state, rng=Random(3456)): block = random_block_capella(spec, state, signed_blocks, scenario_state) # TODO: more commitments. blob_kzg_commitments: List[KZGCommitment, MAX_BLOBS_PER_BLOCK] opaque_tx, _, blob_kzg_commitments, _ = get_sample_opaque_tx(spec, blob_count=1) block.body.execution_payload.transactions = [opaque_tx] block.body.execution_payload.block_hash = compute_el_block_hash(spec, block.body.execution_payload) block.body.blob_kzg_commitments = blob_kzg_commitments return block # validations def no_op_validation(_spec, _state): return True def validate_is_leaking(spec, state): return spec.is_in_inactivity_leak(state) def validate_is_not_leaking(spec, state): return not validate_is_leaking(spec, state) # transitions def with_validation(transition, validation): if isinstance(transition, Callable): transition = transition() transition["validation"] = validation return transition def no_op_transition(): return {} def epoch_transition(n=0): return { "epochs_to_skip": n, } def slot_transition(n=0): return { "slots_to_skip": n, } def transition_to_leaking(): return { "epochs_to_skip": epochs_until_leak, "validation": validate_is_leaking, } transition_without_leak = with_validation(no_op_transition, validate_is_not_leaking) # block transitions def transition_with_random_block(block_randomizer): """ Build a block transition with randomized data. Provide optional sub-transitions to advance some number of epochs or slots before applying the random block. """ return { "block_producer": block_randomizer, } # setup and test gen def _randomized_scenario_setup(state_randomizer): """ Return a sequence of pairs of ("mutation", "validation"). A "mutation" is a function that accepts (``spec``, ``state``, ``stats``) arguments and allegedly performs some change to the state. A "validation" is a function that accepts (spec, state) arguments and validates some change was made. The "mutation" may return some state that should be available to any down-stream transitions across the **entire** scenario. The ``stats`` parameter reflects a summary of actions in a given scenario like how many blocks will be produced. This data can be useful to construct a valid pre-state and so is provided at the setup stage. """ def _skip_epochs(epoch_producer): def f(spec, state, _stats): """ The unoptimized spec implementation is too slow to advance via ``next_epoch``. Instead, just overwrite the ``state.slot`` and continue... """ epochs_to_skip = epoch_producer(spec) slots_to_skip = epochs_to_skip * spec.SLOTS_PER_EPOCH state.slot += slots_to_skip return f def _simulate_honest_execution(spec, state, _stats): """ Want to start tests not in a leak state; the finality data may not reflect this condition with prior (arbitrary) mutations, so this mutator addresses that fact. """ patch_state_to_non_leaking(spec, state) return ( # NOTE: the block randomization function assumes at least 1 shard committee period # so advance the state before doing anything else. (_skip_epochs(epochs_for_shard_committee_period), no_op_validation), (_simulate_honest_execution, no_op_validation), (state_randomizer, ensure_state_has_validators_across_lifecycle), ) # Run the generated tests: # while the test implementation works via code-gen, # references to helper code in this module are serialized as str names. # to resolve this references at runtime, we need a reference to this module: _this_module = sys.modules[__name__] def _resolve_ref(ref): if isinstance(ref, str): return getattr(_this_module, ref) return ref def _iter_temporal(spec, description): """ Intended to advance some number of {epochs, slots}. Caller can provide a constant integer or a callable deriving a number from the ``spec`` under consideration. """ numeric = _resolve_ref(description) if isinstance(numeric, Callable): numeric = numeric(spec) for i in range(numeric): yield i def _compute_statistics(scenario): block_count = 0 for transition in scenario["transitions"]: block_producer = _resolve_ref(transition.get("block_producer", None)) if block_producer and block_producer != no_block: block_count += 1 return { "block_count": block_count, } def run_generated_randomized_test(spec, state, scenario): stats = _compute_statistics(scenario) if "setup" not in scenario: state_randomizer = _resolve_ref(scenario.get("state_randomizer", randomize_state)) scenario["setup"] = _randomized_scenario_setup(state_randomizer) scenario_state = {} for mutation, validation in scenario["setup"]: additional_state = mutation(spec, state, stats) validation(spec, state) if additional_state: scenario_state.update(additional_state) yield "pre", state blocks = [] for transition in scenario["transitions"]: epochs_to_skip = _iter_temporal(spec, transition["epochs_to_skip"]) for _ in epochs_to_skip: next_epoch(spec, state) slots_to_skip = _iter_temporal(spec, transition["slots_to_skip"]) for _ in slots_to_skip: next_slot(spec, state) block_producer = _resolve_ref(transition["block_producer"]) block = block_producer(spec, state, blocks, scenario_state) if block: signed_block = state_transition_and_sign_block(spec, state, block) blocks.append(signed_block) validation = _resolve_ref(transition["validation"]) assert validation(spec, state) yield "blocks", blocks yield "post", state
14,688
33.481221
117
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/utils/utils.py
from typing import Dict, Any from eth2spec.utils.ssz.ssz_typing import View from eth2spec.utils.ssz.ssz_impl import serialize def vector_test(description: str = None): """ vector_test decorator: Allow a caller to pass "generator_mode=True" to make the test yield data, but behave like a normal test (ignoring the yield, but fully processing) a test when not in "generator_mode" This should always be the most outer decorator around functions that yield data. This is to deal with silent iteration through yielding function when in a pytest context (i.e. not in generator mode). :param description: Optional description for the test to add to the metadata. :return: Decorator. """ def runner(fn): # this wraps the function, to yield type-annotated entries of data. # Valid types are: # - "meta": all key-values with this type can be collected by the generator, to put somewhere together. # - "cfg": spec config dictionary # - "ssz": raw SSZ bytes # - "data": a python structure to be encoded by the user. def entry(*args, **kw): def generator_mode(): if description is not None: # description can be explicit yield 'description', 'meta', description # transform the yielded data, and add type annotations for data in fn(*args, **kw): # if not 2 items, then it is assumed to be already formatted with a type: # e.g. ("bls_setting", "meta", 1) if len(data) != 2: yield data continue # Try to infer the type, but keep it as-is if it's not a SSZ type or bytes. (key, value) = data if value is None: continue if isinstance(value, View): yield key, 'ssz', serialize(value) elif isinstance(value, bytes): yield key, 'ssz', value elif isinstance(value, list) and all([isinstance(el, (View, bytes)) for el in value]): for i, el in enumerate(value): if isinstance(el, View): yield f'{key}_{i}', 'ssz', serialize(el) elif isinstance(el, bytes): yield f'{key}_{i}', 'ssz', el yield f'{key}_count', 'meta', len(value) else: # Not a ssz value. # The data will now just be yielded as any python data, # something that should be encodable by the generator runner. yield key, 'data', value # check generator mode, may be None/else. # "pop" removes it, so it is not passed to the inner function. if kw.pop('generator_mode', False) is True: # return the yielding function as a generator object. # Don't yield in this function itself, that would make pytest skip over it. return generator_mode() else: # Just complete the function, ignore all yielded data, # we are not using it (or processing it, i.e. nearly zero efficiency loss) # Pytest does not support yielded data in the outer function, so we need to wrap it like this. for _ in fn(*args, **kw): continue return None return entry return runner def with_meta_tags(tags: Dict[str, Any]): """ Decorator factory, yields meta tags (key, value) pairs to the output of the function. Useful to build test-vector annotations with. :param tags: dict of tags :return: Decorator. """ def runner(fn): def entry(*args, **kw): yielded_any = False for part in fn(*args, **kw): yield part yielded_any = True # Do not add tags if the function is not returning a dict at all (i.e. not in generator mode). # As a pytest, we do not want to be yielding anything (unsupported by pytest) if yielded_any: for k, v in tags.items(): yield k, 'meta', v return entry return runner
4,472
45.113402
113
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/utils/__init__.py
from .utils import ( vector_test, with_meta_tags, ) __all__ = [ # avoid "unused import" lint error "vector_test", "with_meta_tags", ]
153
13
47
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/random/test_random.py
""" This module is generated from the ``random`` test generator. Please do not edit this file manually. See the README for that generator for more information. """ from eth2spec.test.helpers.constants import CAPELLA from eth2spec.test.context import ( misc_balances_in_default_range_with_many_validators, with_phases, zero_activation_threshold, only_generator, ) from eth2spec.test.context import ( always_bls, spec_test, with_custom_state, single_phase, ) from eth2spec.test.utils.randomized_block_tests import ( run_generated_randomized_test, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_0(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_1(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_2(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_3(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_4(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_5(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_6(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_7(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_8(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_9(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_10(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_11(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_12(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_13(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_14(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([CAPELLA]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_15(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block_capella scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block_capella', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state_capella'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, )
28,286
63.43508
939
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/random/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/block_processing/test_process_deposit.py
from eth2spec.test.context import ( spec_state_test, with_capella_and_later, ) from eth2spec.test.helpers.state import next_epoch_via_block from eth2spec.test.helpers.deposits import ( prepare_state_and_deposit, run_deposit_processing, ) from eth2spec.test.helpers.withdrawals import set_validator_fully_withdrawable @with_capella_and_later @spec_state_test def test_success_top_up_to_withdrawn_validator(spec, state): validator_index = 0 # Fully withdraw validator set_validator_fully_withdrawable(spec, state, validator_index) assert state.balances[validator_index] > 0 next_epoch_via_block(spec, state) assert state.balances[validator_index] == 0 assert state.validators[validator_index].effective_balance > 0 next_epoch_via_block(spec, state) assert state.validators[validator_index].effective_balance == 0 # Make a top-up balance to validator amount = spec.MAX_EFFECTIVE_BALANCE // 4 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) yield from run_deposit_processing(spec, state, deposit, validator_index) assert state.balances[validator_index] == amount assert state.validators[validator_index].effective_balance == 0 validator = state.validators[validator_index] balance = state.balances[validator_index] current_epoch = spec.get_current_epoch(state) assert spec.is_fully_withdrawable_validator(validator, balance, current_epoch)
1,474
35.875
90
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/block_processing/test_process_bls_to_execution_change.py
from eth2spec.test.helpers.keys import pubkeys from eth2spec.test.helpers.bls_to_execution_changes import get_signed_address_change from eth2spec.test.helpers.constants import CAPELLA, MAINNET from eth2spec.test.context import ( always_bls, expect_assertion_error, spec_state_test, with_capella_and_later, with_presets, with_phases, ) def run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=True): """ Run ``process_bls_to_execution_change``, yielding: - pre-state ('pre') - address-change ('address_change') - post-state ('post'). If ``valid == False``, run expecting ``AssertionError`` """ # yield pre-state yield 'pre', state yield 'address_change', signed_address_change # If the address_change is invalid, processing is aborted, and there is no post-state. if not valid: expect_assertion_error(lambda: spec.process_bls_to_execution_change(state, signed_address_change)) yield 'post', None return # process address change spec.process_bls_to_execution_change(state, signed_address_change) # Make sure the address change has been processed validator_index = signed_address_change.message.validator_index validator = state.validators[validator_index] assert validator.withdrawal_credentials[:1] == spec.ETH1_ADDRESS_WITHDRAWAL_PREFIX assert validator.withdrawal_credentials[1:12] == b'\x00' * 11 assert validator.withdrawal_credentials[12:] == signed_address_change.message.to_execution_address # yield post-state yield 'post', state @with_capella_and_later @spec_state_test def test_success(spec, state): signed_address_change = get_signed_address_change(spec, state) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change) @with_capella_and_later @spec_state_test def test_success_not_activated(spec, state): validator_index = 3 validator = state.validators[validator_index] validator.activation_eligibility_epoch += 4 validator.activation_epoch = spec.FAR_FUTURE_EPOCH assert not spec.is_active_validator(validator, spec.get_current_epoch(state)) signed_address_change = get_signed_address_change(spec, state) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change) validator = state.validators[validator_index] balance = state.balances[validator_index] assert not spec.is_fully_withdrawable_validator(validator, balance, spec.get_current_epoch(state)) @with_capella_and_later @spec_state_test def test_success_in_activation_queue(spec, state): validator_index = 3 validator = state.validators[validator_index] validator.activation_eligibility_epoch = spec.get_current_epoch(state) validator.activation_epoch += 4 assert not spec.is_active_validator(validator, spec.get_current_epoch(state)) signed_address_change = get_signed_address_change(spec, state) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change) validator = state.validators[validator_index] balance = state.balances[validator_index] assert not spec.is_fully_withdrawable_validator(validator, balance, spec.get_current_epoch(state)) @with_capella_and_later @spec_state_test def test_success_in_exit_queue(spec, state): validator_index = 3 spec.initiate_validator_exit(state, validator_index) assert spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) assert spec.get_current_epoch(state) < state.validators[validator_index].exit_epoch signed_address_change = get_signed_address_change(spec, state, validator_index=validator_index) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change) @with_capella_and_later @spec_state_test def test_success_exited(spec, state): validator_index = 4 validator = state.validators[validator_index] validator.exit_epoch = spec.get_current_epoch(state) assert not spec.is_active_validator(validator, spec.get_current_epoch(state)) signed_address_change = get_signed_address_change(spec, state, validator_index=validator_index) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change) validator = state.validators[validator_index] balance = state.balances[validator_index] assert not spec.is_fully_withdrawable_validator(validator, balance, spec.get_current_epoch(state)) @with_capella_and_later @spec_state_test def test_success_withdrawable(spec, state): validator_index = 4 validator = state.validators[validator_index] validator.exit_epoch = spec.get_current_epoch(state) validator.withdrawable_epoch = spec.get_current_epoch(state) assert not spec.is_active_validator(validator, spec.get_current_epoch(state)) signed_address_change = get_signed_address_change(spec, state, validator_index=validator_index) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change) validator = state.validators[validator_index] balance = state.balances[validator_index] assert spec.is_fully_withdrawable_validator(validator, balance, spec.get_current_epoch(state)) @with_capella_and_later @spec_state_test def test_invalid_val_index_out_of_range(spec, state): # Create for one validator beyond the validator list length signed_address_change = get_signed_address_change(spec, state, validator_index=len(state.validators)) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=False) @with_capella_and_later @spec_state_test def test_invalid_already_0x01(spec, state): # Create for one validator beyond the validator list length validator_index = len(state.validators) // 2 validator = state.validators[validator_index] validator.withdrawal_credentials = b'\x01' + b'\x00' * 11 + b'\x23' * 20 signed_address_change = get_signed_address_change(spec, state, validator_index=validator_index) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=False) @with_capella_and_later @spec_state_test def test_invalid_incorrect_from_bls_pubkey(spec, state): # Create for one validator beyond the validator list length validator_index = 2 signed_address_change = get_signed_address_change( spec, state, validator_index=validator_index, withdrawal_pubkey=pubkeys[0], ) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=False) @with_capella_and_later @spec_state_test @always_bls def test_invalid_bad_signature(spec, state): signed_address_change = get_signed_address_change(spec, state) # Mutate signature signed_address_change.signature = spec.BLSSignature(b'\x42' * 96) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=False) @with_capella_and_later @spec_state_test @always_bls def test_genesis_fork_version(spec, state): signed_address_change = get_signed_address_change(spec, state, fork_version=spec.config.GENESIS_FORK_VERSION) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change) @with_capella_and_later @spec_state_test @always_bls def test_invalid_current_fork_version(spec, state): signed_address_change = get_signed_address_change(spec, state, fork_version=state.fork.current_version) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=False) @with_capella_and_later @spec_state_test @always_bls def test_invalid_previous_fork_version(spec, state): signed_address_change = get_signed_address_change(spec, state, fork_version=state.fork.previous_version) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=False) @with_capella_and_later @spec_state_test @always_bls def test_invalid_genesis_validators_root(spec, state): signed_address_change = get_signed_address_change(spec, state, genesis_validators_root=b'\x99' * 32) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change, valid=False) @with_phases([CAPELLA]) @with_presets([MAINNET], reason="use mainnet fork version") @spec_state_test @always_bls def test_valid_signature_from_staking_deposit_cli(spec, state): validator_index = 1 from_bls_pubkey = bytes.fromhex('86248e64705987236ec3c41f6a81d96f98e7b85e842a1d71405b216fa75a9917512f3c94c85779a9729c927ea2aa9ed1') # noqa: E501 to_execution_address = bytes.fromhex('3434343434343434343434343434343434343434') signature = bytes.fromhex('8cf4219884b326a04f6664b680cd9a99ad70b5280745af1147477aa9f8b4a2b2b38b8688c6a74a06f275ad4e14c5c0c70e2ed37a15ece5bf7c0724a376ad4c03c79e14dd9f633a3d54abc1ce4e73bec3524a789ab9a69d4d06686a8a67c9e4dc') # noqa: E501 # Use mainnet `genesis_validators_root` state.genesis_validators_root = bytes.fromhex('4b363db94e286120d76eb905340fdd4e54bfe9f06bf33ff6cf5ad27f511bfe95') validator = state.validators[validator_index] validator.withdrawal_credentials = spec.BLS_WITHDRAWAL_PREFIX + spec.hash(from_bls_pubkey)[1:] address_change = spec.BLSToExecutionChange( validator_index=validator_index, from_bls_pubkey=from_bls_pubkey, to_execution_address=to_execution_address, ) signed_address_change = spec.SignedBLSToExecutionChange( message=address_change, signature=signature, ) yield from run_bls_to_execution_change_processing(spec, state, signed_address_change)
9,640
38.191057
239
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/block_processing/test_process_execution_payload.py
from eth2spec.test.helpers.execution_payload import ( build_empty_execution_payload, compute_el_block_hash, build_state_with_incomplete_transition, ) from eth2spec.test.context import ( spec_state_test, with_capella_and_later, ) from eth2spec.test.helpers.state import next_slot from eth2spec.test.bellatrix.block_processing.test_process_execution_payload import run_execution_payload_processing @with_capella_and_later @spec_state_test def test_invalid_bad_parent_hash_first_payload(spec, state): state = build_state_with_incomplete_transition(spec, state) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.parent_hash = b'\x55' * 32 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_execution_payload_processing(spec, state, execution_payload, valid=False)
904
35.2
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/block_processing/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/block_processing/test_process_withdrawals.py
import random from eth2spec.test.context import ( spec_state_test, expect_assertion_error, with_presets, with_capella_and_later, ) from eth2spec.test.helpers.constants import MAINNET, MINIMAL from eth2spec.test.helpers.execution_payload import ( build_empty_execution_payload, compute_el_block_hash, ) from eth2spec.test.helpers.random import ( randomize_state, ) from eth2spec.test.helpers.state import ( next_epoch, next_slot, ) from eth2spec.test.helpers.withdrawals import ( prepare_expected_withdrawals, set_eth1_withdrawal_credential_with_balance, set_validator_fully_withdrawable, set_validator_partially_withdrawable, ) def verify_post_state(state, spec, expected_withdrawals, fully_withdrawable_indices, partial_withdrawals_indices): # Consider verifying also the condition when no withdrawals are expected. if len(expected_withdrawals) == 0: return expected_withdrawals_validator_indices = [withdrawal.validator_index for withdrawal in expected_withdrawals] assert state.next_withdrawal_index == expected_withdrawals[-1].index + 1 if len(expected_withdrawals) == spec.MAX_WITHDRAWALS_PER_PAYLOAD: # NOTE: ideally we would also check in the case with # fewer than maximum withdrawals but that requires the pre-state info next_withdrawal_validator_index = (expected_withdrawals_validator_indices[-1] + 1) % len(state.validators) assert state.next_withdrawal_validator_index == next_withdrawal_validator_index for index in fully_withdrawable_indices: if index in expected_withdrawals_validator_indices: assert state.balances[index] == 0 else: assert state.balances[index] > 0 for index in partial_withdrawals_indices: if index in expected_withdrawals_validator_indices: assert state.balances[index] == spec.MAX_EFFECTIVE_BALANCE else: assert state.balances[index] > spec.MAX_EFFECTIVE_BALANCE def run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=None, fully_withdrawable_indices=None, partial_withdrawals_indices=None, valid=True): """ Run ``process_withdrawals``, yielding: - pre-state ('pre') - execution payload ('execution_payload') - post-state ('post'). If ``valid == False``, run expecting ``AssertionError`` """ expected_withdrawals = spec.get_expected_withdrawals(state) assert len(expected_withdrawals) <= spec.MAX_WITHDRAWALS_PER_PAYLOAD if num_expected_withdrawals is not None: assert len(expected_withdrawals) == num_expected_withdrawals pre_state = state.copy() yield 'pre', state yield 'execution_payload', execution_payload if not valid: expect_assertion_error(lambda: spec.process_withdrawals(state, execution_payload)) yield 'post', None return spec.process_withdrawals(state, execution_payload) yield 'post', state if len(expected_withdrawals) == 0: next_withdrawal_validator_index = ( pre_state.next_withdrawal_validator_index + spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP ) assert state.next_withdrawal_validator_index == next_withdrawal_validator_index % len(state.validators) elif len(expected_withdrawals) <= spec.MAX_WITHDRAWALS_PER_PAYLOAD: bound = min(spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP, spec.MAX_WITHDRAWALS_PER_PAYLOAD) assert len(spec.get_expected_withdrawals(state)) <= bound elif len(expected_withdrawals) > spec.MAX_WITHDRAWALS_PER_PAYLOAD: raise ValueError('len(expected_withdrawals) should not be greater than MAX_WITHDRAWALS_PER_PAYLOAD') if fully_withdrawable_indices is not None or partial_withdrawals_indices is not None: verify_post_state(state, spec, expected_withdrawals, fully_withdrawable_indices, partial_withdrawals_indices) return expected_withdrawals @with_capella_and_later @spec_state_test def test_success_zero_expected_withdrawals(spec, state): assert len(spec.get_expected_withdrawals(state)) == 0 next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload) @with_capella_and_later @spec_state_test def test_success_one_full_withdrawal(spec, state): fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_full_withdrawals=1) assert len(fully_withdrawable_indices) == 1 assert len(partial_withdrawals_indices) == 0 next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, fully_withdrawable_indices=fully_withdrawable_indices, partial_withdrawals_indices=partial_withdrawals_indices) @with_capella_and_later @spec_state_test def test_success_one_partial_withdrawal(spec, state): fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_partial_withdrawals=1) assert len(fully_withdrawable_indices) == 0 assert len(partial_withdrawals_indices) == 1 for index in partial_withdrawals_indices: assert state.balances[index] > spec.MAX_EFFECTIVE_BALANCE next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, fully_withdrawable_indices=fully_withdrawable_indices, partial_withdrawals_indices=partial_withdrawals_indices ) @with_capella_and_later @spec_state_test def test_success_mixed_fully_and_partial_withdrawable(spec, state): num_full_withdrawals = spec.MAX_WITHDRAWALS_PER_PAYLOAD // 2 num_partial_withdrawals = spec.MAX_WITHDRAWALS_PER_PAYLOAD - num_full_withdrawals fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_full_withdrawals=num_full_withdrawals, num_partial_withdrawals=num_partial_withdrawals, ) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, fully_withdrawable_indices=fully_withdrawable_indices, partial_withdrawals_indices=partial_withdrawals_indices) @with_capella_and_later @with_presets([MAINNET], reason="too few validators with minimal config") @spec_state_test def test_success_all_fully_withdrawable_in_one_sweep(spec, state): assert len(state.validators) <= spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP withdrawal_count = len(state.validators) fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_full_withdrawals=withdrawal_count) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, fully_withdrawable_indices=fully_withdrawable_indices, partial_withdrawals_indices=partial_withdrawals_indices) @with_capella_and_later @with_presets([MINIMAL], reason="too many validators with mainnet config") @spec_state_test def test_success_all_fully_withdrawable(spec, state): assert len(state.validators) > spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP withdrawal_count = spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_full_withdrawals=withdrawal_count) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, fully_withdrawable_indices=fully_withdrawable_indices, partial_withdrawals_indices=partial_withdrawals_indices) @with_capella_and_later @with_presets([MAINNET], reason="too few validators with minimal config") @spec_state_test def test_success_all_partially_withdrawable_in_one_sweep(spec, state): assert len(state.validators) <= spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP withdrawal_count = len(state.validators) fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_partial_withdrawals=withdrawal_count) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, fully_withdrawable_indices=fully_withdrawable_indices, partial_withdrawals_indices=partial_withdrawals_indices) @with_capella_and_later @with_presets([MINIMAL], reason="too many validators with mainnet config") @spec_state_test def test_success_all_partially_withdrawable(spec, state): assert len(state.validators) > spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP withdrawal_count = spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_partial_withdrawals=withdrawal_count) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, fully_withdrawable_indices=fully_withdrawable_indices, partial_withdrawals_indices=partial_withdrawals_indices) # # Failure cases in which the number of withdrawals in the execution_payload is incorrect # @with_capella_and_later @spec_state_test def test_invalid_non_withdrawable_non_empty_withdrawals(spec, state): next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) withdrawal = spec.Withdrawal( index=0, validator_index=0, address=b'\x30' * 20, amount=420, ) execution_payload.withdrawals.append(withdrawal) execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_one_expected_full_withdrawal_and_none_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=1) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals = [] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_one_expected_partial_withdrawal_and_none_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_partial_withdrawals=1) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals = [] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_one_expected_full_withdrawal_and_duplicate_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=2) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals.append(execution_payload.withdrawals[0].copy()) execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_two_expected_partial_withdrawal_and_duplicate_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_partial_withdrawals=2) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals.append(execution_payload.withdrawals[0].copy()) execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_max_per_slot_full_withdrawals_and_one_less_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals = execution_payload.withdrawals[:-1] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_max_per_slot_partial_withdrawals_and_one_less_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_partial_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals = execution_payload.withdrawals[:-1] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_a_lot_fully_withdrawable_too_few_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 4) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals = execution_payload.withdrawals[:-1] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_a_lot_partially_withdrawable_too_few_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_partial_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 4) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals = execution_payload.withdrawals[:-1] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_a_lot_mixed_withdrawable_in_queue_too_few_in_withdrawals(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD, num_partial_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals = execution_payload.withdrawals[:-1] execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) # # Failure cases in which the withdrawals in the execution_payload are incorrect # @with_capella_and_later @spec_state_test def test_invalid_incorrect_withdrawal_index(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=1) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals[0].index += 1 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_incorrect_address_full(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=1) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals[0].address = b'\xff' * 20 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_incorrect_address_partial(spec, state): prepare_expected_withdrawals(spec, state, num_partial_withdrawals=1) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals[0].address = b'\xff' * 20 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_incorrect_amount_full(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=1) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals[0].amount += 1 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_incorrect_amount_partial(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=1) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) execution_payload.withdrawals[0].amount += 1 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_one_of_many_incorrectly_full(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 4) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) num_withdrawals = len(execution_payload.withdrawals) # Pick withdrawal in middle of list and mutate withdrawal = execution_payload.withdrawals[num_withdrawals // 2] withdrawal.index += 1 withdrawal.address = b'\x99' * 20 withdrawal.amount += 4000000 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_one_of_many_incorrectly_partial(spec, state): prepare_expected_withdrawals(spec, state, num_partial_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 4) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) num_withdrawals = len(execution_payload.withdrawals) # Pick withdrawal in middle of list and mutate withdrawal = execution_payload.withdrawals[num_withdrawals // 2] withdrawal.index += 1 withdrawal.address = b'\x99' * 20 withdrawal.amount += 4000000 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_many_incorrectly_full(spec, state): prepare_expected_withdrawals(spec, state, num_full_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 4) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) for i, withdrawal in enumerate(execution_payload.withdrawals): if i % 3 == 0: withdrawal.index += 1 elif i % 3 == 1: withdrawal.address = i.to_bytes(20, 'big') else: withdrawal.amount += 1 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) @with_capella_and_later @spec_state_test def test_invalid_many_incorrectly_partial(spec, state): prepare_expected_withdrawals(spec, state, num_partial_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 4) next_slot(spec, state) execution_payload = build_empty_execution_payload(spec, state) for i, withdrawal in enumerate(execution_payload.withdrawals): if i % 3 == 0: withdrawal.index += 1 elif i % 3 == 1: withdrawal.address = i.to_bytes(20, 'big') else: withdrawal.amount += 1 execution_payload.block_hash = compute_el_block_hash(spec, execution_payload) yield from run_withdrawals_processing(spec, state, execution_payload, valid=False) # # More full withdrawal cases # @with_capella_and_later @spec_state_test def test_withdrawable_epoch_but_0_balance(spec, state): current_epoch = spec.get_current_epoch(state) set_validator_fully_withdrawable(spec, state, 0, current_epoch) state.validators[0].effective_balance = 10000000000 state.balances[0] = 0 execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=0) @with_capella_and_later @spec_state_test def test_withdrawable_epoch_but_0_effective_balance_0_balance(spec, state): current_epoch = spec.get_current_epoch(state) set_validator_fully_withdrawable(spec, state, 0, current_epoch) state.validators[0].effective_balance = 0 state.balances[0] = 0 execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=0) @with_capella_and_later @spec_state_test def test_withdrawable_epoch_but_0_effective_balance_nonzero_balance(spec, state): current_epoch = spec.get_current_epoch(state) set_validator_fully_withdrawable(spec, state, 0, current_epoch) state.validators[0].effective_balance = 0 state.balances[0] = 100000000 execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=1) @with_capella_and_later @spec_state_test def test_no_withdrawals_but_some_next_epoch(spec, state): current_epoch = spec.get_current_epoch(state) # Make a few validators withdrawable at the *next* epoch for index in range(3): set_validator_fully_withdrawable(spec, state, index, current_epoch + 1) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=0) @with_capella_and_later @spec_state_test def test_all_withdrawal(spec, state): # Make all validators withdrawable for index in range(len(state.validators)): set_validator_fully_withdrawable(spec, state, index) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, num_expected_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD) def run_random_full_withdrawals_test(spec, state, rng): randomize_state(spec, state, rng) for index in range(len(state.validators)): # 50% withdrawable if rng.choice([True, False]): set_validator_fully_withdrawable(spec, state, index) validator = state.validators[index] # 12.5% unset credentials if rng.randint(0, 7) == 0: validator.withdrawal_credentials = spec.BLS_WITHDRAWAL_PREFIX + validator.withdrawal_credentials[1:] # 12.5% not enough balance if rng.randint(0, 7) == 0: state.balances[index] = 0 # 12.5% not close enough epoch if rng.randint(0, 7) == 0: validator.withdrawable_epoch += 1 execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload) @with_capella_and_later @spec_state_test def test_random_full_withdrawals_0(spec, state): yield from run_random_full_withdrawals_test(spec, state, random.Random(444)) @with_capella_and_later @spec_state_test def test_random_full_withdrawals_1(spec, state): yield from run_random_full_withdrawals_test(spec, state, random.Random(420)) @with_capella_and_later @spec_state_test def test_random_full_withdrawals_2(spec, state): yield from run_random_full_withdrawals_test(spec, state, random.Random(200)) @with_capella_and_later @spec_state_test def test_random_full_withdrawals_3(spec, state): yield from run_random_full_withdrawals_test(spec, state, random.Random(2000000)) # # More partial withdrawal cases # @with_capella_and_later @spec_state_test def test_success_no_max_effective_balance(spec, state): validator_index = len(state.validators) // 2 # To be partially withdrawable, the validator's effective balance must be maxed out set_eth1_withdrawal_credential_with_balance(spec, state, validator_index, spec.MAX_EFFECTIVE_BALANCE - 1) validator = state.validators[validator_index] assert validator.effective_balance < spec.MAX_EFFECTIVE_BALANCE assert not spec.is_partially_withdrawable_validator(validator, state.balances[validator_index]) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=0) @with_capella_and_later @spec_state_test def test_success_no_excess_balance(spec, state): validator_index = len(state.validators) // 2 # To be partially withdrawable, the validator needs an excess balance set_eth1_withdrawal_credential_with_balance(spec, state, validator_index, spec.MAX_EFFECTIVE_BALANCE) validator = state.validators[validator_index] assert validator.effective_balance == spec.MAX_EFFECTIVE_BALANCE assert not spec.is_partially_withdrawable_validator(validator, state.balances[validator_index]) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=0) @with_capella_and_later @spec_state_test def test_success_excess_balance_but_no_max_effective_balance(spec, state): validator_index = len(state.validators) // 2 set_validator_partially_withdrawable(spec, state, validator_index) validator = state.validators[validator_index] # To be partially withdrawable, the validator needs both a maxed out effective balance and an excess balance validator.effective_balance = spec.MAX_EFFECTIVE_BALANCE - 1 assert not spec.is_partially_withdrawable_validator(validator, state.balances[validator_index]) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=0) @with_capella_and_later @spec_state_test def test_success_one_partial_withdrawable_not_yet_active(spec, state): validator_index = min(len(state.validators) // 2, spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP - 1) state.validators[validator_index].activation_epoch += 4 set_validator_partially_withdrawable(spec, state, validator_index) assert not spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=1) @with_capella_and_later @spec_state_test def test_success_one_partial_withdrawable_in_exit_queue(spec, state): validator_index = min(len(state.validators) // 2, spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP - 1) state.validators[validator_index].exit_epoch = spec.get_current_epoch(state) + 1 set_validator_partially_withdrawable(spec, state, validator_index) assert spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) assert not spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state) + 1) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=1) @with_capella_and_later @spec_state_test def test_success_one_partial_withdrawable_exited(spec, state): validator_index = min(len(state.validators) // 2, spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP - 1) state.validators[validator_index].exit_epoch = spec.get_current_epoch(state) set_validator_partially_withdrawable(spec, state, validator_index) assert not spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=1) @with_capella_and_later @spec_state_test def test_success_one_partial_withdrawable_active_and_slashed(spec, state): validator_index = min(len(state.validators) // 2, spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP - 1) state.validators[validator_index].slashed = True set_validator_partially_withdrawable(spec, state, validator_index) assert spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=1) @with_capella_and_later @spec_state_test def test_success_one_partial_withdrawable_exited_and_slashed(spec, state): validator_index = min(len(state.validators) // 2, spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP - 1) state.validators[validator_index].slashed = True state.validators[validator_index].exit_epoch = spec.get_current_epoch(state) set_validator_partially_withdrawable(spec, state, validator_index) assert not spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=1) @with_capella_and_later @spec_state_test def test_success_two_partial_withdrawable(spec, state): set_validator_partially_withdrawable(spec, state, 0) set_validator_partially_withdrawable(spec, state, 1) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing(spec, state, execution_payload, num_expected_withdrawals=2) @with_capella_and_later @spec_state_test def test_success_max_partial_withdrawable(spec, state): # Sanity check that this test works for this state assert len(state.validators) >= spec.MAX_WITHDRAWALS_PER_PAYLOAD for i in range(spec.MAX_WITHDRAWALS_PER_PAYLOAD): set_validator_partially_withdrawable(spec, state, i) execution_payload = build_empty_execution_payload(spec, state) yield from run_withdrawals_processing( spec, state, execution_payload, num_expected_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD) @with_capella_and_later @with_presets([MINIMAL], reason="not enough validators with mainnet config") @spec_state_test def test_success_max_plus_one_withdrawable(spec, state): # Sanity check that this test works for this state assert len(state.validators) >= spec.MAX_WITHDRAWALS_PER_PAYLOAD + 1 # More than MAX_WITHDRAWALS_PER_PAYLOAD partially withdrawable for i in range(spec.MAX_WITHDRAWALS_PER_PAYLOAD + 1): set_validator_partially_withdrawable(spec, state, i) execution_payload = build_empty_execution_payload(spec, state) # Should only have MAX_WITHDRAWALS_PER_PAYLOAD withdrawals created yield from run_withdrawals_processing( spec, state, execution_payload, num_expected_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD) def run_random_partial_withdrawals_test(spec, state, rng): for _ in range(rng.randint(0, 2)): next_epoch(spec, state) randomize_state(spec, state, rng) num_validators = len(state.validators) state.next_withdrawal_validator_index = rng.randint(0, num_validators - 1) num_partially_withdrawable = rng.randint(0, num_validators - 1) partially_withdrawable_indices = rng.sample(range(num_validators), num_partially_withdrawable) for index in partially_withdrawable_indices: set_validator_partially_withdrawable(spec, state, index, excess_balance=rng.randint(1, 1000000000)) execution_payload = build_empty_execution_payload(spec, state) # Note: due to the randomness and other block processing, some of these set as "partially withdrawable" # may not be partially withdrawable once we get to ``process_withdrawals``, # thus *not* using the optional third param in this call yield from run_withdrawals_processing(spec, state, execution_payload) @with_capella_and_later @spec_state_test def test_random_0(spec, state): yield from run_random_partial_withdrawals_test(spec, state, random.Random(0)) @with_capella_and_later @spec_state_test def test_random_partial_withdrawals_1(spec, state): yield from run_random_partial_withdrawals_test(spec, state, random.Random(1)) @with_capella_and_later @spec_state_test def test_random_partial_withdrawals_2(spec, state): yield from run_random_partial_withdrawals_test(spec, state, random.Random(2)) @with_capella_and_later @spec_state_test def test_random_partial_withdrawals_3(spec, state): yield from run_random_partial_withdrawals_test(spec, state, random.Random(3)) @with_capella_and_later @spec_state_test def test_random_partial_withdrawals_4(spec, state): yield from run_random_partial_withdrawals_test(spec, state, random.Random(4)) @with_capella_and_later @spec_state_test def test_random_partial_withdrawals_5(spec, state): yield from run_random_partial_withdrawals_test(spec, state, random.Random(5))
34,134
38.145642
117
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/sanity/test_blocks.py
from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.context import ( with_capella_and_later, spec_state_test, with_presets, ) from eth2spec.test.helpers.keys import pubkeys from eth2spec.test.helpers.state import ( next_epoch_via_block, state_transition_and_sign_block, transition_to, next_slot, ) from eth2spec.test.helpers.block import ( build_empty_block_for_next_slot, build_empty_block, ) from eth2spec.test.helpers.bls_to_execution_changes import get_signed_address_change from eth2spec.test.helpers.attestations import ( next_epoch_with_attestations, ) from eth2spec.test.helpers.withdrawals import ( set_eth1_withdrawal_credential_with_balance, set_validator_fully_withdrawable, set_validator_partially_withdrawable, prepare_expected_withdrawals, ) from eth2spec.test.helpers.deposits import ( prepare_state_and_deposit, ) from eth2spec.test.helpers.voluntary_exits import prepare_signed_exits # # `is_execution_enabled` has been removed from Capella # @with_capella_and_later @spec_state_test def test_invalid_is_execution_enabled_false(spec, state): # Set `latest_execution_payload_header` to empty state.latest_execution_payload_header = spec.ExecutionPayloadHeader() yield 'pre', state block = build_empty_block_for_next_slot(spec, state) # Set `execution_payload` to empty block.body.execution_payload = spec.ExecutionPayload() assert len(block.body.execution_payload.transactions) == 0 signed_block = state_transition_and_sign_block(spec, state, block, expect_fail=True) yield 'blocks', [signed_block] yield 'post', None # # BLSToExecutionChange # @with_capella_and_later @spec_state_test def test_bls_change(spec, state): index = 0 signed_address_change = get_signed_address_change(spec, state, validator_index=index) pre_credentials = state.validators[index].withdrawal_credentials yield 'pre', state block = build_empty_block_for_next_slot(spec, state) block.body.bls_to_execution_changes.append(signed_address_change) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state post_credentials = state.validators[index].withdrawal_credentials assert pre_credentials != post_credentials assert post_credentials[:1] == spec.ETH1_ADDRESS_WITHDRAWAL_PREFIX assert post_credentials[1:12] == b'\x00' * 11 assert post_credentials[12:] == signed_address_change.message.to_execution_address @with_capella_and_later @spec_state_test def test_deposit_and_bls_change(spec, state): initial_registry_len = len(state.validators) initial_balances_len = len(state.balances) validator_index = len(state.validators) amount = spec.MAX_EFFECTIVE_BALANCE deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) signed_address_change = get_signed_address_change( spec, state, validator_index=validator_index, withdrawal_pubkey=deposit.data.pubkey, # Deposit helper defaults to use pubkey as withdrawal credential ) deposit_credentials = deposit.data.withdrawal_credentials assert deposit_credentials[:1] == spec.BLS_WITHDRAWAL_PREFIX yield 'pre', state block = build_empty_block_for_next_slot(spec, state) block.body.deposits.append(deposit) block.body.bls_to_execution_changes.append(signed_address_change) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state assert len(state.validators) == initial_registry_len + 1 assert len(state.balances) == initial_balances_len + 1 validator_credentials = state.validators[validator_index].withdrawal_credentials assert deposit_credentials != validator_credentials assert validator_credentials[:1] == spec.ETH1_ADDRESS_WITHDRAWAL_PREFIX assert validator_credentials[1:12] == b'\x00' * 11 assert validator_credentials[12:] == signed_address_change.message.to_execution_address @with_capella_and_later @spec_state_test def test_exit_and_bls_change(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH index = 0 signed_address_change = get_signed_address_change(spec, state, validator_index=index) signed_exit = prepare_signed_exits(spec, state, [index])[0] yield 'pre', state block = build_empty_block_for_next_slot(spec, state) block.body.voluntary_exits.append(signed_exit) block.body.bls_to_execution_changes.append(signed_address_change) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state validator = state.validators[index] balance = state.balances[index] current_epoch = spec.get_current_epoch(state) assert not spec.is_fully_withdrawable_validator(validator, balance, current_epoch) assert validator.withdrawable_epoch < spec.FAR_FUTURE_EPOCH assert spec.is_fully_withdrawable_validator(validator, balance, validator.withdrawable_epoch) @with_capella_and_later @spec_state_test def test_invalid_duplicate_bls_changes_same_block(spec, state): index = 0 signed_address_change = get_signed_address_change(spec, state, validator_index=index) yield 'pre', state block = build_empty_block_for_next_slot(spec, state) # Double BLSToExecutionChange of the same validator for _ in range(2): block.body.bls_to_execution_changes.append(signed_address_change) signed_block = state_transition_and_sign_block(spec, state, block, expect_fail=True) yield 'blocks', [signed_block] yield 'post', None @with_capella_and_later @spec_state_test def test_invalid_two_bls_changes_of_different_addresses_same_validator_same_block(spec, state): index = 0 signed_address_change_1 = get_signed_address_change(spec, state, validator_index=index, to_execution_address=b'\x12' * 20) signed_address_change_2 = get_signed_address_change(spec, state, validator_index=index, to_execution_address=b'\x34' * 20) assert signed_address_change_1 != signed_address_change_2 yield 'pre', state block = build_empty_block_for_next_slot(spec, state) block.body.bls_to_execution_changes.append(signed_address_change_1) block.body.bls_to_execution_changes.append(signed_address_change_2) signed_block = state_transition_and_sign_block(spec, state, block, expect_fail=True) yield 'blocks', [signed_block] yield 'post', None # # Withdrawals # @with_capella_and_later @spec_state_test def test_full_withdrawal_in_epoch_transition(spec, state): index = 0 current_epoch = spec.get_current_epoch(state) set_validator_fully_withdrawable(spec, state, index, current_epoch) assert len(spec.get_expected_withdrawals(state)) == 1 yield 'pre', state # trigger epoch transition block = build_empty_block(spec, state, state.slot + spec.SLOTS_PER_EPOCH) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state assert state.balances[index] == 0 assert len(spec.get_expected_withdrawals(state)) == 0 @with_capella_and_later @spec_state_test def test_partial_withdrawal_in_epoch_transition(spec, state): index = state.next_withdrawal_index set_validator_partially_withdrawable(spec, state, index, excess_balance=1000000000000) pre_balance = state.balances[index] assert len(spec.get_expected_withdrawals(state)) == 1 yield 'pre', state # trigger epoch transition block = build_empty_block(spec, state, state.slot + spec.SLOTS_PER_EPOCH) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state assert state.balances[index] < pre_balance # Potentially less than due to sync committee penalty assert state.balances[index] <= spec.MAX_EFFECTIVE_BALANCE assert len(spec.get_expected_withdrawals(state)) == 0 @with_capella_and_later @spec_state_test def test_many_partial_withdrawals_in_epoch_transition(spec, state): assert len(state.validators) > spec.MAX_WITHDRAWALS_PER_PAYLOAD for i in range(spec.MAX_WITHDRAWALS_PER_PAYLOAD + 1): index = (i + state.next_withdrawal_index) % len(state.validators) set_validator_partially_withdrawable(spec, state, index, excess_balance=1000000000000) assert len(spec.get_expected_withdrawals(state)) == spec.MAX_WITHDRAWALS_PER_PAYLOAD yield 'pre', state # trigger epoch transition block = build_empty_block(spec, state, state.slot + spec.SLOTS_PER_EPOCH) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state assert len(spec.get_expected_withdrawals(state)) == 1 def _perform_valid_withdrawal(spec, state): fully_withdrawable_indices, partial_withdrawals_indices = prepare_expected_withdrawals( spec, state, num_partial_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 2, num_full_withdrawals=spec.MAX_WITHDRAWALS_PER_PAYLOAD * 2) next_slot(spec, state) pre_next_withdrawal_index = state.next_withdrawal_index expected_withdrawals = spec.get_expected_withdrawals(state) pre_state = state.copy() # Block 1 block = build_empty_block_for_next_slot(spec, state) signed_block_1 = state_transition_and_sign_block(spec, state, block) withdrawn_indices = [withdrawal.validator_index for withdrawal in expected_withdrawals] fully_withdrawable_indices = list(set(fully_withdrawable_indices).difference(set(withdrawn_indices))) partial_withdrawals_indices = list(set(partial_withdrawals_indices).difference(set(withdrawn_indices))) assert state.next_withdrawal_index == pre_next_withdrawal_index + spec.MAX_WITHDRAWALS_PER_PAYLOAD withdrawn_indices = [withdrawal.validator_index for withdrawal in expected_withdrawals] fully_withdrawable_indices = list(set(fully_withdrawable_indices).difference(set(withdrawn_indices))) partial_withdrawals_indices = list(set(partial_withdrawals_indices).difference(set(withdrawn_indices))) assert state.next_withdrawal_index == pre_next_withdrawal_index + spec.MAX_WITHDRAWALS_PER_PAYLOAD return pre_state, signed_block_1, pre_next_withdrawal_index @with_capella_and_later @spec_state_test def test_withdrawal_success_two_blocks(spec, state): pre_state, signed_block_1, pre_next_withdrawal_index = _perform_valid_withdrawal(spec, state) yield 'pre', pre_state # Block 2 block = build_empty_block_for_next_slot(spec, state) signed_block_2 = state_transition_and_sign_block(spec, state, block) assert state.next_withdrawal_index == pre_next_withdrawal_index + spec.MAX_WITHDRAWALS_PER_PAYLOAD * 2 yield 'blocks', [signed_block_1, signed_block_2] yield 'post', state @with_capella_and_later @spec_state_test def test_invalid_withdrawal_fail_second_block_payload_isnt_compatible(spec, state): _perform_valid_withdrawal(spec, state) # Block 2 block = build_empty_block_for_next_slot(spec, state) # Modify state.next_withdrawal_index to incorrect number state.next_withdrawal_index += 1 # Only need to output the state transition of signed_block_2 yield 'pre', state signed_block_2 = state_transition_and_sign_block(spec, state, block, expect_fail=True) yield 'blocks', [signed_block_2] yield 'post', None # # Mix top-ups and withdrawals # @with_capella_and_later @spec_state_test def test_top_up_and_partial_withdrawable_validator(spec, state): next_withdrawal_validator_index = 0 validator_index = next_withdrawal_validator_index + 1 set_eth1_withdrawal_credential_with_balance(spec, state, validator_index, spec.MAX_EFFECTIVE_BALANCE) validator = state.validators[validator_index] balance = state.balances[validator_index] assert not spec.is_partially_withdrawable_validator(validator, balance) # Make a top-up balance to validator amount = spec.MAX_EFFECTIVE_BALANCE // 4 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) yield 'pre', state block = build_empty_block_for_next_slot(spec, state) block.body.deposits.append(deposit) signed_block = state_transition_and_sign_block(spec, state, block) yield 'blocks', [signed_block] yield 'post', state # Since withdrawals happen before deposits, it becomes partially withdrawable after state transition. validator = state.validators[validator_index] balance = state.balances[validator_index] assert spec.is_partially_withdrawable_validator(validator, balance) @with_capella_and_later @spec_state_test def test_top_up_to_fully_withdrawn_validator(spec, state): """ Similar to `teste_process_deposit::test_success_top_up_to_withdrawn_validator` test. """ next_withdrawal_validator_index = 0 validator_index = next_withdrawal_validator_index + 1 # Fully withdraw validator set_validator_fully_withdrawable(spec, state, validator_index) assert state.balances[validator_index] > 0 next_epoch_via_block(spec, state) assert state.balances[validator_index] == 0 assert state.validators[validator_index].effective_balance > 0 next_epoch_via_block(spec, state) assert state.validators[validator_index].effective_balance == 0 # Make a top-up deposit to validator amount = spec.MAX_EFFECTIVE_BALANCE // 4 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) yield 'pre', state block = build_empty_block_for_next_slot(spec, state) block.body.deposits.append(deposit) signed_block_1 = state_transition_and_sign_block(spec, state, block) assert spec.is_fully_withdrawable_validator( state.validators[validator_index], state.balances[validator_index], spec.get_current_epoch(state) ) # Apply an empty block block = build_empty_block_for_next_slot(spec, state) signed_block_2 = state_transition_and_sign_block(spec, state, block) # With mainnet preset, it holds if len(state.validators) <= spec.MAX_VALIDATORS_PER_WITHDRAWALS_SWEEP: assert not spec.is_fully_withdrawable_validator( state.validators[validator_index], state.balances[validator_index], spec.get_current_epoch(state) ) yield 'blocks', [signed_block_1, signed_block_2] yield 'post', state def _insert_validator(spec, state, balance): effective_balance = balance if balance < spec.MAX_EFFECTIVE_BALANCE else spec.MAX_EFFECTIVE_BALANCE validator_index = len(state.validators) validator = spec.Validator( pubkey=pubkeys[validator_index], withdrawal_credentials=spec.ETH1_ADDRESS_WITHDRAWAL_PREFIX + b'\x00' * 11 + b'\x56' * 20, activation_eligibility_epoch=1, activation_epoch=2, exit_epoch=spec.FAR_FUTURE_EPOCH, withdrawable_epoch=spec.FAR_FUTURE_EPOCH, effective_balance=effective_balance, ) state.validators.append(validator) state.balances.append(balance) state.previous_epoch_participation.append(spec.ParticipationFlags(0b0000_0000)) state.current_epoch_participation.append(spec.ParticipationFlags(0b0000_0000)) state.inactivity_scores.append(0) return validator_index def _run_activate_and_partial_withdrawal(spec, state, initial_balance): validator_index = _insert_validator(spec, state, balance=initial_balance) # To make it eligibile activation transition_to(spec, state, spec.compute_start_slot_at_epoch(2) - 1) assert not spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) yield 'pre', state blocks = [] # To activate block = build_empty_block_for_next_slot(spec, state) signed_block = state_transition_and_sign_block(spec, state, block) blocks.append(signed_block) assert spec.is_active_validator(state.validators[validator_index], spec.get_current_epoch(state)) if initial_balance > spec.MAX_EFFECTIVE_BALANCE: assert spec.is_partially_withdrawable_validator( state.validators[validator_index], state.balances[validator_index]) else: assert not spec.is_partially_withdrawable_validator( state.validators[validator_index], state.balances[validator_index]) _, new_blocks, state = next_epoch_with_attestations(spec, state, True, True) blocks += new_blocks yield 'blocks', blocks yield 'post', state @with_capella_and_later @with_presets([MINIMAL], reason="too many validators with mainnet config") @spec_state_test def test_activate_and_partial_withdrawal_max_effective_balance(spec, state): yield from _run_activate_and_partial_withdrawal(spec, state, initial_balance=spec.MAX_EFFECTIVE_BALANCE) @with_capella_and_later @with_presets([MINIMAL], reason="too many validators with mainnet config") @spec_state_test def test_activate_and_partial_withdrawal_overdeposit(spec, state): yield from _run_activate_and_partial_withdrawal(spec, state, initial_balance=spec.MAX_EFFECTIVE_BALANCE + 10000000)
17,437
35.028926
119
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/sanity/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/epoch_processing/test_process_historical_summaries_update.py
from eth2spec.test.context import ( spec_state_test, with_capella_and_later, ) from eth2spec.test.helpers.epoch_processing import ( run_epoch_processing_with ) def run_process_historical_summaries_update(spec, state): yield from run_epoch_processing_with(spec, state, 'process_historical_summaries_update') @with_capella_and_later @spec_state_test def test_historical_summaries_accumulator(spec, state): # skip ahead to near the end of the historical batch period (excl block before epoch processing) state.slot = spec.SLOTS_PER_HISTORICAL_ROOT - 1 pre_historical_summaries = state.historical_summaries.copy() yield from run_process_historical_summaries_update(spec, state) assert len(state.historical_summaries) == len(pre_historical_summaries) + 1 summary = state.historical_summaries[len(state.historical_summaries) - 1] assert summary.block_summary_root == state.block_roots.hash_tree_root() assert summary.state_summary_root == state.state_roots.hash_tree_root()
1,022
36.888889
100
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/epoch_processing/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/fork/test_capella_fork_basic.py
from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( BELLATRIX, CAPELLA, MINIMAL, ) from eth2spec.test.helpers.state import ( next_epoch, next_epoch_via_block, ) from eth2spec.test.helpers.capella.fork import ( CAPELLA_FORK_TEST_META_TAGS, run_fork_test, ) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_fork_base_state(spec, phases, state): yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_fork_next_epoch(spec, phases, state): next_epoch(spec, state) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_fork_next_epoch_with_block(spec, phases, state): next_epoch_via_block(spec, state) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_fork_many_next_epoch(spec, phases, state): for _ in range(3): next_epoch(spec, state) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_fork_random_low_balances(spec, phases, state): yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_fork_random_misc_balances(spec, phases, state): yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_fork_random_large_validator_set(spec, phases, state): yield from run_fork_test(phases[CAPELLA], state)
2,676
31.253012
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/fork/test_capella_fork_random.py
from random import Random from eth2spec.test.context import ( with_phases, with_custom_state, with_presets, spec_test, with_state, low_balances, misc_balances, large_validator_set, ) from eth2spec.test.utils import with_meta_tags from eth2spec.test.helpers.constants import ( BELLATRIX, CAPELLA, MINIMAL, ) from eth2spec.test.helpers.capella.fork import ( CAPELLA_FORK_TEST_META_TAGS, run_fork_test, ) from eth2spec.test.helpers.random import randomize_state @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_capella_fork_random_0(spec, phases, state): randomize_state(spec, state, rng=Random(1010)) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_capella_fork_random_1(spec, phases, state): randomize_state(spec, state, rng=Random(2020)) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_capella_fork_random_2(spec, phases, state): randomize_state(spec, state, rng=Random(3030)) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_state @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_capella_fork_random_3(spec, phases, state): randomize_state(spec, state, rng=Random(4040)) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_capella_fork_random_low_balances(spec, phases, state): randomize_state(spec, state, rng=Random(5050)) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @spec_test @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_capella_fork_random_misc_balances(spec, phases, state): randomize_state(spec, state, rng=Random(6060)) yield from run_fork_test(phases[CAPELLA], state) @with_phases(phases=[BELLATRIX], other_phases=[CAPELLA]) @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @spec_test @with_custom_state(balances_fn=large_validator_set, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @with_meta_tags(CAPELLA_FORK_TEST_META_TAGS) def test_capella_fork_random_large_validator_set(spec, phases, state): randomize_state(spec, state, rng=Random(7070)) yield from run_fork_test(phases[CAPELLA], state)
2,942
33.623529
116
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/fork/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/light_client/test_single_merkle_proof.py
from eth2spec.test.context import ( spec_state_test, with_capella_and_later, with_test_suite_name, ) from eth2spec.test.helpers.attestations import ( state_transition_with_full_block, ) @with_test_suite_name("BeaconBlockBody") @with_capella_and_later @spec_state_test def test_execution_merkle_proof(spec, state): block = state_transition_with_full_block(spec, state, True, False) yield "object", block.message.body execution_branch = spec.compute_merkle_proof_for_block_body( block.message.body, spec.EXECUTION_PAYLOAD_INDEX) yield "proof", { "leaf": "0x" + block.message.body.execution_payload.hash_tree_root().hex(), "leaf_index": spec.EXECUTION_PAYLOAD_INDEX, "branch": ['0x' + root.hex() for root in execution_branch] } assert spec.is_valid_merkle_branch( leaf=block.message.body.execution_payload.hash_tree_root(), branch=execution_branch, depth=spec.floorlog2(spec.EXECUTION_PAYLOAD_INDEX), index=spec.get_subtree_index(spec.EXECUTION_PAYLOAD_INDEX), root=block.message.body.hash_tree_root(), )
1,121
34.0625
83
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/capella/light_client/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/random/test_random.py
""" This module is generated from the ``random`` test generator. Please do not edit this file manually. See the README for that generator for more information. """ from eth2spec.test.helpers.constants import PHASE0 from eth2spec.test.context import ( misc_balances_in_default_range_with_many_validators, with_phases, zero_activation_threshold, only_generator, ) from eth2spec.test.context import ( always_bls, spec_test, with_custom_state, single_phase, ) from eth2spec.test.utils.randomized_block_tests import ( run_generated_randomized_test, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_0(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_1(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_2(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_3(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_4(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_5(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_6(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_7(spec, state): # scenario as high-level, informal text: # epochs:0,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'validation': 'validate_is_not_leaking', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_8(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_9(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_10(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_11(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_12(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:last_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'last_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_13(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:random_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'random_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_14(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:penultimate_slot_in_epoch,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 0, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 'penultimate_slot_in_epoch', 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, ) @only_generator("randomized test for broad coverage, not point-to-point CI") @with_phases([PHASE0]) @with_custom_state( balances_fn=misc_balances_in_default_range_with_many_validators, threshold_fn=zero_activation_threshold ) @spec_test @single_phase @always_bls def test_randomized_15(spec, state): # scenario as high-level, informal text: # epochs:epochs_until_leak,slots:0,with-block:no_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block # epochs:1,slots:0,with-block:no_block # epochs:0,slots:0,with-block:no_block # epochs:0,slots:0,with-block:random_block scenario = {'transitions': [{'epochs_to_skip': 'epochs_until_leak', 'validation': 'validate_is_leaking', 'slots_to_skip': 0, 'block_producer': 'no_block'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}, {'epochs_to_skip': 1, 'slots_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'slots_to_skip': 0, 'epochs_to_skip': 0, 'block_producer': 'no_block', 'validation': 'no_op_validation'}, {'block_producer': 'random_block', 'epochs_to_skip': 0, 'slots_to_skip': 0, 'validation': 'no_op_validation'}], 'state_randomizer': 'randomize_state'} # noqa: E501 yield from run_generated_randomized_test( spec, state, scenario, )
27,629
61.938497
915
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/random/__init__.py
0
0
0
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/block_processing/test_process_proposer_slashing.py
from eth2spec.test.context import spec_state_test, expect_assertion_error, always_bls, with_all_phases from eth2spec.test.helpers.block import build_empty_block_for_next_slot from eth2spec.test.helpers.block_header import sign_block_header from eth2spec.test.helpers.keys import privkeys from eth2spec.test.helpers.proposer_slashings import get_valid_proposer_slashing, check_proposer_slashing_effect from eth2spec.test.helpers.state import next_epoch def run_proposer_slashing_processing(spec, state, proposer_slashing, valid=True): """ Run ``process_proposer_slashing``, yielding: - pre-state ('pre') - proposer_slashing ('proposer_slashing') - post-state ('post'). If ``valid == False``, run expecting ``AssertionError`` """ pre_state = state.copy() yield 'pre', state yield 'proposer_slashing', proposer_slashing if not valid: expect_assertion_error(lambda: spec.process_proposer_slashing(state, proposer_slashing)) yield 'post', None return spec.process_proposer_slashing(state, proposer_slashing) yield 'post', state slashed_proposer_index = proposer_slashing.signed_header_1.message.proposer_index check_proposer_slashing_effect(spec, pre_state, state, slashed_proposer_index) @with_all_phases @spec_state_test def test_basic(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=True) yield from run_proposer_slashing_processing(spec, state, proposer_slashing) @with_all_phases @spec_state_test def test_slashed_and_proposer_index_the_same(spec, state): # Get proposer for next slot block = build_empty_block_for_next_slot(spec, state) proposer_index = block.proposer_index # Create slashing for same proposer proposer_slashing = get_valid_proposer_slashing(spec, state, slashed_index=proposer_index, signed_1=True, signed_2=True) yield from run_proposer_slashing_processing(spec, state, proposer_slashing) @with_all_phases @spec_state_test def test_block_header_from_future(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, slot=state.slot + 5, signed_1=True, signed_2=True) yield from run_proposer_slashing_processing(spec, state, proposer_slashing) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_sig_1(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=False, signed_2=True) yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_sig_2(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=False) yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_sig_1_and_2(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=False, signed_2=False) yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_sig_1_and_2_swap(spec, state): # Get valid signatures for the slashings proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=True) # But swap them signature_1 = proposer_slashing.signed_header_1.signature proposer_slashing.signed_header_1.signature = proposer_slashing.signed_header_2.signature proposer_slashing.signed_header_2.signature = signature_1 yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_incorrect_proposer_index(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=True) # Index just too high (by 1) proposer_slashing.signed_header_1.message.proposer_index = len(state.validators) proposer_slashing.signed_header_2.message.proposer_index = len(state.validators) yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_different_proposer_indices(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=True) # set different index and sign header_1 = proposer_slashing.signed_header_1.message header_2 = proposer_slashing.signed_header_2.message active_indices = spec.get_active_validator_indices(state, spec.get_current_epoch(state)) active_indices = [i for i in active_indices if i != header_1.proposer_index] header_2.proposer_index = active_indices[0] proposer_slashing.signed_header_2 = sign_block_header(spec, state, header_2, privkeys[header_2.proposer_index]) yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_slots_of_different_epochs(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=False) # set slots to be in different epochs header_2 = proposer_slashing.signed_header_2.message proposer_index = header_2.proposer_index header_2.slot += spec.SLOTS_PER_EPOCH proposer_slashing.signed_header_2 = sign_block_header(spec, state, header_2, privkeys[proposer_index]) yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_headers_are_same_sigs_are_same(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=False) # set headers to be the same proposer_slashing.signed_header_2 = proposer_slashing.signed_header_1.copy() yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_headers_are_same_sigs_are_different(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=False) # set headers to be the same proposer_slashing.signed_header_2 = proposer_slashing.signed_header_1.copy() # but signatures to be different proposer_slashing.signed_header_2.signature = proposer_slashing.signed_header_2.signature[:-1] + b'\x00' assert proposer_slashing.signed_header_1.signature != proposer_slashing.signed_header_2.signature yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_proposer_is_not_activated(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=True) # set proposer to be not active yet proposer_index = proposer_slashing.signed_header_1.message.proposer_index state.validators[proposer_index].activation_epoch = spec.get_current_epoch(state) + 1 yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_proposer_is_slashed(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=True) # set proposer to slashed proposer_index = proposer_slashing.signed_header_1.message.proposer_index state.validators[proposer_index].slashed = True yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_proposer_is_withdrawn(spec, state): proposer_slashing = get_valid_proposer_slashing(spec, state, signed_1=True, signed_2=True) # move 1 epoch into future, to allow for past withdrawable epoch next_epoch(spec, state) # set proposer withdrawable_epoch in past current_epoch = spec.get_current_epoch(state) proposer_index = proposer_slashing.signed_header_1.message.proposer_index state.validators[proposer_index].withdrawable_epoch = current_epoch - 1 yield from run_proposer_slashing_processing(spec, state, proposer_slashing, valid=False)
8,264
38.735577
115
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/block_processing/test_process_deposit.py
from eth2spec.test.context import spec_state_test, always_bls, with_all_phases from eth2spec.test.helpers.deposits import ( build_deposit, prepare_state_and_deposit, run_deposit_processing, run_deposit_processing_with_specific_fork_version, sign_deposit_data, ) from eth2spec.test.helpers.keys import privkeys, pubkeys @with_all_phases @spec_state_test def test_new_deposit_under_max(spec, state): # fresh deposit = next validator index = validator appended to registry validator_index = len(state.validators) # effective balance will be 1 EFFECTIVE_BALANCE_INCREMENT smaller because of this small decrement. amount = spec.MAX_EFFECTIVE_BALANCE - 1 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test def test_new_deposit_max(spec, state): # fresh deposit = next validator index = validator appended to registry validator_index = len(state.validators) # effective balance will be exactly the same as balance. amount = spec.MAX_EFFECTIVE_BALANCE deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test def test_new_deposit_over_max(spec, state): # fresh deposit = next validator index = validator appended to registry validator_index = len(state.validators) # just 1 over the limit, effective balance should be set MAX_EFFECTIVE_BALANCE during processing amount = spec.MAX_EFFECTIVE_BALANCE + 1 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test def test_new_deposit_eth1_withdrawal_credentials(spec, state): # fresh deposit = next validator index = validator appended to registry validator_index = len(state.validators) withdrawal_credentials = ( spec.ETH1_ADDRESS_WITHDRAWAL_PREFIX + b'\x00' * 11 # specified 0s + b'\x59' * 20 # a 20-byte eth1 address ) amount = spec.MAX_EFFECTIVE_BALANCE deposit = prepare_state_and_deposit( spec, state, validator_index, amount, withdrawal_credentials=withdrawal_credentials, signed=True, ) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test def test_new_deposit_non_versioned_withdrawal_credentials(spec, state): # fresh deposit = next validator index = validator appended to registry validator_index = len(state.validators) withdrawal_credentials = ( b'\xFF' # Non specified withdrawal credentials version + b'\x02' * 31 # Garabage bytes ) amount = spec.MAX_EFFECTIVE_BALANCE deposit = prepare_state_and_deposit( spec, state, validator_index, amount, withdrawal_credentials=withdrawal_credentials, signed=True, ) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test @always_bls def test_correct_sig_but_forked_state(spec, state): validator_index = len(state.validators) amount = spec.MAX_EFFECTIVE_BALANCE # deposits will always be valid, regardless of the current fork state.fork.current_version = spec.Version('0x1234abcd') deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test @always_bls def test_incorrect_sig_new_deposit(spec, state): # fresh deposit = next validator index = validator appended to registry validator_index = len(state.validators) amount = spec.MAX_EFFECTIVE_BALANCE deposit = prepare_state_and_deposit(spec, state, validator_index, amount) yield from run_deposit_processing(spec, state, deposit, validator_index, effective=False) @with_all_phases @spec_state_test def test_top_up__max_effective_balance(spec, state): validator_index = 0 amount = spec.MAX_EFFECTIVE_BALANCE // 4 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) state.balances[validator_index] = spec.MAX_EFFECTIVE_BALANCE state.validators[validator_index].effective_balance = spec.MAX_EFFECTIVE_BALANCE yield from run_deposit_processing(spec, state, deposit, validator_index) assert state.balances[validator_index] == spec.MAX_EFFECTIVE_BALANCE + amount assert state.validators[validator_index].effective_balance == spec.MAX_EFFECTIVE_BALANCE @with_all_phases @spec_state_test def test_top_up__less_effective_balance(spec, state): validator_index = 0 amount = spec.MAX_EFFECTIVE_BALANCE // 4 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) initial_balance = spec.MAX_EFFECTIVE_BALANCE - 1000 initial_effective_balance = spec.MAX_EFFECTIVE_BALANCE - spec.EFFECTIVE_BALANCE_INCREMENT state.balances[validator_index] = initial_balance state.validators[validator_index].effective_balance = initial_effective_balance yield from run_deposit_processing(spec, state, deposit, validator_index) assert state.balances[validator_index] == initial_balance + amount # unchanged effective balance assert state.validators[validator_index].effective_balance == initial_effective_balance @with_all_phases @spec_state_test def test_top_up__zero_balance(spec, state): validator_index = 0 amount = spec.MAX_EFFECTIVE_BALANCE // 4 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, signed=True) initial_balance = 0 initial_effective_balance = 0 state.balances[validator_index] = initial_balance state.validators[validator_index].effective_balance = initial_effective_balance yield from run_deposit_processing(spec, state, deposit, validator_index) assert state.balances[validator_index] == initial_balance + amount # unchanged effective balance assert state.validators[validator_index].effective_balance == initial_effective_balance @with_all_phases @spec_state_test @always_bls def test_incorrect_sig_top_up(spec, state): validator_index = 0 amount = spec.MAX_EFFECTIVE_BALANCE // 4 deposit = prepare_state_and_deposit(spec, state, validator_index, amount) # invalid signatures, in top-ups, are allowed! yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test def test_incorrect_withdrawal_credentials_top_up(spec, state): validator_index = 0 amount = spec.MAX_EFFECTIVE_BALANCE // 4 withdrawal_credentials = spec.BLS_WITHDRAWAL_PREFIX + spec.hash(b"junk")[1:] deposit = prepare_state_and_deposit( spec, state, validator_index, amount, withdrawal_credentials=withdrawal_credentials ) # inconsistent withdrawal credentials, in top-ups, are allowed! yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test def test_invalid_wrong_deposit_for_deposit_count(spec, state): deposit_data_leaves = [spec.DepositData() for _ in range(len(state.validators))] # build root for deposit_1 index_1 = len(deposit_data_leaves) pubkey_1 = pubkeys[index_1] privkey_1 = privkeys[index_1] _, _, deposit_data_leaves = build_deposit( spec, deposit_data_leaves, pubkey_1, privkey_1, spec.MAX_EFFECTIVE_BALANCE, withdrawal_credentials=b'\x00' * 32, signed=True, ) deposit_count_1 = len(deposit_data_leaves) # build root for deposit_2 index_2 = len(deposit_data_leaves) pubkey_2 = pubkeys[index_2] privkey_2 = privkeys[index_2] deposit_2, root_2, deposit_data_leaves = build_deposit( spec, deposit_data_leaves, pubkey_2, privkey_2, spec.MAX_EFFECTIVE_BALANCE, withdrawal_credentials=b'\x00' * 32, signed=True, ) # state has root for deposit_2 but is at deposit_count for deposit_1 state.eth1_data.deposit_root = root_2 state.eth1_data.deposit_count = deposit_count_1 yield from run_deposit_processing(spec, state, deposit_2, index_2, valid=False) @with_all_phases @spec_state_test def test_invalid_bad_merkle_proof(spec, state): validator_index = len(state.validators) amount = spec.MAX_EFFECTIVE_BALANCE deposit = prepare_state_and_deposit(spec, state, validator_index, amount) # mess up merkle branch deposit.proof[5] = spec.Bytes32() sign_deposit_data(spec, deposit.data, privkeys[validator_index]) yield from run_deposit_processing(spec, state, deposit, validator_index, valid=False) @with_all_phases @spec_state_test def test_key_validate_invalid_subgroup(spec, state): validator_index = len(state.validators) amount = spec.MAX_EFFECTIVE_BALANCE # All-zero pubkey would not pass `bls.KeyValidate`, but `process_deposit` would not throw exception. pubkey = b'\x00' * 48 deposit = prepare_state_and_deposit(spec, state, validator_index, amount, pubkey=pubkey, signed=True) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test def test_key_validate_invalid_decompression(spec, state): validator_index = len(state.validators) amount = spec.MAX_EFFECTIVE_BALANCE # `deserialization_fails_infinity_with_true_b_flag` BLS G1 deserialization test case. # This pubkey would not pass `bls.KeyValidate`, but `process_deposit` would not throw exception. pubkey_hex = 'c01000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000' pubkey = bytes.fromhex(pubkey_hex) deposit = prepare_state_and_deposit(spec, state, validator_index, amount, pubkey=pubkey, signed=True) yield from run_deposit_processing(spec, state, deposit, validator_index) @with_all_phases @spec_state_test @always_bls def test_ineffective_deposit_with_bad_fork_version(spec, state): yield from run_deposit_processing_with_specific_fork_version( spec, state, fork_version=spec.Version('0xAaBbCcDd'), effective=False, )
10,427
34.469388
115
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/block_processing/test_process_voluntary_exit.py
from eth2spec.test.helpers.constants import MINIMAL from eth2spec.test.context import ( spec_state_test, always_bls, with_all_phases, with_presets, spec_test, single_phase, with_custom_state, scaled_churn_balances, ) from eth2spec.test.helpers.keys import pubkey_to_privkey from eth2spec.test.helpers.voluntary_exits import ( run_voluntary_exit_processing, sign_voluntary_exit, ) @with_all_phases @spec_state_test def test_basic(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] signed_voluntary_exit = sign_voluntary_exit( spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit) assert state.validators[validator_index].exit_epoch == spec.compute_activation_exit_epoch(current_epoch) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_signature(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] voluntary_exit = spec.VoluntaryExit( epoch=current_epoch, validator_index=validator_index, ) signed_voluntary_exit = sign_voluntary_exit(spec, state, voluntary_exit, 12345) yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) def run_test_success_exit_queue(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH current_epoch = spec.get_current_epoch(state) # exit `MAX_EXITS_PER_EPOCH` initial_indices = spec.get_active_validator_indices(state, current_epoch)[:spec.get_validator_churn_limit(state)] # Prepare a bunch of exits, based on the current state exit_queue = [] for index in initial_indices: privkey = pubkey_to_privkey[state.validators[index].pubkey] signed_voluntary_exit = sign_voluntary_exit( spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=index), privkey) exit_queue.append(signed_voluntary_exit) # Now run all the exits for voluntary_exit in exit_queue: # the function yields data, but we are just interested in running it here, ignore yields. for _ in run_voluntary_exit_processing(spec, state, voluntary_exit): continue # exit an additional validator validator_index = spec.get_active_validator_indices(state, current_epoch)[-1] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] signed_voluntary_exit = sign_voluntary_exit( spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) # This is the interesting part of the test: on a pre-state with a full exit queue, # when processing an additional exit, it results in an exit in a later epoch yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit) for index in initial_indices: assert ( state.validators[validator_index].exit_epoch == state.validators[index].exit_epoch + 1 ) @with_all_phases @spec_state_test def test_success_exit_queue__min_churn(spec, state): yield from run_test_success_exit_queue(spec, state) @with_all_phases @with_presets([MINIMAL], reason="mainnet config leads to larger validator set than limit of public/private keys pre-generated") @spec_test @with_custom_state(balances_fn=scaled_churn_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @single_phase def test_success_exit_queue__scaled_churn(spec, state): churn_limit = spec.get_validator_churn_limit(state) assert churn_limit > spec.config.MIN_PER_EPOCH_CHURN_LIMIT yield from run_test_success_exit_queue(spec, state) @with_all_phases @spec_state_test def test_default_exit_epoch_subsequent_exit(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] signed_voluntary_exit = sign_voluntary_exit( spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) # Exit one validator prior to this new one exited_index = spec.get_active_validator_indices(state, current_epoch)[-1] state.validators[exited_index].exit_epoch = current_epoch - 1 yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit) assert state.validators[validator_index].exit_epoch == spec.compute_activation_exit_epoch(current_epoch) @with_all_phases @spec_state_test def test_invalid_validator_exit_in_future(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] voluntary_exit = spec.VoluntaryExit( epoch=current_epoch + 1, validator_index=validator_index, ) signed_voluntary_exit = sign_voluntary_exit(spec, state, voluntary_exit, privkey) yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) @with_all_phases @spec_state_test def test_invalid_validator_incorrect_validator_index(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow for exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] voluntary_exit = spec.VoluntaryExit( epoch=current_epoch, validator_index=len(state.validators), ) signed_voluntary_exit = sign_voluntary_exit(spec, state, voluntary_exit, privkey) yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) @with_all_phases @spec_state_test def test_invalid_validator_not_active(spec, state): current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] state.validators[validator_index].activation_epoch = spec.FAR_FUTURE_EPOCH signed_voluntary_exit = sign_voluntary_exit( spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) @with_all_phases @spec_state_test def test_invalid_validator_already_exited(spec, state): # move state forward SHARD_COMMITTEE_PERIOD epochs to allow validator able to exit state.slot += spec.config.SHARD_COMMITTEE_PERIOD * spec.SLOTS_PER_EPOCH current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] # but validator already has exited state.validators[validator_index].exit_epoch = current_epoch + 2 signed_voluntary_exit = sign_voluntary_exit( spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False) @with_all_phases @spec_state_test def test_invalid_validator_not_active_long_enough(spec, state): current_epoch = spec.get_current_epoch(state) validator_index = spec.get_active_validator_indices(state, current_epoch)[0] privkey = pubkey_to_privkey[state.validators[validator_index].pubkey] signed_voluntary_exit = sign_voluntary_exit( spec, state, spec.VoluntaryExit(epoch=current_epoch, validator_index=validator_index), privkey) assert ( current_epoch - state.validators[validator_index].activation_epoch < spec.config.SHARD_COMMITTEE_PERIOD ) yield from run_voluntary_exit_processing(spec, state, signed_voluntary_exit, valid=False)
8,972
39.237668
117
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/block_processing/test_process_attester_slashing.py
from random import Random from eth2spec.test.context import ( spec_state_test, expect_assertion_error, always_bls, with_all_phases, with_custom_state, spec_test, single_phase, low_balances, misc_balances, ) from eth2spec.test.helpers.attestations import sign_indexed_attestation from eth2spec.test.helpers.attester_slashings import ( get_valid_attester_slashing, get_valid_attester_slashing_by_indices, get_indexed_attestation_participants, get_attestation_2_data, get_attestation_1_data, ) from eth2spec.test.helpers.proposer_slashings import get_min_slashing_penalty_quotient from eth2spec.test.helpers.state import ( get_balance, next_epoch_via_block, ) def run_attester_slashing_processing(spec, state, attester_slashing, valid=True): """ Run ``process_attester_slashing``, yielding: - pre-state ('pre') - attester_slashing ('attester_slashing') - post-state ('post'). If ``valid == False``, run expecting ``AssertionError`` """ yield 'pre', state yield 'attester_slashing', attester_slashing if not valid: expect_assertion_error(lambda: spec.process_attester_slashing(state, attester_slashing)) yield 'post', None return slashed_indices = get_indexed_attestation_participants(spec, attester_slashing.attestation_1) proposer_index = spec.get_beacon_proposer_index(state) pre_proposer_balance = get_balance(state, proposer_index) pre_slashing_balances = {slashed_index: get_balance(state, slashed_index) for slashed_index in slashed_indices} pre_slashing_effectives = { slashed_index: state.validators[slashed_index].effective_balance for slashed_index in slashed_indices } pre_withdrawalable_epochs = { slashed_index: state.validators[slashed_index].withdrawable_epoch for slashed_index in slashed_indices } total_proposer_rewards = sum( effective_balance // spec.WHISTLEBLOWER_REWARD_QUOTIENT for effective_balance in pre_slashing_effectives.values() ) # Process slashing spec.process_attester_slashing(state, attester_slashing) for slashed_index in slashed_indices: pre_withdrawalable_epoch = pre_withdrawalable_epochs[slashed_index] slashed_validator = state.validators[slashed_index] # Check slashing assert slashed_validator.slashed assert slashed_validator.exit_epoch < spec.FAR_FUTURE_EPOCH if pre_withdrawalable_epoch < spec.FAR_FUTURE_EPOCH: expected_withdrawable_epoch = max( pre_withdrawalable_epoch, spec.get_current_epoch(state) + spec.EPOCHS_PER_SLASHINGS_VECTOR ) assert slashed_validator.withdrawable_epoch == expected_withdrawable_epoch else: assert slashed_validator.withdrawable_epoch < spec.FAR_FUTURE_EPOCH assert get_balance(state, slashed_index) < pre_slashing_balances[slashed_index] if proposer_index not in slashed_indices: # gained whistleblower reward assert get_balance(state, proposer_index) == pre_proposer_balance + total_proposer_rewards else: # gained rewards for all slashings, which may include others. And only lost that of themselves. expected_balance = ( pre_proposer_balance + total_proposer_rewards - pre_slashing_effectives[proposer_index] // get_min_slashing_penalty_quotient(spec) ) assert get_balance(state, proposer_index) == expected_balance yield 'post', state @with_all_phases @spec_state_test def test_basic_double(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @spec_state_test def test_basic_surround(spec, state): next_epoch_via_block(spec, state) state.current_justified_checkpoint.epoch += 1 attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) att_1_data = get_attestation_1_data(spec, attester_slashing) att_2_data = get_attestation_2_data(spec, attester_slashing) # set attestion1 to surround attestation 2 att_1_data.source.epoch = att_2_data.source.epoch - 1 att_1_data.target.epoch = att_2_data.target.epoch + 1 sign_indexed_attestation(spec, state, attester_slashing.attestation_1) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @spec_state_test @always_bls def test_already_exited_recent(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) slashed_indices = get_indexed_attestation_participants(spec, attester_slashing.attestation_1) for index in slashed_indices: spec.initiate_validator_exit(state, index) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @spec_state_test @always_bls def test_proposer_index_slashed(spec, state): # Transition past genesis slot because generally doesn't have a proposer next_epoch_via_block(spec, state) proposer_index = spec.get_beacon_proposer_index(state) attester_slashing = get_valid_attester_slashing_by_indices( spec, state, [proposer_index], signed_1=True, signed_2=True, ) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @spec_state_test def test_attestation_from_future(spec, state): # Transition state to future to enable generation of a "future" attestation future_state = state.copy() next_epoch_via_block(spec, future_state) # Generate slashing using the future state attester_slashing = get_valid_attester_slashing( spec, future_state, slot=state.slot + 5, # Slot is in the future wrt `state` signed_1=True, signed_2=True ) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase def test_low_balances(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase def test_misc_balances(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @with_custom_state(balances_fn=misc_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @spec_test @single_phase def test_with_effective_balance_disparity(spec, state): # Jitter balances to be different from effective balances rng = Random(12345) for i in range(len(state.balances)): pre = int(state.balances[i]) state.balances[i] += rng.randrange(max(pre - 5000, 0), pre + 5000) attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @spec_state_test @always_bls def test_already_exited_long_ago(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) slashed_indices = get_indexed_attestation_participants(spec, attester_slashing.attestation_1) for index in slashed_indices: spec.initiate_validator_exit(state, index) state.validators[index].withdrawable_epoch = spec.get_current_epoch(state) + 2 yield from run_attester_slashing_processing(spec, state, attester_slashing) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_sig_1(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_sig_2(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=False) yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_incorrect_sig_1_and_2(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=False) yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_same_data(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) indexed_att_1 = attester_slashing.attestation_1 att_2_data = get_attestation_2_data(spec, attester_slashing) indexed_att_1.data = att_2_data sign_indexed_attestation(spec, state, attester_slashing.attestation_1) yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_no_double_or_surround(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) att_1_data = get_attestation_1_data(spec, attester_slashing) att_1_data.target.epoch += 1 sign_indexed_attestation(spec, state, attester_slashing.attestation_1) yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_participants_already_slashed(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) # set all indices to slashed validator_indices = get_indexed_attestation_participants(spec, attester_slashing.attestation_1) for index in validator_indices: state.validators[index].slashed = True yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att1_high_index(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) indices = get_indexed_attestation_participants(spec, attester_slashing.attestation_1) indices.append(spec.ValidatorIndex(len(state.validators))) # off by 1 attester_slashing.attestation_1.attesting_indices = indices yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att2_high_index(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) indices = get_indexed_attestation_participants(spec, attester_slashing.attestation_2) indices.append(spec.ValidatorIndex(len(state.validators))) # off by 1 attester_slashing.attestation_2.attesting_indices = indices yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att1_empty_indices(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) attester_slashing.attestation_1.attesting_indices = [] attester_slashing.attestation_1.signature = spec.bls.G2_POINT_AT_INFINITY yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att2_empty_indices(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=False) attester_slashing.attestation_2.attesting_indices = [] attester_slashing.attestation_2.signature = spec.bls.G2_POINT_AT_INFINITY yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_all_empty_indices(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=False) attester_slashing.attestation_1.attesting_indices = [] attester_slashing.attestation_1.signature = spec.bls.G2_POINT_AT_INFINITY attester_slashing.attestation_2.attesting_indices = [] attester_slashing.attestation_2.signature = spec.bls.G2_POINT_AT_INFINITY yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att1_bad_extra_index(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) indices = get_indexed_attestation_participants(spec, attester_slashing.attestation_1) options = list(set(range(len(state.validators))) - set(indices)) indices.append(options[len(options) // 2]) # add random index, not previously in attestation. attester_slashing.attestation_1.attesting_indices = sorted(indices) # Do not sign the modified attestation (it's ok to slash if attester signed, not if they did not), # see if the bad extra index is spotted, and slashing is aborted. yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att1_bad_replaced_index(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) indices = attester_slashing.attestation_1.attesting_indices options = list(set(range(len(state.validators))) - set(indices)) indices[3] = options[len(options) // 2] # replace with random index, not previously in attestation. attester_slashing.attestation_1.attesting_indices = sorted(indices) # Do not sign the modified attestation (it's ok to slash if attester signed, not if they did not), # see if the bad replaced index is spotted, and slashing is aborted. yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att2_bad_extra_index(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) indices = attester_slashing.attestation_2.attesting_indices options = list(set(range(len(state.validators))) - set(indices)) indices.append(options[len(options) // 2]) # add random index, not previously in attestation. attester_slashing.attestation_2.attesting_indices = sorted(indices) # Do not sign the modified attestation (it's ok to slash if attester signed, not if they did not), # see if the bad extra index is spotted, and slashing is aborted. yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att2_bad_replaced_index(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=True) indices = attester_slashing.attestation_2.attesting_indices options = list(set(range(len(state.validators))) - set(indices)) indices[3] = options[len(options) // 2] # replace with random index, not previously in attestation. attester_slashing.attestation_2.attesting_indices = sorted(indices) # Do not sign the modified attestation (it's ok to slash if attester signed, not if they did not), # see if the bad replaced index is spotted, and slashing is aborted. yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att1_duplicate_index_normal_signed(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) indices = list(attester_slashing.attestation_1.attesting_indices) indices.pop(1) # remove an index, make room for the additional duplicate index. attester_slashing.attestation_1.attesting_indices = sorted(indices) # The signature will be valid for a single occurrence. If the transition accidentally ignores the duplicate. sign_indexed_attestation(spec, state, attester_slashing.attestation_1) indices.append(indices[0]) # add one of the indices a second time attester_slashing.attestation_1.attesting_indices = sorted(indices) # it will just appear normal, unless the double index is spotted yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att2_duplicate_index_normal_signed(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=False) indices = list(attester_slashing.attestation_2.attesting_indices) indices.pop(2) # remove an index, make room for the additional duplicate index. attester_slashing.attestation_2.attesting_indices = sorted(indices) # The signature will be valid for a single occurrence. If the transition accidentally ignores the duplicate. sign_indexed_attestation(spec, state, attester_slashing.attestation_2) indices.append(indices[1]) # add one of the indices a second time attester_slashing.attestation_2.attesting_indices = sorted(indices) # it will just appear normal, unless the double index is spotted yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att1_duplicate_index_double_signed(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) indices = list(attester_slashing.attestation_1.attesting_indices) indices.pop(1) # remove an index, make room for the additional duplicate index. indices.append(indices[2]) # add one of the indices a second time attester_slashing.attestation_1.attesting_indices = sorted(indices) sign_indexed_attestation(spec, state, attester_slashing.attestation_1) # will have one attester signing it double yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_att2_duplicate_index_double_signed(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=False) indices = list(attester_slashing.attestation_2.attesting_indices) indices.pop(1) # remove an index, make room for the additional duplicate index. indices.append(indices[2]) # add one of the indices a second time attester_slashing.attestation_2.attesting_indices = sorted(indices) sign_indexed_attestation(spec, state, attester_slashing.attestation_2) # will have one attester signing it double yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_unsorted_att_1(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=False, signed_2=True) indices = attester_slashing.attestation_1.attesting_indices assert len(indices) >= 3 indices[1], indices[2] = indices[2], indices[1] # unsort second and third index sign_indexed_attestation(spec, state, attester_slashing.attestation_1) yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False) @with_all_phases @spec_state_test def test_invalid_unsorted_att_2(spec, state): attester_slashing = get_valid_attester_slashing(spec, state, signed_1=True, signed_2=False) indices = attester_slashing.attestation_2.attesting_indices assert len(indices) >= 3 indices[1], indices[2] = indices[2], indices[1] # unsort second and third index sign_indexed_attestation(spec, state, attester_slashing.attestation_2) yield from run_attester_slashing_processing(spec, state, attester_slashing, valid=False)
20,150
39.382766
118
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/block_processing/test_process_attestation.py
from eth2spec.test.context import ( spec_state_test, always_bls, never_bls, with_all_phases, spec_test, low_balances, with_custom_state, single_phase, ) from eth2spec.test.helpers.attestations import ( run_attestation_processing, get_valid_attestation, sign_aggregate_attestation, sign_attestation, compute_max_inclusion_slot, ) from eth2spec.test.helpers.state import ( next_slots, next_epoch_via_block, transition_to_slot_via_block, ) from eth2spec.utils.ssz.ssz_typing import Bitlist @with_all_phases @spec_state_test def test_one_basic_attestation(spec, state): attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_test @with_custom_state(balances_fn=low_balances, threshold_fn=lambda spec: spec.config.EJECTION_BALANCE) @single_phase def test_multi_proposer_index_iterations(spec, state): next_slots(spec, state, spec.SLOTS_PER_EPOCH * 2) attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_previous_epoch(spec, state): attestation = get_valid_attestation(spec, state, signed=True) next_epoch_via_block(spec, state) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test @always_bls def test_invalid_attestation_signature(spec, state): attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_empty_participants_zeroes_sig(spec, state): attestation = get_valid_attestation(spec, state, filter_participant_set=lambda comm: []) # 0 participants attestation.signature = spec.BLSSignature(b'\x00' * 96) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_empty_participants_seemingly_valid_sig(spec, state): attestation = get_valid_attestation(spec, state, filter_participant_set=lambda comm: []) # 0 participants # Special BLS value, valid for zero pubkeys on some (but not all) BLS implementations. attestation.signature = spec.BLSSignature(b'\xc0' + b'\x00' * 95) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_before_inclusion_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=True) # do not increment slot to allow for inclusion delay yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_at_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=True) # increment past latest inclusion slot transition_to_slot_via_block(spec, state, compute_max_inclusion_slot(spec, attestation)) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_invalid_after_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=True) # increment past latest inclusion slot transition_to_slot_via_block(spec, state, compute_max_inclusion_slot(spec, attestation) + 1) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_old_source_epoch(spec, state): next_slots(spec, state, spec.SLOTS_PER_EPOCH * 5) state.finalized_checkpoint.epoch = 2 state.previous_justified_checkpoint.epoch = 3 state.current_justified_checkpoint.epoch = 4 attestation = get_valid_attestation(spec, state, slot=(spec.SLOTS_PER_EPOCH * 3) + 1) # test logic sanity check: make sure the attestation is pointing to oldest known source epoch assert attestation.data.source.epoch == state.previous_justified_checkpoint.epoch # Now go beyond that, it will be invalid attestation.data.source.epoch -= 1 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test @always_bls def test_invalid_wrong_index_for_committee_signature(spec, state): attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.data.index += 1 yield from run_attestation_processing(spec, state, attestation, valid=False) def reduce_state_committee_count_from_max(spec, state): """ Modified ``state`` to ensure that it has fewer committees at each slot than ``MAX_COMMITTEES_PER_SLOT`` """ while spec.get_committee_count_per_slot(state, spec.get_current_epoch(state)) >= spec.MAX_COMMITTEES_PER_SLOT: state.validators = state.validators[:len(state.validators) // 2] state.balances = state.balances[:len(state.balances) // 2] @with_all_phases @spec_state_test @never_bls def test_invalid_wrong_index_for_slot_0(spec, state): reduce_state_committee_count_from_max(spec, state) attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) # Invalid index: current committees per slot is less than the max attestation.data.index = spec.MAX_COMMITTEES_PER_SLOT - 1 yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test @never_bls def test_invalid_wrong_index_for_slot_1(spec, state): reduce_state_committee_count_from_max(spec, state) current_epoch = spec.get_current_epoch(state) committee_count = spec.get_committee_count_per_slot(state, current_epoch) attestation = get_valid_attestation(spec, state, index=0) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) # Invalid index: off by one attestation.data.index = committee_count yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test @never_bls def test_invalid_index(spec, state): attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) # Invalid index: off by one (with respect to valid range) on purpose attestation.data.index = spec.MAX_COMMITTEES_PER_SLOT yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_mismatched_target_and_slot(spec, state): next_epoch_via_block(spec, state) next_epoch_via_block(spec, state) attestation = get_valid_attestation(spec, state) attestation.data.slot = attestation.data.slot - spec.SLOTS_PER_EPOCH sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_old_target_epoch(spec, state): assert spec.MIN_ATTESTATION_INCLUSION_DELAY < spec.SLOTS_PER_EPOCH * 2 attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, spec.SLOTS_PER_EPOCH * 2) # target epoch will be too old to handle yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_future_target_epoch(spec, state): assert spec.MIN_ATTESTATION_INCLUSION_DELAY < spec.SLOTS_PER_EPOCH * 2 attestation = get_valid_attestation(spec, state) participants = spec.get_attesting_indices( state, attestation.data, attestation.aggregation_bits ) attestation.data.target.epoch = spec.get_current_epoch(state) + 1 # target epoch will be too new to handle # manually add signature for correct participants attestation.signature = sign_aggregate_attestation(spec, state, attestation.data, participants) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_new_source_epoch(spec, state): attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.data.source.epoch += 1 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_source_root_is_target_root(spec, state): attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.data.source.root = attestation.data.target.root sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_current_source_root(spec, state): next_slots(spec, state, spec.SLOTS_PER_EPOCH * 5) state.finalized_checkpoint.epoch = 2 state.previous_justified_checkpoint = spec.Checkpoint(epoch=3, root=b'\x01' * 32) state.current_justified_checkpoint = spec.Checkpoint(epoch=4, root=b'\x32' * 32) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation = get_valid_attestation(spec, state, slot=spec.SLOTS_PER_EPOCH * 5) # Test logic sanity checks: assert attestation.data.target.epoch == spec.get_current_epoch(state) assert state.current_justified_checkpoint.root != state.previous_justified_checkpoint.root assert attestation.data.source.root == state.current_justified_checkpoint.root # Make attestation source root invalid: should be current justified, not previous one attestation.data.source.root = state.previous_justified_checkpoint.root sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_previous_source_root(spec, state): next_slots(spec, state, spec.SLOTS_PER_EPOCH * 5) state.finalized_checkpoint.epoch = 2 state.previous_justified_checkpoint = spec.Checkpoint(epoch=3, root=b'\x01' * 32) state.current_justified_checkpoint = spec.Checkpoint(epoch=4, root=b'\x32' * 32) attestation = get_valid_attestation(spec, state, slot=(spec.SLOTS_PER_EPOCH * 4) + 1) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) # Test logic sanity checks: assert attestation.data.target.epoch == spec.get_previous_epoch(state) assert state.current_justified_checkpoint.root != state.previous_justified_checkpoint.root assert attestation.data.source.root == state.previous_justified_checkpoint.root # Make attestation source root invalid: should be previous justified, not current one attestation.data.source.root = state.current_justified_checkpoint.root sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_bad_source_root(spec, state): attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.data.source.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_too_many_aggregation_bits(spec, state): attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) # one too many bits attestation.aggregation_bits.append(0b0) yield from run_attestation_processing(spec, state, attestation, valid=False) @with_all_phases @spec_state_test def test_invalid_too_few_aggregation_bits(spec, state): attestation = get_valid_attestation(spec, state) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.aggregation_bits = Bitlist[spec.MAX_VALIDATORS_PER_COMMITTEE]( *([0b1] + [0b0] * (len(attestation.aggregation_bits) - 1))) sign_attestation(spec, state, attestation) # one too few bits attestation.aggregation_bits = attestation.aggregation_bits[:-1] yield from run_attestation_processing(spec, state, attestation, valid=False) # # Full correct attestation contents at different slot inclusions # @with_all_phases @spec_state_test def test_correct_attestation_included_at_min_inclusion_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_correct_attestation_included_at_sqrt_epoch_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, spec.integer_squareroot(spec.SLOTS_PER_EPOCH)) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_correct_attestation_included_at_one_epoch_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, spec.SLOTS_PER_EPOCH) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_correct_attestation_included_at_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=True) next_slots(spec, state, compute_max_inclusion_slot(spec, attestation)) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_invalid_correct_attestation_included_after_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=True) # increment past latest inclusion slot next_slots(spec, state, compute_max_inclusion_slot(spec, attestation) + 1) yield from run_attestation_processing(spec, state, attestation, valid=False) # # Incorrect head but correct source/target at different slot inclusions # @with_all_phases @spec_state_test def test_incorrect_head_included_at_min_inclusion_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.data.beacon_block_root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_incorrect_head_included_at_sqrt_epoch_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.integer_squareroot(spec.SLOTS_PER_EPOCH)) attestation.data.beacon_block_root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_incorrect_head_included_at_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, compute_max_inclusion_slot(spec, attestation)) attestation.data.beacon_block_root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_invalid_incorrect_head_included_after_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=False) # increment past latest inclusion slot next_slots(spec, state, compute_max_inclusion_slot(spec, attestation) + 1) attestation.data.beacon_block_root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) # # Incorrect head and target but correct source at different slot inclusions # @with_all_phases @spec_state_test def test_incorrect_head_and_target_min_inclusion_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.data.beacon_block_root = b'\x42' * 32 attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_incorrect_head_and_target_included_at_sqrt_epoch_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.integer_squareroot(spec.SLOTS_PER_EPOCH)) attestation.data.beacon_block_root = b'\x42' * 32 attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_incorrect_head_and_target_included_at_epoch_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.SLOTS_PER_EPOCH) attestation.data.beacon_block_root = b'\x42' * 32 attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_invalid_incorrect_head_and_target_included_after_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=False) # increment past latest inclusion slot next_slots(spec, state, compute_max_inclusion_slot(spec, attestation) + 1) attestation.data.beacon_block_root = b'\x42' * 32 attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False) # # Correct head and source but incorrect target at different slot inclusions # @with_all_phases @spec_state_test def test_incorrect_target_included_at_min_inclusion_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.MIN_ATTESTATION_INCLUSION_DELAY) attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_incorrect_target_included_at_sqrt_epoch_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.integer_squareroot(spec.SLOTS_PER_EPOCH)) attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_incorrect_target_included_at_epoch_delay(spec, state): attestation = get_valid_attestation(spec, state, signed=False) next_slots(spec, state, spec.SLOTS_PER_EPOCH) attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation) @with_all_phases @spec_state_test def test_invalid_incorrect_target_included_after_max_inclusion_slot(spec, state): attestation = get_valid_attestation(spec, state, signed=False) # increment past latest inclusion slot next_slots(spec, state, compute_max_inclusion_slot(spec, attestation) + 1) attestation.data.target.root = b'\x42' * 32 sign_attestation(spec, state, attestation) yield from run_attestation_processing(spec, state, attestation, valid=False)
20,053
33.105442
114
py
consensus-specs
consensus-specs-master/tests/core/pyspec/eth2spec/test/phase0/block_processing/test_process_block_header.py
from copy import deepcopy from eth2spec.test.context import spec_state_test, expect_assertion_error, with_all_phases from eth2spec.test.helpers.block import build_empty_block_for_next_slot from eth2spec.test.helpers.state import next_slot def prepare_state_for_header_processing(spec, state): spec.process_slots(state, state.slot + 1) def run_block_header_processing(spec, state, block, prepare_state=True, valid=True): """ Run ``process_block_header``, yielding: - pre-state ('pre') - block ('block') - post-state ('post'). If ``valid == False``, run expecting ``AssertionError`` """ if prepare_state: prepare_state_for_header_processing(spec, state) yield 'pre', state yield 'block', block if not valid: expect_assertion_error(lambda: spec.process_block_header(state, block)) yield 'post', None return spec.process_block_header(state, block) yield 'post', state @with_all_phases @spec_state_test def test_basic_block_header(spec, state): block = build_empty_block_for_next_slot(spec, state) yield from run_block_header_processing(spec, state, block) @with_all_phases @spec_state_test def test_invalid_slot_block_header(spec, state): block = build_empty_block_for_next_slot(spec, state) block.slot = state.slot + 2 # invalid slot yield from run_block_header_processing(spec, state, block, valid=False) @with_all_phases @spec_state_test def test_invalid_proposer_index(spec, state): block = build_empty_block_for_next_slot(spec, state) active_indices = spec.get_active_validator_indices(state, spec.get_current_epoch(state)) active_indices = [i for i in active_indices if i != block.proposer_index] block.proposer_index = active_indices[0] # invalid proposer index yield from run_block_header_processing(spec, state, block, valid=False) @with_all_phases @spec_state_test def test_invalid_parent_root(spec, state): block = build_empty_block_for_next_slot(spec, state) block.parent_root = b'\12' * 32 # invalid prev root yield from run_block_header_processing(spec, state, block, valid=False) @with_all_phases @spec_state_test def test_invalid_multiple_blocks_single_slot(spec, state): block = build_empty_block_for_next_slot(spec, state) prepare_state_for_header_processing(spec, state) spec.process_block_header(state, block) assert state.latest_block_header.slot == state.slot child_block = block.copy() child_block.parent_root = block.hash_tree_root() yield from run_block_header_processing(spec, state, child_block, prepare_state=False, valid=False) @with_all_phases @spec_state_test def test_invalid_proposer_slashed(spec, state): # use stub state to get proposer index of next slot stub_state = deepcopy(state) next_slot(spec, stub_state) proposer_index = spec.get_beacon_proposer_index(stub_state) # set proposer to slashed state.validators[proposer_index].slashed = True block = build_empty_block_for_next_slot(spec, state) yield from run_block_header_processing(spec, state, block, valid=False)
3,143
29.823529
102
py