async def run(self) -> None: async with TrioEndpoint.serve(self._connection_config) as endpoint: self._endpoint = endpoint # signal that the endpoint is now available self._endpoint_available.set() # run background task that automatically connects to newly announced endpoints self.manager.run_daemon_task( _auto_connect_new_announced_endpoints, self._endpoint, self._new_available_endpoints(), self.logger, ) # connect to the *main* endpoint which communicates information # about other endpoints that come online. main_endpoint_config = ConnectionConfig.from_name( MAIN_EVENTBUS_ENDPOINT, self._trinity_config.ipc_dir) await endpoint.connect_to_endpoints(main_endpoint_config) # announce ourself to the event bus await endpoint.wait_until_endpoint_subscribed_to( MAIN_EVENTBUS_ENDPOINT, EventBusConnected) await endpoint.broadcast( EventBusConnected(self._connection_config), BroadcastConfig(filter_endpoint=MAIN_EVENTBUS_ENDPOINT), ) # run until the endpoint exits await self.manager.wait_finished()
async def run() -> None: socket = trio.socket.socket(family=trio.socket.AF_INET, type=trio.socket.SOCK_DGRAM) await socket.bind(('0.0.0.0', listen_port)) async with TrioEndpoint.serve( networking_connection_config) as endpoint: service = DiscoveryService(privkey, addr, bootstrap_nodes, endpoint, socket) await TrioManager.run_service(service)
async def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('-bootnode', type=str, help="The enode to use as bootnode") parser.add_argument('-networkid', type=int, choices=[ROPSTEN_NETWORK_ID, MAINNET_NETWORK_ID], default=ROPSTEN_NETWORK_ID, help="1 for mainnet, 3 for testnet") parser.add_argument('-l', type=str, help="Log level", default="info") args = parser.parse_args() logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%H:%M:%S') if args.l == "debug2": # noqa: E741 log_level = DEBUG2_LEVEL_NUM else: log_level = getattr(logging, args.l.upper()) logging.getLogger('p2p').setLevel(log_level) network_cfg = PRECONFIGURED_NETWORKS[args.networkid] # Listen on a port other than 30303 so that we can test against a local geth instance # running on that port. listen_port = 30304 # Use a hard-coded privkey so that our enode is always the same. privkey = keys.PrivateKey( b'~\x054{4\r\xd64\x0f\x98\x1e\x85;\xcc\x08\x1eQ\x10t\x16\xc0\xb0\x7f)=\xc4\x1b\xb7/\x8b&\x83' ) # noqa: E501 addr = kademlia.Address('127.0.0.1', listen_port, listen_port) if args.bootnode: bootstrap_nodes = tuple([kademlia.Node.from_uri(args.bootnode)]) else: bootstrap_nodes = tuple( kademlia.Node.from_uri(enode) for enode in network_cfg.bootnodes) ipc_path = Path(f"networking-{uuid.uuid4()}.ipc") networking_connection_config = ConnectionConfig( name=NETWORKING_EVENTBUS_ENDPOINT, path=ipc_path) headerdb = TrioHeaderDB(AtomicDB(MemoryDB())) headerdb.persist_header(network_cfg.genesis_header) vm_config = network_cfg.vm_configuration enr_field_providers = (functools.partial(generate_eth_cap_enr_field, vm_config, headerdb), ) socket = trio.socket.socket(family=trio.socket.AF_INET, type=trio.socket.SOCK_DGRAM) await socket.bind(('0.0.0.0', listen_port)) async with TrioEndpoint.serve(networking_connection_config) as endpoint: service = DiscoveryService(privkey, addr, bootstrap_nodes, endpoint, socket, enr_field_providers) service.logger.info("Enode: %s", service.this_node.uri()) async with background_trio_service(service): await service.manager.wait_finished()
async def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('--ipc', type=str, help="The path to UPnPService's IPC file") args = parser.parse_args() connection_config = ConnectionConfig(UPNP_EVENTBUS_ENDPOINT, args.ipc) async with TrioEndpoint(f"upnp-watcher-{uuid.uuid4()}").run() as client: with trio.fail_after(1): await client.connect_to_endpoints(connection_config) async for event in client.stream(UPnPMapping): external_ip = event.ip print("Got new UPnP mapping:", external_ip)
async def main() -> None: logging.basicConfig(level=logging.INFO, format='%(asctime)s %(levelname)s: %(message)s', datefmt='%H:%M:%S') logger = logging.getLogger() parser = argparse.ArgumentParser() parser.add_argument('--ipc', type=str, help="The path to DiscoveryService's IPC file") args = parser.parse_args() # XXX: This is an ugly hack, but it's the easiest way to ensure we use the same network as the # DiscoveryService instance we connect to. for n_id, network_cfg in PRECONFIGURED_NETWORKS.items(): if network_cfg.data_dir_name in args.ipc: network_id = n_id break else: raise AssertionError("Failed to detect network_id") logger.info( f"Asking DiscoveryService for peers on {network_cfg.chain_name}") connection_config = ConnectionConfig(DISCOVERY_EVENTBUS_ENDPOINT, args.ipc) network_cfg = PRECONFIGURED_NETWORKS[network_id] vm_config = network_cfg.vm_configuration fork_blocks = extract_fork_blocks(vm_config) MAX_PEERS = 260 skip_list: Set[NodeID] = set() async with TrioEndpoint(f"discv4-driver-{uuid.uuid4()}").run() as client: with trio.fail_after(2): await client.connect_to_endpoints(connection_config) await client.wait_until_any_endpoint_subscribed_to( PeerCandidatesRequest) while True: logger.info("Skip list has %d peers", len(skip_list)) should_skip = functools.partial( skip_candidate_if_on_list_or_fork_mismatch, network_cfg.genesis_header.hash, network_cfg.genesis_header.block_number, fork_blocks, skip_list, ) with trio.fail_after(1): response = await client.request( PeerCandidatesRequest(MAX_PEERS, should_skip)) candidates = response.candidates missing_forkid = [] for candidate in candidates: try: extract_forkid(candidate.enr) except ENRMissingForkID: missing_forkid.append(candidate.id) logger.info( "Got %d connection candidates, %d of those with a matching ForkID", len(candidates), len(candidates) - len(missing_forkid), ) # Add candidates with no forkid to the skip list, just so that we keep triggering # random discovery lookups and hopefully come across more candidates with # compatible forkids logger.info("Adding %d candidates with no ForkID to skip list", len(missing_forkid)) skip_list.update(missing_forkid) await trio.sleep(10)