Пример #1
0
def sample_beacon_state_params(config, genesis_slot, genesis_epoch,
                               sample_fork_params, sample_eth1_data_params,
                               sample_block_header_params,
                               sample_crosslink_record_params):
    return {
        # Versioning
        'genesis_time':
        0,
        'slot':
        genesis_slot + 100,
        'fork':
        Fork(**sample_fork_params),
        # History
        'latest_block_header':
        BeaconBlockHeader(**sample_block_header_params),
        'block_roots': (ZERO_HASH32, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        'state_roots': (ZERO_HASH32, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        'historical_roots': (),
        # Eth1
        'eth1_data':
        Eth1Data(**sample_eth1_data_params),
        'eth1_data_votes': (),
        'eth1_deposit_index':
        0,
        # Registry
        'validators': (),
        'balances': (),
        # Shuffling
        'start_shard':
        1,
        'randao_mixes': (ZERO_HASH32, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        'active_index_roots':
        (ZERO_HASH32, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        # Slashings
        'slashed_balances': (0, ) * config.EPOCHS_PER_SLASHED_BALANCES_VECTOR,
        # Attestations
        'previous_epoch_attestations': (),
        'current_epoch_attestations': (),
        # Crosslinks
        'previous_crosslinks':
        ((Crosslink(**sample_crosslink_record_params), ) * config.SHARD_COUNT),
        'current_crosslinks':
        ((Crosslink(**sample_crosslink_record_params), ) * config.SHARD_COUNT),
        # Justification
        'previous_justified_epoch':
        0,
        'previous_justified_root':
        b'\x99' * 32,
        'current_justified_epoch':
        0,
        'current_justified_root':
        b'\x55' * 32,
        'justification_bitfield':
        0,
        # Finality
        'finalized_epoch':
        0,
        'finalized_root':
        b'\x33' * 32,
    }
Пример #2
0
def sample_beacon_state_params(sample_fork_params, sample_eth1_data_params):
    return {
        'slot': 0,
        'genesis_time': 0,
        'fork': Fork(**sample_fork_params),
        'validator_registry': (),
        'validator_balances': (),
        'validator_registry_update_epoch': 0,
        'latest_randao_mixes': (),
        'previous_epoch_start_shard': 1,
        'current_epoch_start_shard': 2,
        'previous_calculation_epoch': 0,
        'current_calculation_epoch': 0,
        'previous_epoch_seed': b'\x77' * 32,
        'current_epoch_seed': b'\x88' * 32,
        'previous_justified_epoch': 0,
        'justified_epoch': 0,
        'justification_bitfield': 0,
        'finalized_epoch': 0,
        'latest_crosslinks': (),
        'latest_block_roots': (),
        'latest_index_roots': (),
        'latest_penalized_balances': (),
        'latest_attestations': (),
        'batched_block_roots': (),
        'latest_eth1_data': Eth1Data(**sample_eth1_data_params),
        'eth1_data_votes': (),
        'deposit_index': 0,
    }
Пример #3
0
def test_process_eth1_data(original_votes,
                           block_data,
                           expected_votes,
                           sample_beacon_state_params,
                           sample_beacon_block_params,
                           sample_beacon_block_body_params,
                           config):
    eth1_data_votes = tuple(mapcat(
        _expand_eth1_votes,
        original_votes,
    ))
    state = BeaconState(**sample_beacon_state_params).copy(
        eth1_data_votes=eth1_data_votes,
    )

    block_body = BeaconBlockBody(**sample_beacon_block_body_params).copy(
        eth1_data=Eth1Data(
            block_hash=block_data,
        ),
    )

    block = BeaconBlock(**sample_beacon_block_params).copy(
        body=block_body,
    )

    updated_state = process_eth1_data(state, block, config)
    updated_votes = updated_state.eth1_data_votes
    expanded_expected_votes = tuple(mapcat(
        _expand_eth1_votes,
        expected_votes,
    ))

    assert updated_votes == expanded_expected_votes
Пример #4
0
def create_mock_genesis(
    pubkeys: Sequence[BLSPubkey],
    config: Eth2Config,
    keymap: Dict[BLSPubkey, int],
    genesis_block_class: Type[BaseBeaconBlock],
    genesis_time: Timestamp = ZERO_TIMESTAMP,
) -> Tuple[BeaconState, BaseBeaconBlock]:
    genesis_deposits, deposit_root = create_mock_deposits_and_root(
        pubkeys=pubkeys, keymap=keymap, config=config)

    genesis_eth1_data = Eth1Data(
        deposit_root=deposit_root,
        deposit_count=len(genesis_deposits),
        block_hash=ZERO_HASH32,
    )

    state = initialize_beacon_state_from_eth1(
        eth1_block_hash=genesis_eth1_data.block_hash,
        eth1_timestamp=genesis_time,
        deposits=genesis_deposits,
        config=config,
    )

    block = get_genesis_block(genesis_state_root=state.hash_tree_root,
                              block_class=genesis_block_class)
    assert len(state.validators) == len(pubkeys)

    return state, block
def test_ensure_update_eth1_vote_if_exists(genesis_state, config,
                                           vote_offsets):
    # one less than a majority is the majority divided by 2
    threshold = config.SLOTS_PER_ETH1_VOTING_PERIOD // 2
    data_votes = tuple(
        concat((Eth1Data.create(block_hash=(i).to_bytes(32, "little")), ) *
               (threshold + offset) for i, offset in enumerate(vote_offsets)))
    state = genesis_state

    for vote in data_votes:
        state = process_eth1_data(
            state,
            BeaconBlock.create(body=BeaconBlockBody.create(eth1_data=vote)),
            config,
        )

    if not vote_offsets:
        assert state.eth1_data == genesis_state.eth1_data

    # we should update the 'latest' entry if we have a majority
    for offset in vote_offsets:
        if offset <= 0:
            assert genesis_state.eth1_data == state.eth1_data
        else:
            assert state.eth1_data == data_votes[0]
Пример #6
0
def create_mock_genesis(
    num_validators: int,
    config: Eth2Config,
    keymap: Dict[BLSPubkey, int],
    genesis_block_class: Type[BaseBeaconBlock],
    genesis_time: Timestamp = ZERO_TIMESTAMP
) -> Tuple[BeaconState, BaseBeaconBlock]:
    assert num_validators <= len(keymap)

    genesis_deposits, deposit_root = create_mock_deposits_and_root(
        pubkeys=list(keymap)[:num_validators],
        keymap=keymap,
        config=config,
    )

    genesis_eth1_data = Eth1Data(
        deposit_root=deposit_root,
        deposit_count=len(genesis_deposits),
        block_hash=ZERO_HASH32,
    )

    state = get_genesis_beacon_state(
        genesis_deposits=genesis_deposits,
        genesis_time=genesis_time,
        genesis_eth1_data=genesis_eth1_data,
        config=config,
    )

    block = get_genesis_block(
        genesis_state_root=state.root,
        block_class=genesis_block_class,
    )
    assert len(state.validators) == num_validators

    return state, block
Пример #7
0
def create_block_on_state(
        *,
        state: BeaconState,
        config: BeaconConfig,
        state_machine: BaseBeaconStateMachine,
        block_class: BaseBeaconBlock,
        parent_block: BaseBeaconBlock,
        slot: SlotNumber,
        validator_index: ValidatorIndex,
        privkey: int,
        attestations: Sequence[Attestation],
        check_proposer_index: bool = True) -> BaseBeaconBlock:
    """
    Create a beacon block with the given parameters.
    """
    # Check proposer
    if check_proposer_index:
        validate_proposer_index(state, config, slot, validator_index)

    # Prepare block: slot and parent_root
    block = block_class.from_parent(
        parent_block=parent_block,
        block_params=FromBlockParams(slot=slot),
    )

    # TODO: Add more operations
    randao_reveal = ZERO_HASH32
    eth1_data = Eth1Data.create_empty_data()
    body = BeaconBlockBody.create_empty_body().copy(
        attestations=attestations, )

    block = block.copy(
        randao_reveal=randao_reveal,
        eth1_data=eth1_data,
        body=body,
    )

    # Apply state transition to get state root
    state, block = state_machine.import_block(block,
                                              check_proposer_signature=True)

    # Sign
    empty_signature_block_root = block.block_without_signature_root
    proposal_root = ProposalSignedData(
        slot,
        config.BEACON_CHAIN_SHARD_NUMBER,
        empty_signature_block_root,
    ).root
    domain = get_domain(
        state.fork,
        slot_to_epoch(slot, config.EPOCH_LENGTH),
        SignatureDomain.DOMAIN_PROPOSAL,
    )
    block = block.copy(signature=bls.sign(
        message=proposal_root,
        privkey=privkey,
        domain=domain,
    ), )

    return block
Пример #8
0
def sample_beacon_state_params(sample_fork_params, sample_eth1_data_params):
    return {
        'slot': 0,
        'genesis_time': 0,
        'fork': Fork(**sample_fork_params),
        'validator_registry': (),
        'validator_balances': (),
        'validator_registry_update_slot': 10,
        'validator_registry_exit_count': 10,
        'latest_randao_mixes': (),
        'latest_vdf_outputs': (),
        'persistent_committees': (),
        'persistent_committee_reassignments': (),
        'previous_epoch_start_shard': 1,
        'current_epoch_start_shard': 2,
        'previous_epoch_calculation_slot': 5,
        'current_epoch_calculation_slot': 10,
        'previous_epoch_seed': b'\x77' * 32,
        'current_epoch_seed': b'\x88' * 32,
        'custody_challenges': (),
        'previous_justified_slot': 0,
        'justified_slot': 0,
        'justification_bitfield': 0,
        'finalized_slot': 0,
        'latest_crosslinks': (),
        'latest_block_roots': (),
        'latest_index_roots': (),
        'latest_penalized_balances': (),
        'latest_attestations': (),
        'batched_block_roots': (),
        'latest_eth1_data': Eth1Data(**sample_eth1_data_params),
        'eth1_data_votes': (),
    }
Пример #9
0
def sample_beacon_state_params(
    config,
    genesis_slot,
    genesis_epoch,
    sample_fork_params,
    sample_eth1_data_params,
    sample_block_header_params,
    sample_crosslink_record_params,
):
    return {
        # Versioning
        "genesis_time":
        0,
        "slot":
        genesis_slot + 100,
        "fork":
        Fork(**sample_fork_params),
        # History
        "latest_block_header":
        BeaconBlockHeader(**sample_block_header_params),
        "block_roots": (ZERO_HASH32, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        "state_roots": (ZERO_HASH32, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        "historical_roots": (),
        # Eth1
        "eth1_data":
        Eth1Data(**sample_eth1_data_params),
        "eth1_data_votes": (),
        "eth1_deposit_index":
        0,
        # Registry
        "validators": (),
        "balances": (),
        # Shuffling
        "start_shard":
        1,
        "randao_mixes": (ZERO_HASH32, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        "active_index_roots":
        (ZERO_HASH32, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        "compact_committees_roots":
        (ZERO_HASH32, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        # Slashings
        "slashings": (0, ) * config.EPOCHS_PER_SLASHINGS_VECTOR,
        # Attestations
        "previous_epoch_attestations": (),
        "current_epoch_attestations": (),
        # Crosslinks
        "previous_crosslinks":
        ((Crosslink(**sample_crosslink_record_params), ) * config.SHARD_COUNT),
        "current_crosslinks":
        ((Crosslink(**sample_crosslink_record_params), ) * config.SHARD_COUNT),
        # Justification
        "justification_bits": (False, ) * JUSTIFICATION_BITS_LENGTH,
        "previous_justified_checkpoint":
        Checkpoint(epoch=0, root=b"\x99" * 32),
        "current_justified_checkpoint":
        Checkpoint(epoch=0, root=b"\x55" * 32),
        # Finality
        "finalized_checkpoint":
        Checkpoint(epoch=0, root=b"\x33" * 32),
    }
def test_process_eth1_data(
    original_votes,
    block_data,
    expected_votes,
    sample_beacon_state_params,
    sample_beacon_block_params,
    sample_beacon_block_body_params,
    config,
):
    eth1_data_votes = tuple(mapcat(_expand_eth1_votes, original_votes))
    state = BeaconState.create(**sample_beacon_state_params).set(
        "eth1_data_votes", eth1_data_votes)

    block_body = BeaconBlockBody.create(
        **sample_beacon_block_body_params).mset(
            "eth1_data", Eth1Data.create(block_hash=block_data))

    block = BeaconBlock.create(**sample_beacon_block_params).set(
        "body", block_body)

    updated_state = process_eth1_data(state, block, config)
    updated_votes = updated_state.eth1_data_votes
    expanded_expected_votes = tuple(mapcat(_expand_eth1_votes, expected_votes))

    assert tuple(updated_votes) == expanded_expected_votes
Пример #11
0
def create_block_on_state(state: BeaconState, config: BeaconConfig,
                          block_class: BaseBeaconBlock,
                          parent_block: BaseBeaconBlock, slot: SlotNumber,
                          validator_index: int, privkey: int,
                          attestations: Sequence[Attestation]):
    """
    Create a beacon block with the given parameters.
    """
    # Check proposer
    beacon_proposer_index = get_beacon_proposer_index(
        state.copy(slot=slot, ),
        slot,
        config.EPOCH_LENGTH,
        config.TARGET_COMMITTEE_SIZE,
        config.SHARD_COUNT,
    )

    if validator_index != beacon_proposer_index:
        raise ProposerIndexError

    # Prepare block: slot and parent_root
    block = block_class.from_parent(
        parent_block=parent_block,
        block_params=FromBlockParams(slot=slot),
    )

    # TODO: Add more operations
    randao_reveal = ZERO_HASH32
    eth1_data = Eth1Data.create_empty_data()
    body = BeaconBlockBody.create_empty_body().copy(
        attestations=attestations, )

    block = block.copy(
        randao_reveal=randao_reveal,
        eth1_data=eth1_data,
        body=body,
    )

    # Sign
    empty_signature_block_root = block.block_without_signature_root
    proposal_root = ProposalSignedData(
        slot,
        config.BEACON_CHAIN_SHARD_NUMBER,
        empty_signature_block_root,
    ).root
    domain = get_domain(
        state.fork,
        slot,
        SignatureDomain.DOMAIN_PROPOSAL,
    )
    block = block.copy(signature=bls.sign(
        message=proposal_root,
        privkey=privkey,
        domain=domain,
    ), )

    return block
Пример #12
0
def genesis_state(genesis_validators, genesis_balances, genesis_time,
                  sample_eth1_data_params, config):
    genesis_eth1_data = Eth1Data(**sample_eth1_data_params).copy(
        deposit_count=len(genesis_validators))

    return create_mock_genesis_state_from_validators(genesis_time,
                                                     genesis_eth1_data,
                                                     genesis_validators,
                                                     genesis_balances, config)
Пример #13
0
def test_get_genesis_block():
    startup_state_root = b'\x10' * 32
    genesis_slot = 10
    genesis_block = get_genesis_block(startup_state_root, genesis_slot, BeaconBlock)
    assert genesis_block.slot == genesis_slot
    assert genesis_block.parent_root == ZERO_HASH32
    assert genesis_block.state_root == startup_state_root
    assert genesis_block.randao_reveal == ZERO_HASH32
    assert genesis_block.eth1_data == Eth1Data.create_empty_data()
    assert genesis_block.signature == EMPTY_SIGNATURE
    assert genesis_block.body.is_empty
Пример #14
0
def sample_beacon_block_body_params(sample_eth1_data_params):
    return {
        'randao_reveal': SAMPLE_SIGNATURE,
        'eth1_data': Eth1Data(**sample_eth1_data_params),
        'proposer_slashings': (),
        'attester_slashings': (),
        'attestations': (),
        'deposits': (),
        'voluntary_exits': (),
        'transfers': (),
    }
Пример #15
0
def sample_beacon_block_params(sample_beacon_block_body_params,
                               sample_eth1_data_params):
    return {
        'slot': 10,
        'parent_root': ZERO_HASH32,
        'state_root': b'\x55' * 32,
        'randao_reveal': EMPTY_SIGNATURE,
        'eth1_data': Eth1Data(**sample_eth1_data_params),
        'signature': EMPTY_SIGNATURE,
        'body': BeaconBlockBody(**sample_beacon_block_body_params)
    }
Пример #16
0
def create_block_on_state(
        *,
        state: BeaconState,
        config: Eth2Config,
        state_machine: BaseBeaconStateMachine,
        block_class: Type[BaseBeaconBlock],
        parent_block: BaseBeaconBlock,
        slot: Slot,
        validator_index: ValidatorIndex,
        privkey: int,
        attestations: Sequence[Attestation],
        check_proposer_index: bool = True) -> BaseBeaconBlock:
    """
    Create a beacon block with the given parameters.
    """
    # Check proposer
    if check_proposer_index:
        validate_proposer_index(state, config, slot, validator_index)

    # Prepare block: slot and previous_block_root
    block = block_class.from_parent(
        parent_block=parent_block,
        block_params=FromBlockParams(slot=slot),
    )

    # TODO: Add more operations
    randao_reveal = _generate_randao_reveal(privkey, slot, state.fork, config)
    eth1_data = Eth1Data.create_empty_data()
    body = BeaconBlockBody.create_empty_body().copy(
        randao_reveal=randao_reveal,
        eth1_data=eth1_data,
        attestations=attestations,
    )

    block = block.copy(body=body, )

    # Apply state transition to get state root
    state, block = state_machine.import_block(block,
                                              check_proposer_signature=False)

    # Sign
    # TODO make sure we use the correct signed_root
    signature = sign_transaction(
        message_hash=block.signed_root,
        privkey=privkey,
        fork=state.fork,
        slot=slot,
        signature_domain=SignatureDomain.DOMAIN_BEACON_BLOCK,
        slots_per_epoch=config.SLOTS_PER_EPOCH,
    )

    block = block.copy(signature=signature, )

    return block
Пример #17
0
def get_genesis_block(startup_state_root: Hash32, genesis_slot: SlotNumber,
                      block_class: Type[BaseBeaconBlock]) -> BaseBeaconBlock:
    return block_class(
        slot=genesis_slot,
        parent_root=ZERO_HASH32,
        state_root=startup_state_root,
        randao_reveal=ZERO_HASH32,
        eth1_data=Eth1Data.create_empty_data(),
        signature=EMPTY_SIGNATURE,
        body=BeaconBlockBody.create_empty_body(),
    )
Пример #18
0
def sample_beacon_block_body_params(sample_signature, sample_eth1_data_params):
    return {
        "randao_reveal": sample_signature,
        "eth1_data": Eth1Data.create(**sample_eth1_data_params),
        "graffiti": ZERO_HASH32,
        "proposer_slashings": (),
        "attester_slashings": (),
        "attestations": (),
        "deposits": (),
        "voluntary_exits": (),
    }
Пример #19
0
def initialize_beacon_state_from_eth1(*, eth1_block_hash: Hash32,
                                      eth1_timestamp: Timestamp,
                                      deposits: Sequence[Deposit],
                                      config: Eth2Config) -> BeaconState:
    fork = Fork.create(
        previous_version=config.GENESIS_FORK_VERSION,
        current_version=config.GENESIS_FORK_VERSION,
        epoch=GENESIS_EPOCH,
    )

    state = BeaconState.create(
        genesis_time=_genesis_time_from_eth1_timestamp(eth1_timestamp,
                                                       config.GENESIS_DELAY),
        fork=fork,
        eth1_data=Eth1Data.create(block_hash=eth1_block_hash,
                                  deposit_count=len(deposits)),
        latest_block_header=BeaconBlockHeader.create(
            body_root=BeaconBlockBody.create().hash_tree_root),
        block_roots=(ZERO_ROOT, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        state_roots=(ZERO_HASH32, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        randao_mixes=(eth1_block_hash, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        slashings=(Gwei(0), ) * config.EPOCHS_PER_SLASHINGS_VECTOR,
        config=config,
    )

    # Process genesis deposits
    for index, deposit in enumerate(deposits):
        deposit_data_list = tuple(deposit.data
                                  for deposit in deposits[:index + 1])
        deposit_root = ssz.get_hash_tree_root(
            deposit_data_list,
            ssz.List(DepositData, 2**DEPOSIT_CONTRACT_TREE_DEPTH))
        state = state.transform(("eth1_data", "deposit_root"), deposit_root)
        state = process_deposit(state=state, deposit=deposit, config=config)

    # Process genesis activations
    for validator_index in range(len(state.validators)):
        validator_index = ValidatorIndex(validator_index)
        balance = state.balances[validator_index]
        effective_balance = calculate_effective_balance(balance, config)

        state = state.transform(
            ("validators", validator_index, "effective_balance"),
            effective_balance)

        if effective_balance == config.MAX_EFFECTIVE_BALANCE:
            activated_validator = activate_validator(
                state.validators[validator_index], GENESIS_EPOCH)
            state = state.transform(("validators", validator_index),
                                    activated_validator)

    return state.set("genesis_validators_root",
                     state.validators.hash_tree_root)
Пример #20
0
def sample_beacon_block_body_params(sample_signature, sample_eth1_data_params):
    return {
        'randao_reveal': sample_signature,
        'eth1_data': Eth1Data(**sample_eth1_data_params),
        'graffiti': ZERO_HASH32,
        'proposer_slashings': (),
        'attester_slashings': (),
        'attestations': (),
        'deposits': (),
        'voluntary_exits': (),
        'transfers': (),
    }
Пример #21
0
    def _get_eth1_data(
            self, distance: BlockNumber,
            eth1_voting_period_start_timestamp: Timestamp) -> Eth1Data:
        """
        Return `Eth1Data` at `distance` relative to the eth1 block earlier and closest to the
        timestamp `eth1_voting_period_start_timestamp`.
        Ref: https://github.com/ethereum/eth2.0-specs/blob/61f2a0662ebcfb4c097360cc1835c5f01872705c/specs/validator/0_beacon-chain-validator.md#eth1-data  # noqa: E501

        First, we find the `eth1_block` whose timestamp is the largest timestamp which is smaller
        than `eth1_voting_period_start_timestamp`. Then, find the block `target_block` at number
        `eth1_block.number - distance`. Therefore, we can return `Eth1Data` according to the
        information of this block.
        """
        eth1_voting_period_start_block_number = self._get_closest_eth1_voting_period_start_block(
            eth1_voting_period_start_timestamp)
        target_block_number = BlockNumber(
            eth1_voting_period_start_block_number - distance)
        if target_block_number < 0:
            raise Eth1MonitorValidationError(
                f"`distance` is larger than `eth1_voting_period_start_block_number`: "
                f"`distance`={distance}, ",
                f"eth1_voting_period_start_block_number={eth1_voting_period_start_block_number}",
            )
        try:
            block = self._eth1_data_provider.get_block(target_block_number)
        except BlockNotFound:
            raise Eth1MonitorValidationError(
                f"Block does not exist for block number={target_block_number}")
        block_hash = block.block_hash
        # `Eth1Data.deposit_count`: get the `deposit_count` corresponding to the block.
        accumulated_deposit_count = self._get_accumulated_deposit_count(
            target_block_number)
        if accumulated_deposit_count == 0:
            raise Eth1MonitorValidationError(
                f"failed to make `Eth1Data`: `deposit_count = 0` at block #{target_block_number}"
            )
        # Verify that the deposit data in db and the deposit data in contract match
        deposit_data_in_range = self._db.get_deposit_data_range(
            0, accumulated_deposit_count)
        _, deposit_root = make_deposit_tree_and_root(deposit_data_in_range)
        contract_deposit_root = self._get_deposit_root_from_contract(
            target_block_number)
        if contract_deposit_root != deposit_root:
            raise DepositDataCorrupted(
                "deposit root built locally mismatches the one in the contract on chain: "
                f"contract_deposit_root={contract_deposit_root.hex()}, "
                f"deposit_root={deposit_root.hex()}")
        return Eth1Data.create(
            deposit_root=deposit_root,
            deposit_count=accumulated_deposit_count,
            block_hash=block_hash,
        )
Пример #22
0
def create_mock_genesis(
        num_validators: int,
        config: Eth2Config,
        keymap: Dict[BLSPubkey, int],
        genesis_block_class: Type[BaseBeaconBlock],
        genesis_time: Timestamp=ZERO_TIMESTAMP) -> Tuple[BeaconState, BaseBeaconBlock]:
    assert num_validators <= len(keymap)

    pubkeys = list(keymap)[:num_validators]

    genesis_validator_deposits, deposit_root = create_mock_genesis_validator_deposits_and_root(
        num_validators=num_validators,
        config=config,
        pubkeys=pubkeys,
        keymap=keymap,
    )

    genesis_eth1_data = Eth1Data(
        deposit_root=deposit_root,
        block_hash=ZERO_HASH32,
    )

    state = get_genesis_beacon_state(
        genesis_validator_deposits=genesis_validator_deposits,
        genesis_time=genesis_time,
        genesis_eth1_data=genesis_eth1_data,
        genesis_slot=config.GENESIS_SLOT,
        genesis_epoch=config.GENESIS_EPOCH,
        genesis_fork_version=config.GENESIS_FORK_VERSION,
        genesis_start_shard=config.GENESIS_START_SHARD,
        shard_count=config.SHARD_COUNT,
        min_seed_lookahead=config.MIN_SEED_LOOKAHEAD,
        slots_per_historical_root=config.SLOTS_PER_HISTORICAL_ROOT,
        latest_active_index_roots_length=config.LATEST_ACTIVE_INDEX_ROOTS_LENGTH,
        slots_per_epoch=config.SLOTS_PER_EPOCH,
        max_deposit_amount=config.MAX_DEPOSIT_AMOUNT,
        latest_slashed_exit_length=config.LATEST_SLASHED_EXIT_LENGTH,
        latest_randao_mixes_length=config.LATEST_RANDAO_MIXES_LENGTH,
        activation_exit_delay=config.ACTIVATION_EXIT_DELAY,
        deposit_contract_tree_depth=config.DEPOSIT_CONTRACT_TREE_DEPTH,
        block_class=genesis_block_class,
    )

    block = get_genesis_block(
        genesis_state_root=state.root,
        genesis_slot=config.GENESIS_SLOT,
        block_class=genesis_block_class,
    )
    assert len(state.validator_registry) == num_validators

    return state, block
Пример #23
0
def create_test_block(parent=None, **kwargs):
    defaults = {
        "slot": 0,
        "parent_root": ZERO_HASH32,
        "state_root": ZERO_HASH32,  # note: not the actual genesis state root
        "randao_reveal": EMPTY_SIGNATURE,
        "eth1_data": Eth1Data.create_empty_data(),
        "signature": EMPTY_SIGNATURE,
        "body": BeaconBlockBody.create_empty_body()
    }

    if parent is not None:
        kwargs["parent_root"] = parent.root
        kwargs["slot"] = parent.slot + 1

    return BeaconBlock(**merge(defaults, kwargs))
def _build_chain_of_blocks_with_states(
    chain,
    state,
    parent_block,
    slots,
    config,
    keymap,
    attestation_participation=1.0,
    eth1_block_hash=ZERO_HASH32,
):
    blocks = ()
    states = ()
    for slot in range(parent_block.slot + 1, parent_block.slot + 1 + slots):
        sm = chain.get_state_machine(state.slot)
        pre_state, _ = sm.apply_state_transition(state, future_slot=slot)
        proposer_index = get_beacon_proposer_index(pre_state, config)
        public_key = state.validators[proposer_index].pubkey
        private_key = keymap[public_key]
        randao_reveal = generate_randao_reveal(private_key, slot, pre_state,
                                               config)

        attestations = create_mock_signed_attestations_at_slot(
            state,
            config,
            sm,
            slot - 1,
            parent_block.hash_tree_root,
            keymap,
            voted_attesters_ratio=attestation_participation,
        )
        block = create_block(
            slot,
            parent_block.hash_tree_root,
            randao_reveal,
            Eth1Data.create(block_hash=eth1_block_hash),
            attestations,
            state,
            sm,
            private_key,
        )

        parent_block = block.message
        state, block = sm.apply_state_transition(state, block)

        blocks += (block, )
        states += (state, )
    return blocks, states
Пример #25
0
def create_mock_genesis(
        num_validators: int,
        config: BeaconConfig,
        keymap: Dict[BLSPubkey, int],
        genesis_block_class: Type[BaseBeaconBlock],
        genesis_time: Timestamp = 0) -> Tuple[BeaconState, BaseBeaconBlock]:
    latest_eth1_data = Eth1Data.create_empty_data()

    assert num_validators <= len(keymap)

    pubkeys = list(keymap)[:num_validators]

    initial_validator_deposits = create_mock_initial_validator_deposits(
        num_validators=num_validators,
        config=config,
        pubkeys=pubkeys,
        keymap=keymap,
    )
    state = get_initial_beacon_state(
        initial_validator_deposits=initial_validator_deposits,
        genesis_time=genesis_time,
        latest_eth1_data=latest_eth1_data,
        genesis_slot=config.GENESIS_SLOT,
        genesis_epoch=config.GENESIS_EPOCH,
        genesis_fork_version=config.GENESIS_FORK_VERSION,
        genesis_start_shard=config.GENESIS_START_SHARD,
        shard_count=config.SHARD_COUNT,
        seed_lookahead=config.SEED_LOOKAHEAD,
        latest_block_roots_length=config.LATEST_BLOCK_ROOTS_LENGTH,
        latest_index_roots_length=config.LATEST_INDEX_ROOTS_LENGTH,
        epoch_length=config.EPOCH_LENGTH,
        max_deposit_amount=config.MAX_DEPOSIT_AMOUNT,
        latest_penalized_exit_length=config.LATEST_PENALIZED_EXIT_LENGTH,
        latest_randao_mixes_length=config.LATEST_RANDAO_MIXES_LENGTH,
        entry_exit_delay=config.ENTRY_EXIT_DELAY,
    )

    block = get_genesis_block(
        startup_state_root=state.root,
        genesis_slot=config.GENESIS_SLOT,
        block_class=genesis_block_class,
    )
    assert len(state.validator_registry) == num_validators

    return state, block
Пример #26
0
def sample_beacon_state_params(config, sample_fork_params,
                               sample_eth1_data_params,
                               sample_block_header_params):
    return {
        # Versioning
        "genesis_time":
        0,
        "slot":
        GENESIS_SLOT + 100,
        "fork":
        Fork.create(**sample_fork_params),
        # History
        "latest_block_header":
        BeaconBlockHeader.create(**sample_block_header_params),
        "block_roots": (ZERO_HASH32, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        "state_roots": (ZERO_HASH32, ) * config.SLOTS_PER_HISTORICAL_ROOT,
        "historical_roots": (),
        # Eth1
        "eth1_data":
        Eth1Data.create(**sample_eth1_data_params),
        "eth1_data_votes": (),
        "eth1_deposit_index":
        0,
        # Registry
        "validators": (),
        "balances": (),
        # Shuffling
        "randao_mixes": (ZERO_HASH32, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        # Slashings
        "slashings": (0, ) * config.EPOCHS_PER_SLASHINGS_VECTOR,
        # Attestations
        "previous_epoch_attestations": (),
        "current_epoch_attestations": (),
        # Justification
        "justification_bits": (False, ) * JUSTIFICATION_BITS_LENGTH,
        "previous_justified_checkpoint":
        Checkpoint.create(epoch=0, root=b"\x99" * 32),
        "current_justified_checkpoint":
        Checkpoint.create(epoch=0, root=b"\x55" * 32),
        # Finality
        "finalized_checkpoint":
        Checkpoint.create(epoch=0, root=b"\x33" * 32),
    }
Пример #27
0
def initialize_beacon_state_from_eth1(*, eth1_block_hash: Hash32,
                                      eth1_timestamp: Timestamp,
                                      deposits: Sequence[Deposit],
                                      config: Eth2Config) -> BeaconState:
    state = BeaconState(
        genesis_time=_genesis_time_from_eth1_timestamp(eth1_timestamp),
        eth1_data=Eth1Data(block_hash=eth1_block_hash,
                           deposit_count=len(deposits)),
        latest_block_header=BeaconBlockHeader(
            body_root=BeaconBlockBody().hash_tree_root),
        randao_mixes=(eth1_block_hash, ) * config.EPOCHS_PER_HISTORICAL_VECTOR,
        config=config,
    )

    # Process genesis deposits
    for index, deposit in enumerate(deposits):
        deposit_data_list = tuple(deposit.data
                                  for deposit in deposits[:index + 1])
        state = state.copy(eth1_data=state.eth1_data.copy(
            deposit_root=ssz.get_hash_tree_root(
                deposit_data_list,
                ssz.List(DepositData, 2**DEPOSIT_CONTRACT_TREE_DEPTH),
            )))
        state = process_deposit(state=state, deposit=deposit, config=config)

    # Process genesis activations
    for validator_index in range(len(state.validators)):
        validator_index = ValidatorIndex(validator_index)
        balance = state.balances[validator_index]
        effective_balance = calculate_effective_balance(balance, config)

        state = state.update_validator_with_fn(
            validator_index,
            lambda v, *_: v.copy(effective_balance=effective_balance))

        if effective_balance == config.MAX_EFFECTIVE_BALANCE:
            state = state.update_validator_with_fn(validator_index,
                                                   activate_validator,
                                                   config.GENESIS_EPOCH)

    return state
Пример #28
0
async def test_send_single_block(request, event_loop):
    alice, msg_buffer = await get_command_setup(request, event_loop)

    request_id = 5
    block = BeaconBlock(
        slot=1,
        parent_root=ZERO_HASH32,
        state_root=ZERO_HASH32,
        randao_reveal=EMPTY_SIGNATURE,
        eth1_data=Eth1Data.create_empty_data(),
        signature=EMPTY_SIGNATURE,
        body=BeaconBlockBody.create_empty_body(),
    )
    alice.sub_proto.send_blocks((block,), request_id=request_id)

    message = await msg_buffer.msg_queue.get()
    assert isinstance(message.command, BeaconBlocks)
    assert message.payload == {
        "request_id": request_id,
        "encoded_blocks": (ssz.encode(block),),
    }
Пример #29
0
async def test_send_multiple_blocks(request, event_loop):
    alice, msg_buffer = await get_command_setup(request, event_loop)

    request_id = 5
    blocks = tuple(
        BeaconBlock(
            slot=slot,
            parent_root=ZERO_HASH32,
            state_root=ZERO_HASH32,
            randao_reveal=ZERO_HASH32,
            eth1_data=Eth1Data.create_empty_data(),
            signature=EMPTY_SIGNATURE,
            body=BeaconBlockBody.create_empty_body(),
        ) for slot in range(3))
    alice.sub_proto.send_blocks(blocks, request_id=request_id)

    message = await msg_buffer.msg_queue.get()
    assert isinstance(message.command, BeaconBlocks)
    assert message.payload == {
        "request_id": request_id,
        "blocks": blocks,
    }
Пример #30
0
def sample_beacon_state_params(genesis_slot,
                               genesis_epoch,
                               sample_fork_params,
                               sample_eth1_data_params,
                               sample_block_header_params):
    return {
        'slot': genesis_slot + 100,
        'genesis_time': 0,
        'fork': Fork(**sample_fork_params),
        'validator_registry': (),
        'validator_balances': (),
        'validator_registry_update_epoch': 0,
        'latest_randao_mixes': (),
        'previous_shuffling_start_shard': 1,
        'current_shuffling_start_shard': 2,
        'previous_shuffling_epoch': genesis_epoch,
        'current_shuffling_epoch': genesis_epoch,
        'previous_shuffling_seed': b'\x77' * 32,
        'current_shuffling_seed': b'\x88' * 32,
        'previous_epoch_attestations': (),
        'current_epoch_attestations': (),
        'previous_justified_epoch': 0,
        'current_justified_epoch': 0,
        'previous_justified_root': b'\x99' * 32,
        'current_justified_root': b'\x55' * 32,
        'justification_bitfield': 0,
        'finalized_epoch': 0,
        'finalized_root': b'\x33' * 32,
        'latest_crosslinks': (),
        'latest_block_roots': (),
        'latest_state_roots': (),
        'latest_active_index_roots': (),
        'latest_slashed_balances': (),
        'latest_block_header': BeaconBlockHeader(**sample_block_header_params),
        'historical_roots': (),
        'latest_eth1_data': Eth1Data(**sample_eth1_data_params),
        'eth1_data_votes': (),
        'deposit_index': 0,
    }