Exemple #1
0
async def get_fake_chain() -> FakeChain:
    genesis_config = Eth2GenesisConfig(MINIMAL_SERENITY_CONFIG)
    chain_db = AsyncBeaconChainDBFactory(genesis_config=genesis_config)
    genesis_block = SignedBeaconBlockFactory()
    chain_db.persist_block(genesis_block, SerenitySignedBeaconBlock,
                           HigherSlotScoring())
    return FakeChain(base_db=chain_db.db, genesis_config=genesis_config)
Exemple #2
0
    def genesis_config(self) -> Eth2GenesisConfig:
        if self._genesis_config is None:
            self._genesis_config = Eth2GenesisConfig(
                self.beacon_chain_class.get_genesis_state_machine_class().config,
            )

        return self._genesis_config
Exemple #3
0
async def get_fake_chain() -> FakeChain:
    genesis_config = Eth2GenesisConfig(XIAO_LONG_BAO_CONFIG)
    chain_db = await bcc_helpers.get_genesis_chain_db(
        genesis_config=genesis_config)
    return FakeChain(base_db=chain_db.db,
                     attestation_pool=TempPool(),
                     genesis_config=genesis_config)
Exemple #4
0
 def _create(cls, model_class: Type[TestnetChain], *args: Any,
             **kwargs: Any) -> BaseBeaconChain:
     return model_class.from_genesis(
         base_db=AtomicDB(),
         genesis_state=genesis_state,
         genesis_block=genesis_block,
         genesis_config=Eth2GenesisConfig(
             model_class.get_genesis_state_machine_class().config),
     )
Exemple #5
0
    def genesis_config(self) -> Eth2GenesisConfig:
        """
        NOTE: this ``genesis_config`` is derivative of the ``Eth2Config``.
        TODO:(ralexstokes) patch up the names here...
        """
        if self._genesis_config is None:
            self._genesis_config = Eth2GenesisConfig(self._eth2_config)

        return self._genesis_config
Exemple #6
0
    def _create(cls, model_class: Type[BaseBeaconChain], *args: Any,
                **kwargs: Any) -> BaseBeaconChain:
        """
        Create a BeaconChain according to the factory definition.

        NOTE: clients of this class may provide a ``branch`` keyword in the ``kwargs`` to
        construct a chain with a ``Collection[BaseBeaconBlock]``. This ``branch`` is NOT
        assumed to have been constructed according to the full set of validity rules, e.g.
        lacking a proper signature so the ``perform_validation`` option to ``import_block``
        is disabled.
        """
        override_lengths(cls.config)
        if "num_validators" in kwargs:
            num_validators = kwargs["num_validators"]
        else:
            num_validators = cls.num_validators

        if kwargs["genesis_state"] is None:
            keymap = mk_keymap_of_size(num_validators)
            genesis_state, genesis_block = create_mock_genesis(
                config=cls.config,
                pubkeys=tuple(keymap.keys()),
                keymap=keymap,
                genesis_block_class=SerenityBeaconBlock,
                genesis_time=Timestamp(int(time.time())),
            )
        elif kwargs["genesis_block"] is None:
            genesis_state = kwargs["genesis_state"]
            genesis_block = get_genesis_block(genesis_state.hash_tree_root,
                                              SerenityBeaconBlock)
        else:
            genesis_state = kwargs["genesis_state"]
            genesis_block = kwargs["genesis_block"]

        db = kwargs.pop("db", AtomicDB())
        genesis_config = Eth2GenesisConfig(
            model_class.get_genesis_state_machine_class().config)
        chain = model_class.from_genesis(
            base_db=db,
            genesis_state=genesis_state,
            genesis_block=genesis_block,
            genesis_config=genesis_config,
        )

        if kwargs["branch"] is not None:
            branch = kwargs["branch"]
            for block in branch:
                if block.is_genesis:
                    continue
                # NOTE: ideally we use the ``import_block`` method
                # on ``chain`` but for the time being we skip some
                # validation corresponding to assumptions made in clients of
                # this class. A future refactoring should use the external API.
                chain.chaindb.persist_block(block, SerenityBeaconBlock,
                                            HigherSlotScoring())

        return chain
Exemple #7
0
async def test_json_rpc_http_server(aiohttp_raw_server, aiohttp_client,
                                    event_bus, base_db, ipc_path):
    manager = DBManager(base_db)
    with manager.run(ipc_path):
        # Set chaindb
        override_lengths(SERENITY_CONFIG)
        db = DBClient.connect(ipc_path)
        genesis_config = Eth2GenesisConfig(SERENITY_CONFIG)
        chaindb = AsyncBeaconChainDB(db, genesis_config)

        fork_choice_scoring = HigherSlotScoring()
        genesis_state, genesis_block = create_mock_genesis(
            pubkeys=(),
            config=SERENITY_CONFIG,
            keymap=dict(),
            genesis_block_class=BeaconBlock,
            genesis_time=0,
        )

        chaindb.persist_state(genesis_state)
        chaindb.persist_block(
            SignedBeaconBlock.create(message=genesis_block),
            SignedBeaconBlock,
            fork_choice_scoring,
        )
        try:
            rpc = RPCServer(initialize_beacon_modules(chaindb, event_bus),
                            chaindb, event_bus)
            raw_server = await aiohttp_raw_server(
                RPCHandler.handle(rpc.execute))
            client = await aiohttp_client(raw_server)

            request_id = 1
            request_data = {
                "jsonrpc": "2.0",
                "method": "beacon_head",
                "params": [],
                "id": request_id,
            }

            response = await client.post("/", json=request_data)
            response_data = await response.json()

            assert response_data["id"] == request_id
            result = response_data["result"]
            assert result["slot"] == 0
            assert decode_hex(
                result["block_root"]) == genesis_block.hash_tree_root
            assert decode_hex(
                result["state_root"]) == genesis_state.hash_tree_root
        except KeyboardInterrupt:
            pass
        finally:
            await raw_server.close()
            db.close()
Exemple #8
0
def execute_state_transtion(test_case, base_db):
    bls.use_noop_backend()
    dict_config = test_case['config']
    verify_signatures = test_case['verify_signatures']
    dict_initial_state = test_case['initial_state']
    dict_blocks = test_case['blocks']
    dict_expected_state = test_case['expected_state']

    # TODO: make it case by case
    assert verify_signatures is False

    # Set config
    config = generate_config_by_dict(dict_config)

    # Set Vector fields
    override_vector_lengths(config)

    # Set pre_state
    pre_state = from_formatted_dict(dict_initial_state, BeaconState)

    # Set blocks
    blocks = ()
    for dict_block in dict_blocks:
        block = from_formatted_dict(dict_block, SerenityBeaconBlock)
        blocks += (block, )

    sm_class = SerenityStateMachine.configure(
        __name__='SerenityStateMachineForTesting',
        config=config,
    )
    chaindb = BeaconChainDB(base_db, Eth2GenesisConfig(config))
    attestation_pool = AttestationPool()

    post_state = pre_state.copy()
    for block in blocks:
        sm = sm_class(chaindb, attestation_pool, None, post_state)
        post_state, _ = sm.import_block(block)

    # Use dict diff, easier to see the diff
    dict_post_state = to_formatted_dict(post_state, BeaconState)

    for key, value in dict_expected_state.items():
        if isinstance(value, list):
            value = tuple(value)
        assert dict_post_state[key] == value
Exemple #9
0
    def _create(cls, model_class: Type[BaseBeaconChain], *args: Any,
                **kwargs: Any) -> BaseBeaconChain:
        override_lengths(cls.config)

        keymap = mk_keymap_of_size(cls.num_validators)

        genesis_state, genesis_block = create_mock_genesis(
            config=cls.config,
            pubkeys=tuple(keymap.keys()),
            keymap=keymap,
            genesis_block_class=SerenityBeaconBlock,
            genesis_time=Timestamp(int(time.time())),
        )

        db = kwargs.pop("db", AtomicDB())
        chain = model_class.from_genesis(
            base_db=db,
            genesis_state=genesis_state,
            genesis_block=genesis_block,
            genesis_config=Eth2GenesisConfig(
                model_class.get_genesis_state_machine_class().config),
        )

        return chain
Exemple #10
0
def genesis_config(config):
    return Eth2GenesisConfig(config)
Exemple #11
0
from trinity.db.beacon.chain import AsyncBeaconChainDB

from trinity.protocol.bcc_libp2p.node import Node, PeerPool, Peer
from trinity.protocol.bcc_libp2p.servers import BCCReceiveServer
from trinity.sync.beacon.chain import BeaconChainSyncer

from .factories import (
    AtomicDBFactory, )

try:
    import factory
except ImportError:
    raise ImportError(
        "The p2p.tools.factories module requires the `factory_boy` library.")

SERENITY_GENESIS_CONFIG = Eth2GenesisConfig(SERENITY_CONFIG)

#
# LibP2P
#


class NodeFactory(factory.Factory):
    class Meta:
        model = Node

    key_pair = factory.LazyFunction(create_new_key_pair)
    listen_ip = "127.0.0.1"
    listen_port = factory.LazyFunction(get_open_port)
    security_protocol_ops = None
    muxer_protocol_ops = None
async def get_fake_chain() -> FakeChain:
    genesis_config = Eth2GenesisConfig(XIAO_LONG_BAO_CONFIG)
    chain_db = AsyncBeaconChainDBFactory(genesis_config=genesis_config)
    return FakeChain(base_db=chain_db.db,
                     attestation_pool=TempPool(),
                     genesis_config=genesis_config)
Exemple #13
0
def get_chaindb_of_config(base_db, config):
    return BeaconChainDB(base_db, Eth2GenesisConfig(config))
async def get_fake_chain() -> FakeChain:
    genesis_config = Eth2GenesisConfig(MINIMAL_SERENITY_CONFIG)
    chain_db = AsyncBeaconChainDBFactory(genesis_config=genesis_config)
    return FakeChain(base_db=chain_db.db, genesis_config=genesis_config)
Exemple #15
0
async def get_fake_chain() -> FakeChain:
    genesis_config = Eth2GenesisConfig(XIAO_LONG_BAO_CONFIG)
    chain_db = await helpers.get_genesis_chain_db(genesis_config=genesis_config
                                                  )
    return FakeChain(base_db=chain_db.db, genesis_config=genesis_config)