async def test_host_routing_success(): routers = await set_up_routers() transports = [["/ip4/127.0.0.1/tcp/0"], ["/ip4/127.0.0.1/tcp/0"]] transport_disc_opt_list = zip(transports, routers) (host_a, host_b ) = await set_up_nodes_by_transport_and_disc_opt(transport_disc_opt_list) # Set routing info await routers[0].server.set( host_a.get_id().xor_id, peer_info_to_str(PeerInfo(host_a.get_id(), host_a.get_addrs())), ) await routers[1].server.set( host_b.get_id().xor_id, peer_info_to_str(PeerInfo(host_b.get_id(), host_b.get_addrs())), ) # forces to use routing as no addrs are provided await host_a.connect(PeerInfo(host_b.get_id(), [])) await host_b.connect(PeerInfo(host_a.get_id(), [])) # Clean up await asyncio.gather(*[host_a.close(), host_b.close()]) routers[0].server.stop() routers[1].server.stop()
async def test_host_routing_fail(): routers = await set_up_routers() transports = [["/ip4/127.0.0.1/tcp/0"], ["/ip4/127.0.0.1/tcp/0"]] transport_disc_opt_list = zip(transports, routers) (host_a, host_b ) = await set_up_nodes_by_transport_and_disc_opt(transport_disc_opt_list) host_c = (await set_up_nodes_by_transport_opt([["/ip4/127.0.0.1/tcp/0"]]))[0] # Set routing info await routers[0].server.set( host_a.get_id().xor_id, peer_info_to_str(PeerInfo(host_a.get_id(), host_a.get_addrs())), ) await routers[1].server.set( host_b.get_id().xor_id, peer_info_to_str(PeerInfo(host_b.get_id(), host_b.get_addrs())), ) # routing fails because host_c does not use routing with pytest.raises(ConnectionFailure): await host_a.connect(PeerInfo(host_c.get_id(), [])) with pytest.raises(ConnectionFailure): await host_b.connect(PeerInfo(host_c.get_id(), [])) # Clean up await asyncio.gather(*[host_a.close(), host_b.close(), host_c.close()]) routers[0].server.stop() routers[1].server.stop()
async def test_host_routing_success(): host_a, host_b = await set_up_routed_hosts() # forces to use routing as no addrs are provided await host_a.connect(PeerInfo(host_b.get_id(), [])) await host_b.connect(PeerInfo(host_a.get_id(), [])) # Clean up await asyncio.gather(*[host_a.close(), host_b.close()])
async def test_host_routing_fail(): async with RoutedHostFactory.create_batch_and_listen( 2) as routed_hosts, HostFactory.create_batch_and_listen( 1) as basic_hosts: # routing fails because host_c does not use routing with pytest.raises(ConnectionFailure): await routed_hosts[0].connect(PeerInfo(basic_hosts[0].get_id(), [])) with pytest.raises(ConnectionFailure): await routed_hosts[1].connect(PeerInfo(basic_hosts[0].get_id(), []))
async def ConnectionPairFactory( alice_chaindb: AsyncBeaconChainDB = None, bob_chaindb: AsyncBeaconChainDB = None, cancel_token: CancelToken = None, handshake: bool = True, ) -> AsyncIterator[Tuple[Node, Node]]: if cancel_token is None: cancel_token = CancelTokenFactory() alice_kwargs = {} bob_kwargs = {} if alice_chaindb is not None: alice_kwargs["chain__db"] = alice_chaindb.db if bob_chaindb is not None: bob_kwargs["chain__db"] = bob_chaindb.db alice = NodeFactory(cancel_token=cancel_token, **alice_kwargs) bob = NodeFactory(cancel_token=cancel_token, **bob_kwargs) async with run_service(alice), run_service(bob): await asyncio.sleep(0.01) await alice.host.connect( PeerInfo( peer_id=bob.peer_id, addrs=[bob.listen_maddr], )) await asyncio.sleep(0.01) if handshake: await alice.request_status(bob.peer_id) await asyncio.sleep(0.01) yield alice, bob
async def test_host_routing_fail(): host_a, host_b = await set_up_routed_hosts() basic_host_c = (await set_up_nodes_by_transport_opt([["/ip4/127.0.0.1/tcp/0"]] ))[0] # routing fails because host_c does not use routing with pytest.raises(ConnectionFailure): await host_a.connect(PeerInfo(basic_host_c.get_id(), [])) with pytest.raises(ConnectionFailure): await host_b.connect(PeerInfo(basic_host_c.get_id(), [])) # Clean up await asyncio.gather( *[host_a.close(), host_b.close(), basic_host_c.close()])
async def set_up_routed_hosts() -> Tuple[RoutedHost, RoutedHost]: router_a, router_b = DummyRouter(), DummyRouter() transport = "/ip4/127.0.0.1/tcp/0" host_a = await new_node(transport_opt=[transport], disc_opt=router_a) host_b = await new_node(transport_opt=[transport], disc_opt=router_b) address = multiaddr.Multiaddr(transport) await host_a.get_network().listen(address) await host_b.get_network().listen(address) mock_routing_table = { host_a.get_id(): PeerInfo(host_a.get_id(), host_a.get_addrs()), host_b.get_id(): PeerInfo(host_b.get_id(), host_b.get_addrs()), } router_a._routing_table = router_b._routing_table = mock_routing_table return cast(RoutedHost, host_a), cast(RoutedHost, host_b)
def decode_peerinfo(encoded): if isinstance(encoded, bytes): encoded = encoded.decode() lines = encoded.splitlines() peer_id = lines[0] addrs = lines[1:] peer_data = PeerData() peer_data.add_addrs(addrs) return PeerInfo(peer_id, addrs)
async def dial_peer(self, ip: str, port: int, peer_id: ID) -> None: """ Dial the peer ``peer_id`` through the IPv4 protocol """ await self.host.connect( PeerInfo( peer_id=peer_id, addrs=[make_tcp_ip_maddr(ip, port)], ))
def test_init_(): random_addrs = [random.randint(0, 255) for r in range(4)] random_id_string = "" for _ in range(10): random_id_string += random.SystemRandom().choice(ALPHABETS) peer_id = ID(random_id_string.encode()) peer_info = PeerInfo(peer_id, random_addrs) assert peer_info.peer_id == peer_id assert peer_info.addrs == random_addrs
def _get_peer_info(node: TDaemonOrHost) -> PeerInfo: peer_info: PeerInfo if isinstance(node, Daemon): peer_info = node.peer_info else: # isinstance(node, IHost) peer_id = node.get_id() maddrs = [ node.get_addrs()[0].decapsulate( Multiaddr(f"/p2p/{peer_id.to_string()}")) ] peer_info = PeerInfo(peer_id, maddrs) return peer_info
def test_init_(): peer_data = PeerData() random_addrs = [random.randint(0, 255) for r in range(4)] peer_data.add_addrs(random_addrs) random_id_string = '' for _ in range(10): random_id_string += random.SystemRandom().choice(ALPHABETS) peer_id = ID(random_id_string) peer_info = PeerInfo(peer_id, peer_data) assert peer_info.peer_id == peer_id assert peer_info.addrs == random_addrs
async def dial_peer(self, ip: str, port: int, peer_id: ID) -> None: """ Dial the peer ``peer_id`` through the IPv4 protocol """ await self.host.connect( PeerInfo( peer_id=peer_id, addrs=[make_tcp_ip_maddr(ip, port)], )) try: # TODO: set a time limit on completing saying hello await self.say_hello(peer_id) except HandshakeFailure as e: self.logger.info("HandshakeFailure: %s", str(e))
async def add_peer_from_maddr(self, maddr: Multiaddr) -> None: """ Connect to the eth2 peer at ``maddr`` and incorporate them into our view of the network. """ peer_id_encoded = maddr.value_for_protocol("p2p") peer_id = PeerID.from_base58(peer_id_encoded) try: await self.connect(PeerInfo(peer_id=peer_id, addrs=[maddr])) local_status = self._status_provider() remote_status = await self.exchange_status(peer_id, local_status) if self._peer_is_compatible(local_status, remote_status): self._peers.add(peer_id) await self._peer_updater(peer_id, remote_status) else: await self.disconnect(peer_id) except Exception as e: self.logger.exception(e)
async def dial_peer(self, ip: str, port: int, peer_id: ID) -> None: """ Dial the peer ``peer_id`` through the IPv4 protocol """ try: maddr = make_tcp_ip_maddr(ip, port) self.logger.debug("Dialing peer_id %s maddr %s", peer_id, maddr) await self.host.connect(PeerInfo( peer_id=peer_id, addrs=[maddr], )) except Exception as e: raise ConnectionRefusedError() from e try: # TODO: set a time limit on completing handshake await self.request_status(peer_id) except HandshakeFailure as e: self.logger.info("HandshakeFailure: %s", str(e)) raise ConnectionRefusedError() from e
async def ConnectionPairFactory( alice_chaindb: AsyncBeaconChainDB = None, alice_branch: Collection[BaseSignedBeaconBlock] = None, bob_chaindb: AsyncBeaconChainDB = None, bob_branch: Collection[BaseSignedBeaconBlock] = None, genesis_state: BeaconState = None, alice_event_bus: EndpointAPI = None, cancel_token: CancelToken = None, handshake: bool = True, ) -> AsyncIterator[Tuple[Node, Node]]: if cancel_token is None: cancel_token = CancelTokenFactory() alice_kwargs: Dict[str, Any] = {} bob_kwargs: Dict[str, Any] = {} if alice_chaindb is not None: alice_kwargs["chain__db"] = alice_chaindb.db if alice_branch is not None: alice_kwargs["chain__branch"] = alice_branch if bob_chaindb is not None: bob_kwargs["chain__db"] = bob_chaindb.db if bob_branch is not None: bob_kwargs["chain__branch"] = bob_branch if genesis_state is not None: alice_kwargs["chain__genesis_state"] = genesis_state bob_kwargs["chain__genesis_state"] = genesis_state alice = NodeFactory( cancel_token=cancel_token, event_bus=alice_event_bus, **alice_kwargs ) bob = NodeFactory(cancel_token=cancel_token, **bob_kwargs) async with run_service(alice), run_service(bob): await asyncio.sleep(0.01) await alice.host.connect( PeerInfo(peer_id=bob.peer_id, addrs=[bob.listen_maddr]) ) await asyncio.sleep(0.01) if handshake: await alice.request_status(bob.peer_id) await asyncio.sleep(0.01) yield alice, bob
async def dial_peer_maddr(self, maddr: Multiaddr, peer_id: ID) -> None: """ Dial the peer with given multi-address """ self.logger.debug("Dialing peer_id: %s, maddr: %s", peer_id, maddr) try: await self.host.connect( PeerInfo( peer_id=peer_id, addrs=[maddr], ) ) except SwarmException as e: self.logger.debug("Fail to dial peer_id: %s, maddr: %s, error: %s", peer_id, maddr, e) raise DialPeerError from e try: # TODO: set a time limit on completing handshake await self.request_status(peer_id) except HandshakeFailure as e: self.logger.debug("Fail to handshake with peer_id: %s, error: %s", peer_id, e) raise DialPeerError from e self.logger.debug("Successfully connect to peer_id %s maddr %s", peer_id, maddr)
async def test_host_routing_success(): async with RoutedHostFactory.create_batch_and_listen(2) as hosts: # forces to use routing as no addrs are provided await hosts[0].connect(PeerInfo(hosts[1].get_id(), [])) await hosts[1].connect(PeerInfo(hosts[0].get_id(), []))
def test_init_no_value(): with pytest.raises(Exception) as _: #pylint: disable=no-value-for-parameter PeerInfo()
def peer_info_from_str(string: str) -> PeerInfo: peer_id, raw_addrs = json.loads(string) return PeerInfo(ID.from_base58(peer_id), list(map(lambda a: multiaddr.Multiaddr(a), raw_addrs)))
def _add_peer(self, peer_id: ID, addrs: List[Multiaddr]) -> None: self._routing_table[peer_id] = PeerInfo(peer_id, addrs)