# Buggy code
def get_external_ip_from_default_teacher(
    network: str,
    federated_only: bool = False,
    log: Logger = IP_DETECTION_LOGGER,
    registry: BaseContractRegistry = None,
) -> Union[str, None]:
    from nucypher.characters.lawful import Ursula

    if federated_only and registry:
        raise ValueError("Federated mode must not be true if registry is provided.")
    base_error = "Cannot determine IP using default teacher"
    try:
        top_teacher_url = RestMiddleware.TEACHER_NODES[network][0]
    except IndexError:
        log.debug(f'{base_error}: No teacher available for network "{network}".')
        return
    except KeyError:
        log.debug(f'{base_error}: Unknown network "{network}".')
        return

    ####
    # TODO: Clean this mess #1481
    node_storage = LocalFileBasedNodeStorage(federated_only=federated_only)
    Ursula.set_cert_storage_function(node_storage.store_node_certificate)
    Ursula.set_federated_mode(federated_only)
    #####

    teacher = Ursula.from_teacher_uri(
        teacher_uri=top_teacher_url, federated_only=federated_only, min_stake=0
    )  # TODO: Handle customized min stake here.

    # TODO: Pass registry here to verify stake (not essential here since it's a hardcoded node)
    client = NucypherMiddlewareClient()
    try:
        response = client.get(
            node_or_sprout=teacher, path=f"ping", timeout=2
        )  # TLS certificate logic within
    except RestMiddleware.UnexpectedResponse:
        # 404, 405, 500, All server response codes handled by will be caught here.
        return  # Default teacher does not support this request - just move on.
    if response.status_code == 200:
        try:
            ip = str(ip_address(response.text))
        except ValueError:
            error = f"Default teacher at {top_teacher_url} returned an invalid IP response; Got {response.text}"
            raise UnknownIPAddress(error)
        log.info(
            f"Fetched external IP address ({ip}) from default teacher ({top_teacher_url})."
        )
        return ip
    else:
        log.debug(
            f"Failed to get external IP from teacher node ({response.status_code})"
        )


# Traceback (ConnectionRefusedError)
Verbose mode is enabled
Authenticating Ursula
Qualifying worker
✓ Worker is bonded to 0x559A0408aAf3beAb55E80Bd5E2ea83D233f43F7d
✓ Worker is funded with 0.378943746597798709 ETH
Traceback (most recent call last):
File "/usr/lib/python3.8/site-packages/nucypher/characters/lawful.py", line 1466, in __attempt
teacher = cls.from_seed_and_stake_info(seed_uri=teacher_uri,
File "/usr/lib/python3.8/site-packages/nucypher/characters/lawful.py", line 1507, in from_seed_and_stake_info
certificate = network_middleware.get_certificate(host=host, port=port)
File "/usr/lib/python3.8/site-packages/nucypher/network/middleware.py", line 176, in get_certificate
seednode_certificate = ssl.get_server_certificate(addr=(host, port))
File "/usr/lib/python3.8/ssl.py", line 1483, in get_server_certificate
with  create_connection(addr) as sock:
File "/usr/lib/python3.8/socket.py", line 808, in create_connection
raise err
File "/usr/lib/python3.8/socket.py", line 796, in create_connection
sock.connect(sa)
ConnectionRefusedError: [Errno 111] Connection refused

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "/usr/bin/nucypher", line 8, in <module>
sys.exit(nucypher_cli())
File "/usr/lib/python3.8/site-packages/click/core.py", line 829, in __call__
return self.main(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/click/core.py", line 782, in main
rv = self.invoke(ctx)
File "/usr/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/lib/python3.8/site-packages/click/core.py", line 1259, in invoke
return _process_result(sub_ctx.command.invoke(sub_ctx))
File "/usr/lib/python3.8/site-packages/click/core.py", line 1066, in invoke
return ctx.invoke(self.callback, **ctx.params)
File "/usr/lib/python3.8/site-packages/click/core.py", line 610, in invoke
return callback(*args, **kwargs)
File "/usr/lib/python3.8/site-packages/nucypher/cli/options.py", line 169, in wrapper
return func(**kwargs)
File "/usr/lib/python3.8/site-packages/nucypher/cli/options.py", line 169, in wrapper
return func(**kwargs)
File "/usr/lib/python3.8/site-packages/nucypher/cli/options.py", line 169, in wrapper
return func(**kwargs)
File "/usr/lib/python3.8/site-packages/nucypher/cli/commands/ursula.py", line 390, in run
perform_startup_ip_check(emitter=emitter, ursula=URSULA, force=force)
File "/usr/lib/python3.8/site-packages/nucypher/cli/actions/configure.py", line 157, in perform_startup_ip_check
external_ip = determine_external_ip_address(network=ursula.domain, known_nodes=ursula.known_nodes)
File "/usr/lib/python3.8/site-packages/nucypher/utilities/networking.py", line 172, in determine_external_ip_address
rest_host = get_external_ip_from_default_teacher(network=network)
File "/usr/lib/python3.8/site-packages/nucypher/utilities/networking.py", line 105, in get_external_ip_from_default_teacher
teacher = Ursula.from_teacher_uri(teacher_uri=top_teacher_url,
File "/usr/lib/python3.8/site-packages/nucypher/characters/lawful.py", line 1481, in from_teacher_uri
return __attempt()
File "/usr/lib/python3.8/site-packages/nucypher/characters/lawful.py", line 1477, in __attempt
return __attempt(attempt=attempt + 1)
File "/usr/lib/python3.8/site-packages/nucypher/characters/lawful.py", line 1463, in __attempt
raise ConnectionRefusedError("Host {} Refused Connection".format(teacher_uri))
ConnectionRefusedError: Host https://mainnet.nucypher.network:9151 Refused Connection

# Fixed code
def get_external_ip_from_default_teacher(
    network: str,
    federated_only: bool = False,
    registry: Optional[BaseContractRegistry] = None,
    log: Logger = IP_DETECTION_LOGGER,
) -> Union[str, None]:
    # Prevents circular import
    from nucypher.characters.lawful import Ursula

    if federated_only and registry:
        raise ValueError("Federated mode must not be true if registry is provided.")
    base_error = "Cannot determine IP using default teacher"
    try:
        top_teacher_url = RestMiddleware.TEACHER_NODES[network][0]
    except IndexError:
        log.debug(f'{base_error}: No teacher available for network "{network}".')
        return
    except KeyError:
        log.debug(f'{base_error}: Unknown network "{network}".')
        return

    ####
    # TODO: Clean this mess #1481 (Federated Mode)
    node_storage = LocalFileBasedNodeStorage(federated_only=federated_only)
    Ursula.set_cert_storage_function(node_storage.store_node_certificate)
    Ursula.set_federated_mode(federated_only)
    #####

    try:
        teacher = Ursula.from_teacher_uri(
            teacher_uri=top_teacher_url, federated_only=federated_only, min_stake=0
        )  # TODO: Handle customized min stake here.
    except NodeSeemsToBeDown:
        # Teacher is unreachable.  Move on.
        return

    # TODO: Pass registry here to verify stake (not essential here since it's a hardcoded node)
    result = _request_from_node(teacher=teacher)
    return result