# Buggy code
def get_uniformed_tracker_url(tracker_url):
    """
    Parse a tracker url of string_types type.

    The following checks and transformations are applied to the url:
        - Check if the url is valid unicode data
        - Strip whitespaces
        - Strip a trailing '/'
        - Check that the port is
            - provided in case of UDP
            - in range in case of HTTP (implicitly done in the `urlparse` function)
        - If it is a url for a HTTP tracker, don't include the default port HTTP_PORT

    Examples:
        udp://tracker.openbittorrent.com:80
        http://tracker.openbittorrent.com:80/announce

    :param tracker_url: a string_types url for either a UDP or HTTP tracker
    :return: the tracker in a uniform format <type>://<host>:<port>/<page>
    """
    assert isinstance(tracker_url, string_types), (
        "tracker_url is not a string_types: %s" % type(tracker_url)
    )

    # check if the URL is valid unicode data
    try:
        tracker_url = text_type(tracker_url)
    except UnicodeDecodeError:
        return None

    # Search the string for delimiters and try to get the first correct URL
    for tracker_url in re.split(delimiters_regex, tracker_url):
        # Rule out truncated URLs
        if re.search(truncated_url_detector, tracker_url):
            continue
        # Try to match it against a simple regexp
        if not re.match(url_regex, tracker_url):
            continue

        tracker_url = re.sub(remove_trailing_junk, "", tracker_url)
        url = urlparse(tracker_url)

        # accessing urlparse attributes may throw UnicodeError's or ValueError's
        try:
            # scheme must be either UDP or HTTP
            if url.scheme == "udp" or url.scheme == "http":
                uniformed_scheme = url.scheme
            else:
                continue

            uniformed_hostname = url.hostname

            if not url.port:
                # UDP trackers must have a port
                if url.scheme == "udp":
                    continue
                # HTTP trackers default to port HTTP_PORT
                elif url.scheme == "http":
                    uniformed_port = HTTP_PORT
            else:
                uniformed_port = url.port

            # UDP trackers have no path
            if url.scheme == "udp":
                uniformed_path = ""
            else:
                uniformed_path = url.path.rstrip("/")
            # HTTP trackers must have a path
            if url.scheme == "http" and not uniformed_path:
                continue

            if url.scheme == "http" and uniformed_port == HTTP_PORT:
                uniformed_url = "%s://%s%s" % (
                    uniformed_scheme,
                    uniformed_hostname,
                    uniformed_path,
                )
            else:
                uniformed_url = "%s://%s:%d%s" % (
                    uniformed_scheme,
                    uniformed_hostname,
                    uniformed_port,
                    uniformed_path,
                )
        except ValueError:
            continue
        else:
            return uniformed_url
    return None


# Traceback (InvalidSignatureException)
INFO    1558196143.11              db72_to_pony:335  (TriblerUpgrader)  Converted old torrents: 151830/152780 0.906724
INFO    1558196155.05              db72_to_pony:335  (TriblerUpgrader)  Converted old torrents: 152566/152780 1.287935
INFO    1558196165.47              db72_to_pony:335  (TriblerUpgrader)  Converted old torrents: 153515/152780 0.001943
INFO    1558196169.26           tracker_manager:40   (TrackerManager)  No tracker blacklist file found at /home/user/.Tribler/tracker_blacklist.txt.
ERROR   1558196169.26            LaunchManyCore:271  (TriblerLaunchMany)  bitcoinlib library cannot be loaded: No module named bitcoinlib.wallets
INFO    1558196169.31                 community:120  (DHTDiscoveryCommunity)  DHT community initialized (peer mid dbd693da46e85248d040ad7559373864663a0573)
INFO    1558196169.33          order_repository:122  (DatabaseOrderRepository)  Memory order repository used
INFO    1558196169.33    transaction_repository:123  (DatabaseTransactionRepository)  Database transaction repository used
INFO    1558196169.33             order_manager:18   (OrderManager)  Market order manager initialized
INFO    1558196169.33       transaction_manager:20   (TransactionManager)  Transaction manager initialized
INFO    1558196169.33                 community:207  (MarketCommunity)  Market community initialized with mid dbd693da46e85248d040ad7559373864663a0573
INFO    1558196169.53            LaunchManyCore:623  (TriblerLaunchMany)  tlm: not resuming checkpoint because download has already been added
INFO    1558196169.54     event_request_manager:132  (TriblerGUI)  Will connect to events endpoint
WARNING 1558196169.71            tribler_window:348  (root)  Received duplicate Tribler Core started event
ERROR   1558196171.35              ipv8_service:144  (root)  Exception occurred while trying to walk!
Traceback (most recent call last):
File "/usr/share/tribler/Tribler/pyipv8/ipv8_service.py", line 141, in on_tick
strategy.take_step()
File "/usr/share/tribler/Tribler/community/gigachannel/sync_strategy.py", line 19, in take_step
self.overlay.send_random_to(peer)
File "/usr/share/tribler/Tribler/community/gigachannel/community.py", line 77, in send_random_to
blob = entries_to_chunk(md_list, maximum_payload_size)[0] if md_list else None
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/channel_metadata.py", line 71, in entries_to_chunk
''.join(metadata.serialized_delete() if metadata.status == TODELETE else metadata.serialized()))
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/channel_node.py", line 140, in serialized
return ''.join(self._serialized(key))
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/channel_node.py", line 132, in _serialized
return self._payload_class(key=key, **self.to_dict())._serialized()
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 265, in __init__
**kwargs)
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 210, in __init__
**kwargs)
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 165, in __init__
**kwargs)
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 105, in __init__
raise InvalidSignatureException("Tried to create payload with wrong signature")
InvalidSignatureException: <class 'Tribler.Core.exceptions.InvalidSignatureException'>: Tried to create payload with wrong signature

ERROR   1558196171.85              ipv8_service:144  (root)  Exception occurred while trying to walk!
Traceback (most recent call last):
File "/usr/share/tribler/Tribler/pyipv8/ipv8_service.py", line 141, in on_tick
strategy.take_step()
File "/usr/share/tribler/Tribler/community/gigachannel/sync_strategy.py", line 19, in take_step
self.overlay.send_random_to(peer)
File "/usr/share/tribler/Tribler/community/gigachannel/community.py", line 77, in send_random_to
blob = entries_to_chunk(md_list, maximum_payload_size)[0] if md_list else None
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/channel_metadata.py", line 71, in entries_to_chunk
''.join(metadata.serialized_delete() if metadata.status == TODELETE else metadata.serialized()))
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/channel_node.py", line 140, in serialized
return ''.join(self._serialized(key))
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/OrmBindings/channel_node.py", line 132, in _serialized
return self._payload_class(key=key, **self.to_dict())._serialized()
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 265, in __init__
**kwargs)
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 210, in __init__
**kwargs)
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 165, in __init__
**kwargs)
File "/usr/share/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 105, in __init__
raise InvalidSignatureException("Tried to create payload with wrong signature")
InvalidSignatureException: <class 'Tribler.Core.exceptions.InvalidSignatureException'>: Tried to create payload with wrong signature

# Fixed code
def get_uniformed_tracker_url(tracker_url):
    """
    Parse a tracker url of string_types type.

    The following checks and transformations are applied to the url:
        - Check if the url is valid unicode data
        - Strip whitespaces
        - Strip a trailing '/'
        - Check that the port is
            - provided in case of UDP
            - in range in case of HTTP (implicitly done in the `urlparse` function)
        - If it is a url for a HTTP tracker, don't include the default port HTTP_PORT

    Examples:
        udp://tracker.openbittorrent.com:80
        http://tracker.openbittorrent.com:80/announce

    :param tracker_url: a string_types url for either a UDP or HTTP tracker
    :return: the tracker in a uniform format <type>://<host>:<port>/<page>
    """
    assert isinstance(tracker_url, string_types), (
        "tracker_url is not a string_types: %s" % type(tracker_url)
    )

    # check if the URL is valid unicode data
    try:
        tracker_url = text_type(tracker_url)
    except UnicodeDecodeError:
        return None

    # Search the string for delimiters and try to get the first correct URL
    for tracker_url in re.split(delimiters_regex, tracker_url):
        # Rule out the case where the regex returns None
        if not tracker_url:
            continue
        # Rule out truncated URLs
        if re.search(truncated_url_detector, tracker_url):
            continue
        # Try to match it against a simple regexp
        if not re.match(url_regex, tracker_url):
            continue

        tracker_url = re.sub(remove_trailing_junk, "", tracker_url)
        url = urlparse(tracker_url)

        # accessing urlparse attributes may throw UnicodeError's or ValueError's
        try:
            # scheme must be either UDP or HTTP
            if url.scheme == "udp" or url.scheme == "http":
                uniformed_scheme = url.scheme
            else:
                continue

            uniformed_hostname = url.hostname

            if not url.port:
                # UDP trackers must have a port
                if url.scheme == "udp":
                    continue
                # HTTP trackers default to port HTTP_PORT
                elif url.scheme == "http":
                    uniformed_port = HTTP_PORT
            else:
                uniformed_port = url.port

            # UDP trackers have no path
            if url.scheme == "udp":
                uniformed_path = ""
            else:
                uniformed_path = url.path.rstrip("/")
            # HTTP trackers must have a path
            if url.scheme == "http" and not uniformed_path:
                continue

            if url.scheme == "http" and uniformed_port == HTTP_PORT:
                uniformed_url = "%s://%s%s" % (
                    uniformed_scheme,
                    uniformed_hostname,
                    uniformed_path,
                )
            else:
                uniformed_url = "%s://%s:%d%s" % (
                    uniformed_scheme,
                    uniformed_hostname,
                    uniformed_port,
                    uniformed_path,
                )
        except ValueError:
            continue
        else:
            return uniformed_url
    return None