# Buggy code
def render_PUT(self, request):
    """
    .. http:put:: /downloads

    A PUT request to this endpoint will start a download from a provided URI. This URI can either represent a file
    location, a magnet link or a HTTP(S) url.
    - anon_hops: the number of hops for the anonymous download. 0 hops is equivalent to a plain download
    - safe_seeding: whether the seeding of the download should be anonymous or not (0 = off, 1 = on)
    - destination: the download destination path of the torrent
    - torrent: the URI of the torrent file that should be downloaded. This parameter is required.

        **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/downloads
                --data "anon_hops=2&safe_seeding=1&destination=/my/dest/on/disk/&uri=file:/home/me/test.torrent

        **Example response**:

            .. sourcecode:: javascript

                {"started": True, "infohash": "4344503b7e797ebf31582327a5baae35b11bda01"}
    """
    parameters = http.parse_qs(request.content.read(), 1)

    if "uri" not in parameters or len(parameters["uri"]) == 0:
        request.setResponseCode(http.BAD_REQUEST)
        return json.twisted_dumps({"error": "uri parameter missing"})

    download_config, error = DownloadsEndpoint.create_dconfig_from_params(parameters)
    if error:
        request.setResponseCode(http.BAD_REQUEST)
        return json.twisted_dumps({"error": error})

    def download_added(download):
        request.write(
            json.twisted_dumps(
                {
                    "started": True,
                    "infohash": hexlify(download.get_def().get_infohash()),
                }
            )
        )
        request.finish()

    def on_error(error):
        request.setResponseCode(http.INTERNAL_SERVER_ERROR)
        request.write(
            json.twisted_dumps({"error": unichar_string(error.getErrorMessage())})
        )
        request.finish()

    uri = ensure_unicode(parameters["uri"][0], "utf-8")
    if uri.startswith("file:"):
        filename = url2pathname(uri[5:])
        if uri.endswith(".mdblob"):
            try:
                payload = ChannelMetadataPayload.from_file(filename)
            except IOError:
                request.setResponseCode(http.BAD_REQUEST)
                return json.twisted_dumps({"error": "file not found"})
            except InvalidSignatureException:
                request.setResponseCode(http.BAD_REQUEST)
                return json.twisted_dumps({"error": "Metadata has invalid signature"})

            with db_session:
                result = self.session.lm.mds.process_payload(payload)
                if result:
                    node, status = result[0]
                    if status == UNKNOWN_CHANNEL or (
                        status == UPDATED_OUR_VERSION
                        and node.metadata_type == CHANNEL_TORRENT
                    ):
                        node.subscribed = True
                        return json.twisted_dumps(
                            {"started": True, "infohash": hexlify(node.infohash)}
                        )
                return json.twisted_dumps({"error": "Already subscribed"})
        else:
            download_uri = "file:%s" % filename
    else:
        download_uri = unquote_plus(uri)
    download_deferred = self.session.start_download_from_uri(
        download_uri, download_config
    )
    download_deferred.addCallback(download_added)
    download_deferred.addErrback(on_error)

    return NOT_DONE_YET


# Traceback (PackError)
ERROR   1562070054.96              rest_manager:83   (RESTRequest)  [Failure instance: Traceback: <class 'ipv8.messaging.serialization.PackError'>: Could not pack item 9: varlenI
error: unpack_from requires a buffer of at least 1869967971 bytes
/home/tribler/.local/lib/python2.7/site-packages/twisted/web/http.py:2121:_finishRequestBody
/home/tribler/.local/lib/python2.7/site-packages/twisted/web/http.py:2196:allContentReceived
/home/tribler/.local/lib/python2.7/site-packages/twisted/web/http.py:920:requestReceived
/home/tribler/tudelft/tribler/Tribler/Core/Modules/restapi/rest_manager.py:118:process
--- <exception caught here> ---
/home/tribler/.local/lib/python2.7/site-packages/twisted/web/server.py:199:process
/home/tribler/.local/lib/python2.7/site-packages/twisted/web/server.py:259:render
/home/tribler/.local/lib/python2.7/site-packages/twisted/web/resource.py:250:render
/home/tribler/tudelft/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py:347:render_PUT
/home/tribler/tudelft/tribler/Tribler/Core/Modules/MetadataStore/serialization.py:166:from_file
/home/tribler/tudelft/tribler/Tribler/Core/Modules/MetadataStore/serialization.py:135:from_signed_blob
/home/tribler/tudelft/tribler/Tribler/Core/Modules/MetadataStore/serialization.py:140:from_signed_blob_with_offset
/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py:328:unpack_multiple
/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py:320:unpack_multiple
/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py:297:unpack
/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py:160:unpack_from
]
Traceback (most recent call last):
File "/home/tribler/.local/lib/python2.7/site-packages/twisted/web/server.py", line 199, in process
self.render(resrc)
File "/home/tribler/.local/lib/python2.7/site-packages/twisted/web/server.py", line 259, in render
body = resrc.render(self)
File "/home/tribler/.local/lib/python2.7/site-packages/twisted/web/resource.py", line 250, in render
return m(request)
File "/home/tribler/tudelft/tribler/Tribler/Core/Modules/restapi/downloads_endpoint.py", line 347, in render_PUT
payload = ChannelMetadataPayload.from_file(filename)
File "/home/tribler/tudelft/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 166, in from_file
return cls.from_signed_blob(f.read())
File "/home/tribler/tudelft/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 135, in from_signed_blob
return cls.from_signed_blob_with_offset(data, check_signature)[0]
File "/home/tribler/tudelft/tribler/Tribler/Core/Modules/MetadataStore/serialization.py", line 140, in from_signed_blob_with_offset
unpack_list, end_offset = default_serializer.unpack_multiple(cls.format_list, data, offset=offset)
File "/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 328, in unpack_multiple
sys.exc_info()[2])
File "/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 320, in unpack_multiple
unpacked, unpacked_size = self.unpack(format, data, current_offset)
File "/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 297, in unpack
return self._packers[format].unpack_from(data, offset)
File "/home/tribler/tudelft/tribler/Tribler/pyipv8/ipv8/messaging/serialization.py", line 160, in unpack_from
out, = unpack_from('>%ds' % length, data, offset + self.format_size)
PackError: Could not pack item 9: varlenI
error: unpack_from requires a buffer of at least 1869967971 bytes

# Fixed code
def render_PUT(self, request):
    """
    .. http:put:: /downloads

    A PUT request to this endpoint will start a download from a provided URI. This URI can either represent a file
    location, a magnet link or a HTTP(S) url.
    - anon_hops: the number of hops for the anonymous download. 0 hops is equivalent to a plain download
    - safe_seeding: whether the seeding of the download should be anonymous or not (0 = off, 1 = on)
    - destination: the download destination path of the torrent
    - torrent: the URI of the torrent file that should be downloaded. This parameter is required.

        **Example request**:

            .. sourcecode:: none

                curl -X PUT http://localhost:8085/downloads
                --data "anon_hops=2&safe_seeding=1&destination=/my/dest/on/disk/&uri=file:/home/me/test.torrent

        **Example response**:

            .. sourcecode:: javascript

                {"started": True, "infohash": "4344503b7e797ebf31582327a5baae35b11bda01"}
    """
    parameters = http.parse_qs(request.content.read(), 1)

    if "uri" not in parameters or len(parameters["uri"]) == 0:
        request.setResponseCode(http.BAD_REQUEST)
        return json.twisted_dumps({"error": "uri parameter missing"})

    download_config, error = DownloadsEndpoint.create_dconfig_from_params(parameters)
    if error:
        request.setResponseCode(http.BAD_REQUEST)
        return json.twisted_dumps({"error": error})

    def download_added(download):
        request.write(
            json.twisted_dumps(
                {
                    "started": True,
                    "infohash": hexlify(download.get_def().get_infohash()),
                }
            )
        )
        request.finish()

    def on_error(error):
        request.setResponseCode(http.INTERNAL_SERVER_ERROR)
        request.write(
            json.twisted_dumps({"error": unichar_string(error.getErrorMessage())})
        )
        request.finish()

    uri = ensure_unicode(parameters["uri"][0], "utf-8")
    if uri.startswith("file:"):
        filename = url2pathname(uri[5:])
        if uri.endswith(".mdblob") or uri.endswith(".mdblob.lz4"):
            with db_session:
                try:
                    results = self.session.lm.mds.process_mdblob_file(filename)
                    if results:
                        node, status = results[0]
                        if status == UNKNOWN_CHANNEL or (
                            status == UPDATED_OUR_VERSION
                            and node.metadata_type == CHANNEL_TORRENT
                        ):
                            node.subscribed = True
                            return json.twisted_dumps(
                                {"started": True, "infohash": hexlify(node.infohash)}
                            )
                    return json.twisted_dumps(
                        {"error": "Could not import Tribler metadata file"}
                    )
                except IOError:
                    request.setResponseCode(http.BAD_REQUEST)
                    return json.twisted_dumps({"error": "Metadata file not found"})
                except InvalidSignatureException:
                    request.setResponseCode(http.BAD_REQUEST)
                    return json.twisted_dumps(
                        {"error": "Metadata has invalid signature"}
                    )
        else:
            download_uri = "file:%s" % filename
    else:
        download_uri = unquote_plus(uri)
    download_deferred = self.session.start_download_from_uri(
        download_uri, download_config
    )
    download_deferred.addCallback(download_added)
    download_deferred.addErrback(on_error)

    return NOT_DONE_YET