Conghao97's picture tcftrees's picture
ProgramGen release
d086025
|
Raw History Blame Contribute Delete
57.2 kB

7sdream/torrent_parser

Project Overview

torrent_parser is a lightweight, single-module Python library for reading, editing, and writing BitTorrent .torrent files, distributed on PyPI as torrent_parser and compatible with both Python 2 and Python 3. Its purpose is to expose the contents of a torrent file as ordinary Python data structures—dictionaries, lists, integers, strings, and byte strings—so applications can inspect metadata such as the announce URL or the info dictionary, modify it, and save a valid torrent file again.

The core of the library is a complete implementation of the BEncode serialization format used by the BitTorrent protocol. A BDecoder turns raw bytes into Python objects while BEncoder performs the reverse, and module-level decode/encode helpers provide one-shot conversion between in-memory objects and BEncoded bytes. On top of this sit file-oriented conveniences: TorrentFileParser reads a torrent from a binary stream, TorrentFileCreator serializes edited data back out, and the parse_torrent_file/create_torrent_file functions wrap these in simple filename-based calls.

Several conveniences distinguish the library: it can automatically decode byte fields into strings using a user-specified encoding and error handler, detect encodings automatically when the optional chardet package is installed, and decode fixed-length hash fields (such as piece hashes) into hash blocks, with that behavior customizable. Malformed input raises InvalidTorrentDataException, reporting the position where parsing failed.

A command-line interface, pytp, is included; it parses a torrent file or a stream piped to stdin and prints the contents as indented JSON.

Architecturally, the entire implementation lives in one file, torrent_parser.py, with a clean separation between low-level BEncode primitives and higher-level torrent file handling. A unittest suite in tests/ covers decoding, encoding, file creation, hash fields, info-hash computation, and error handling, alongside packaging metadata (setup.py, setup.cfg, MANIFEST.in).

Re-implement this repository from scratch so that the original test suite passes. The sections below document the language/environment, the project structure, the public API the tests exercise, and per-capability implementation guidance.

Submission Constraints (read carefully — the evaluation depends on these)

This is a closed-book task. The graded test suite is hidden and will be injected into the workspace at evaluation time. To be scored correctly you MUST follow these rules:

  1. Do NOT create or modify any files under the test directories (e.g. tests/, test/, testing/, or files named test_*.py / conftest.py). The grader injects its own test files at those paths; any file you place there will collide with the injected suite and cause the whole evaluation to score 0. Implement only the library/source code — never the tests.

  2. Your package MUST be importable by the name the tests use. The hidden tests import your package by its documented top-level name (see the Project Directory Structure and API Usage Guide below). Provide a valid pyproject.toml / setup.py / setup.cfg and lay out your modules so that pip install -e . succeeds and the package imports cleanly. If your package is not installable/importable, every test errors out and the reward is 0.

  3. Match the documented module paths and public API exactly (names, signatures, and any literal error/exception strings). Internal helpers not listed in the API guide may be implemented however you like.

Install / Reconstruction Contract

Follow this contract before implementing the documented APIs:

  • Project root: /workspace/repo at runtime; the submitted repository root is ..
  • Package/distribution name: torrent_parser
  • Package roots: .
  • Install strategy: editable-install
  • Import/entry: use the package and public entry points listed in the API Usage Guide; do not invent a different top-level package.
  • Provision commands:
    python3 -I -c 'import base64; from pathlib import Path; Path('"'"'/tmp/programgen-pip-compat-v1.py'"'"').write_bytes(base64.b64decode('"'"'aW1wb3J0IG9zCmZyb20gcGF0aGxpYiBpbXBvcnQgUGF0aAppbXBvcnQgc3VicHJvY2VzcwppbXBvcnQgc3lzCmltcG9ydCB0ZW1wZmlsZQoKZGVmIGNvbnN0cmFpbmVkX2J1aWxkX2luc3RhbGwoY29tbWFuZCwgcnVuKToKICAgIGNvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCgnUFJPR1JBTUdFTl9CVUlMRF9DT05TVFJBSU5UJykKICAgIGlmIG5vdCBjb25zdHJhaW50IG9yICctLW5vLWJ1aWxkLWlzb2xhdGlvbicgaW4gY29tbWFuZDoKICAgICAgICByZXR1cm4gTm9uZQogICAgaWYgc3lzLnZlcnNpb25faW5mb1s6Ml0gPCAoMywgOSk6CiAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSBpc29sYXRlZCBidWlsZCBjb25zdHJhaW50cyByZXF1aXJlIFB5dGhvbiA+PTMuOScsIGZsdXNoPVRydWUpCiAgICAgICAgcmV0dXJuIDEKICAgICMgQSBkZWRpY2F0ZWQgaW5zdGFsbGVyIGNvbnRyb2xzIFBFUCA1MTcgYnVpbGQgZGVwZW5kZW5jaWVzIG9ubHkuIEl0IGRvZXMKICAgICMgbm90IHVwZ3JhZGUgcGlwL3NldHVwdG9vbHMgaW4gdGhlIG1lYXN1cmVkIHByb2plY3QncyBydW50aW1lIGVudmlyb25tZW50LgogICAgd2l0aCB0ZW1wZmlsZS5UZW1wb3JhcnlEaXJlY3RvcnkocHJlZml4PSdwcm9ncmFtZ2VuLWJ1aWxkLWluc3RhbGxlci0nKSBhcyBkaXJlY3Rvcnk6CiAgICAgICAgcnVubmVyID0gc3RyKFBhdGgoZGlyZWN0b3J5KSAvICdiaW4nIC8gJ3B5dGhvbicpCiAgICAgICAgZm9yIHNldHVwIGluIChbc3lzLmV4ZWN1dGFibGUsICctbScsICd2ZW52JywgZGlyZWN0b3J5XSwKICAgICAgICAgICAgICAgICAgICAgIFtydW5uZXIsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICctLW5vLWNhY2hlLWRpcicsICdwaXA9PTI1LjMnXSk6CiAgICAgICAgICAgIHJlc3VsdCA9IHJ1bihzZXR1cCkKICAgICAgICAgICAgaWYgcmVzdWx0LnJldHVybmNvZGU6CiAgICAgICAgICAgICAgICByZXR1cm4gcmVzdWx0LnJldHVybmNvZGUKICAgICAgICBpZiBjb21tYW5kWzo0XSAhPSBbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCddIGFuZCBjb21tYW5kWzo0XSAhPSBbJ3B5dGhvbjMnLCAnLW0nLCAncGlwJywgJ2luc3RhbGwnXToKICAgICAgICAgICAgcHJpbnQoJ1twcm9ncmFtZ2VuXSB1bnN1cHBvcnRlZCBjb25zdHJhaW5lZCBpbnN0YWxsZXIgY29tbWFuZCcsIGZsdXNoPVRydWUpCiAgICAgICAgICAgIHJldHVybiAxCiAgICAgICAgdGFyZ2V0ID0gW3J1bm5lciwgJy1tJywgJ3BpcCcsICctLXB5dGhvbicsIHN5cy5leGVjdXRhYmxlLCAnaW5zdGFsbCcsCiAgICAgICAgICAgICAgICAgICctLWJ1aWxkLWNvbnN0cmFpbnQnLCBjb25zdHJhaW50XSArIGNvbW1hbmRbNDpdCiAgICAgICAgcmV0dXJuIHJ1bih0YXJnZXQpLnJldHVybmNvZGUKCmRlZiBpbnN0YWxsKGNvbW1hbmQsIHJ1bj1zdWJwcm9jZXNzLnJ1bik6CiAgICBmb3IgdmFyaWFibGUgaW4gKCdQUk9HUkFNR0VOX1JVTlRJTUVfQ09OU1RSQUlOVCcsICdQUk9HUkFNR0VOX1JVTlRJTUVfUkVQQUlSX0NPTlNUUkFJTlQnKToKICAgICAgICBydW50aW1lX2NvbnN0cmFpbnQgPSBvcy5lbnZpcm9uLmdldCh2YXJpYWJsZSkKICAgICAgICBpZiBydW50aW1lX2NvbnN0cmFpbnQ6CiAgICAgICAgICAgIGNvbW1hbmQgPSBsaXN0KGNvbW1hbmQpICsgWyctYycsIHJ1bnRpbWVfY29uc3RyYWludF0KICAgIGNvbnN0cmFpbmVkID0gY29uc3RyYWluZWRfYnVpbGRfaW5zdGFsbChjb21tYW5kLCBydW4pCiAgICBpZiBjb25zdHJhaW5lZCBpcyBub3QgTm9uZToKICAgICAgICByZXR1cm4gY29uc3RyYWluZWQKICAgIHJlc3VsdCA9IHJ1bihjb21tYW5kLCBzdGRvdXQ9c3VicHJvY2Vzcy5QSVBFLCBzdGRlcnI9c3VicHJvY2Vzcy5TVERPVVQsIHRleHQ9VHJ1ZSkKICAgIG91dHB1dCA9IHJlc3VsdC5zdGRvdXQgb3IgJycKICAgIHN5cy5zdGRvdXQud3JpdGUob3V0cHV0KQogICAgc3lzLnN0ZG91dC5mbHVzaCgpCiAgICBpZiByZXN1bHQucmV0dXJuY29kZSA9PSAwOgogICAgICAgIHJldHVybiAwCiAgICBsZWdhY3kgPSAnaW52YWxpZCBtZXRhZGF0YScgaW4gb3V0cHV0Lmxvd2VyKCkgYW5kICdwbGVhc2UgdXNlIHBpcDwyNC4xJyBpbiBvdXRwdXQubG93ZXIoKQogICAgaWYgbm90IGxlZ2FjeSBvciBub3QgKDMsIDgpIDw9IHN5cy52ZXJzaW9uX2luZm9bOjJdIDw9ICgzLCAxMik6CiAgICAgICAgcmV0dXJuIHJlc3VsdC5yZXR1cm5jb2RlCiAgICBwcmludCgnW3Byb2dyYW1nZW5dIGxlZ2FjeSBkaXN0cmlidXRpb24gbWV0YWRhdGE6IHJldHJ5aW5nIHRoZSB1bmNoYW5nZWQgcmVxdWlyZW1lbnRzIHdpdGggcGlwPDI0LjEnLCBmbHVzaD1UcnVlKQogICAgY2hhbmdlZCA9IHJ1bihbc3lzLmV4ZWN1dGFibGUsICctbScsICdwaXAnLCAnaW5zdGFsbCcsICdwaXA8MjQuMSddKQogICAgaWYgY2hhbmdlZC5yZXR1cm5jb2RlOgogICAgICAgIHJldHVybiBjaGFuZ2VkLnJldHVybmNvZGUKICAgIHJldHVybiBydW4oY29tbWFuZCkucmV0dXJuY29kZQoKaWYgX19uYW1lX18gPT0gJ19fbWFpbl9fJzoKICAgIHJhaXNlIFN5c3RlbUV4aXQoaW5zdGFsbChzeXMuYXJndlsxOl0pKQo='"'"'))'
    programgen_pip_install() { python3 -I /tmp/programgen-pip-compat-v1.py "$@"; }
    export -f programgen_pip_install
    programgen_pip_install python3 -m pip install -U pip 'setuptools<82' wheel
    programgen_pip_install python3 -m pip install 'setuptools>=61,<82' wheel
    (
    programgen_install_report="$(mktemp)"
    trap 'rm -f "$programgen_install_report"' EXIT
    SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 programgen_pip_install python3 -m pip install -e . --no-build-isolation --no-deps --report "$programgen_install_report"
    python3 -c 'exec("import json,subprocess,sys\nfrom pip._vendor.packaging.requirements import Requirement\nfrom pip._vendor.packaging.utils import canonicalize_name\nreport=json.load(open(sys.argv[1], encoding='"'"'utf-8'"'"'))\n\nrequested={canonicalize_name(name) for name in ()}\nrequirements=[]\nfor item in report.get('"'"'install'"'"', []):\n    metadata=item.get('"'"'metadata'"'"', {})\n    name=canonicalize_name(metadata.get('"'"'name'"'"', '"'"''"'"'))\n    provided={canonicalize_name(value) for value in metadata.get('"'"'provides_extra'"'"', [])}\n    selected={'"'"''"'"'} | (provided & requested)\n    parsed=[Requirement(value) for value in metadata.get('"'"'requires_dist'"'"', [])]\n    while True:\n        added=set()\n        for requirement in parsed:\n            if requirement.marker is not None and not any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n                continue\n            if canonicalize_name(requirement.name)==name:\n                if requirement.url or (requirement.specifier and not requirement.specifier.contains(metadata.get('"'"'version'"'"', '"'"''"'"'), prereleases=True)):\n                    raise ValueError('"'"'local extra requires a different target distribution'"'"')\n                extras={canonicalize_name(value) for value in requirement.extras}\n                if not extras <= provided:\n                    raise ValueError('"'"'local extra refers to an undeclared extra'"'"')\n                added.update(extras - selected)\n        if not added:\n            break\n        selected.update(added)\n    for requirement in parsed:\n        if canonicalize_name(requirement.name)==name:\n            continue\n        if requirement.marker is None or any(requirement.marker.evaluate({'"'"'extra'"'"': extra}) for extra in selected):\n            requirement.marker=None\n            requirements.append(str(requirement))\nrequirements=list(dict.fromkeys(requirements))\nsubprocess.run([sys.executable, '"'"'-I'"'"', '"'"'/tmp/programgen-pip-compat-v1.py'"'"', sys.executable, '"'"'-m'"'"', '"'"'pip'"'"', '"'"'install'"'"', *requirements], check=True) if requirements else None\n")' "$programgen_install_report"
    )
    
  • Runtime setup:
    {
      SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0 PDM_BUILD_SCM_VERSION=0.0.0 POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0 UV_DYNAMIC_VERSIONING_BYPASS=0.0.0 SETUPTOOLS_SCM_WRITE_TO_SOURCE=1 python3 -m pip install -e "$PWD" --no-build-isolation --no-deps;
    }
    
  • Project root for installation: .
  • Build-version environment: SETUPTOOLS_SCM_PRETEND_VERSION=0.0.0, PDM_BUILD_SCM_VERSION=0.0.0, POETRY_DYNAMIC_VERSIONING_BYPASS=0.0.0, UV_DYNAMIC_VERSIONING_BYPASS=0.0.0
  • Test directory: tests
  • Test command: bash -lc 'set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_create.py tests/test_decode.py tests/test_decoding_error.py tests/test_encode.py tests/test_hash_field.py tests/test_hash_raw.py tests/test_info_hash.py tests/test_parse.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_create.py tests/test_decode.py tests/test_decoding_error.py tests/test_encode.py tests/test_hash_field.py tests/test_hash_raw.py tests/test_info_hash.py tests/test_parse.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_create.py tests/test_decode.py tests/test_decoding_error.py tests/test_encode.py tests/test_hash_field.py tests/test_hash_raw.py tests/test_info_hash.py tests/test_parse.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '"'"'/::/p'"'"' | sed '"'"'s/[[:space:]]*$//'"'"') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'"'"'::'"'"' -v limit=500 '"'"'{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}'"'"') fi "${run[@]}"; exit $?'
  • Test startup: run the exact test command above from the project root after installation; hidden tests are injected separately.

Environment & Project Structure

  • Language: python
  • Build system: python
  • Test command: bash -lc set -uo pipefail run=(python3 -m pytest -vv -o addopts= tests/test_create.py tests/test_decode.py tests/test_decoding_error.py tests/test_encode.py tests/test_hash_field.py tests/test_hash_raw.py tests/test_info_hash.py tests/test_parse.py) if [ -n "${COVERAGE_FILE:-}" ]; then run=(python3 -m coverage run --source=. -m pytest -vv -o addopts= tests/test_create.py tests/test_decode.py tests/test_decoding_error.py tests/test_encode.py tests/test_hash_field.py tests/test_hash_raw.py tests/test_info_hash.py tests/test_parse.py); fi collect=(python3 -m pytest -q -o addopts= tests/test_create.py tests/test_decode.py tests/test_decoding_error.py tests/test_encode.py tests/test_hash_field.py tests/test_hash_raw.py tests/test_info_hash.py tests/test_parse.py) collected_output=$("${collect[@]}" --collect-only) collect_rc=$? if [ "$collect_rc" -ne 0 ] && [ "$collect_rc" -ne 5 ]; then printf "%s\n" "$collected_output" >&2 printf "[programgen] test collection failed with exit code %s\n" "$collect_rc" >&2 exit "$collect_rc" fi mapfile -t collected < <(printf "%s\n" "$collected_output" | sed -n '/::/p' | sed 's/[[:space:]]*$//') if [ "${#collected[@]}" -gt 500 ]; then while IFS= read -r id; do run+=("--deselect=$id"); done < <(printf "%s\n" "${collected[@]}" | awk -F'::' -v limit=500 '{f=$1; n[f]++; idx[f,n[f]]=NR; all[NR]=$0; if(!(f in seen)){seen[f]=1; order[++m]=f}} END{d=1; c=0; while(c<limit){a=0; for(i=1;i<=m;i++){f=order[i]; if(d<=n[f]){keep[idx[f,d]]=1; c++; a=1; if(c>=limit) break}} if(!a) break; d++} for(r=1;r<=NR;r++) if(!(r in keep)) print all[r]}') fi "${run[@]}"; exit $?

Project Directory Structure

.gitignore
CHANGELOG.md
LICENSE
MANIFEST.in
README.md
setup.cfg
setup.py
torrent_parser.py

API Usage Guide

Each capability below lists the components the tests exercise with their exact signatures and behavior. Re-create these so the tests pass; internal helpers not listed here may be implemented freely.

Capability: Bencode decoding of torrent data

Bencode decoding of torrent data

Purpose and mental model

This capability is the read half of the library's bencode round trip: it turns BEncoded input — a bytes object or a binary file-like stream — into ordinary Python objects (int, str/bytes, list, dict/OrderedDict). decode() is the one-shot shortcut; BDecoder is the reusable engine behind it, and TorrentFileParser is a preset of BDecoder for real .torrent files. Everything a decoder produces is consumable by the encoder side (encode/BEncoder), including hexlified hash strings.

Entry points and how they relate

  • decode(data, use_ordered_dict=False, encoding='utf-8', errors='strict', hash_fields=None, hash_raw=False) — constructs a BDecoder with these options and calls decode() on it.
  • BDecoder(...).decode() — identical semantics, but the instance is stateful and reusable: each decode() call first seeks the underlying stream back to offset 0, so repeated calls re-parse from the beginning regardless of where the stream was left. The restart resets only the stream position, though: the active encoding is instance state that survives. If a previous parse decoded a dict entry under the key "encoding", that value remains the active encoding for every string of all later decode() calls on the same instance — reuse is not equivalent to constructing a fresh decoder for such payloads. .hash_field(name, block_length=20, need_list=False) can be chained before decoding to register hash fields; it returns self.
  • TorrentFileParser(fp, ...).parse() — delegates to BDecoder but seeds default hash fields (pieces → (20, True), ed2k → (16, False), filehash → (20, False), "pieces root" → (32, False)) and defaults errors to "usebytes". The combination rules differ: hash_fields is merged — the preset map is copied and then updated with the caller's mapping, so a user entry overrides only the same-named preset while the other defaults stay active — whereas a passed errors replaces the "usebytes" default entirely. Use it when decoding whole torrent files; use decode/BDecoder for raw bencode blobs and full control over defaults.

Input acceptance

data must be bytes (wrapped internally in a BytesIO) or an object exposing both read and seek. The check is duck-typed via bare getattr(data, "read") / getattr(data, "seek") lookups with no default, so the failure mode depends on what is missing:

  • An object with neither attribute (e.g. decode(123)), or one that has read but lacks seek, raises an unhandled AttributeError — not ValueError.
  • ValueError("Parameter data must be bytes or file like object") fires only when both attributes exist but at least one is None (the is not None checks short-circuit into the error branch).

Text-mode files pass the attribute check structurally but will misbehave; always open files with mode 'rb'. hash_fields, when given, is validated eagerly in the constructor: each key must be str and each value a 2-tuple (int, bool), else ValueError with the literal parameter message from the profile.

Grammar mapping

BEncode form Python result
i[-]<digits>e int
<length>:<raw bytes> str decoded with the active encoding (or raw bytes, see below)
l<element>*e list, elements in wire order
d<key><value>*e dict (or collections.OrderedDict when use_ordered_dict=True), preserving wire order

Nesting is arbitrary and recursive. Decoding requires exactly one top-level element: after it is parsed, one more byte is read and must be EOF; any leftover byte raises InvalidTorrentDataException with message Expect EOF, but get [<byte>] at pos <pos>, where <pos> is the decoder position after consuming that byte. Empty input never yields None — it fails inside the first element with Unexpected EOF when reading torrent file at pos 0.

Reads do not reliably detect truncation: the EOF error fires only when a read returns zero bytes. A string (or hash value) whose declared length exceeds the remaining input still parses when at least one byte remains — the value is silently truncated (decode(b'3:ab') == 'ab', decode(b'5:abc') == 'abc') and the running position advances by the declared length, overshooting the real end of the stream. End-of-stream truncation of string and hash values is therefore not detected as an error.

A byte that cannot begin any listed form (l, d, i, e, or a digit) does not produce an unknown-type error: the empty string indicator matches it, parsing falls into the string-length scan, and the byte fails the digit check there, raising InvalidTorrentDataException with the default message Invalid torrent format when read at pos <pos> anchored at that byte's offset (e.g. decode(b'x') fails at pos 0).

Non-obvious integer scanner behavior: digits accumulate until the terminator (e for integer values, : for string lengths). A single - toggles negation wherever it appears (even after digits); a second - or any other non-digit aborts with InvalidTorrentDataException anchored at that byte's offset. Leading zeros and an empty body (ie) parse to valid ints (0).

Dictionary keys must decode to str or bytes — an int/list/dict key raises InvalidTorrentDataException with Type of dict key can't be <typename> at the position reached after the key. Later duplicate keys overwrite earlier values. Key lookup for hash fields happens against the decoded key value.

Strings, encodings, and the self-describing encoding key

Strings are length-prefixed raw bytes decoded with the active encoding:

  • encoding="auto" runs charset detection (detect(), backed by chardet) separately on each string's raw bytes; without chardet installed it emits a warning and falls back to utf-8. The per-string detection result is not persisted into the decoder's active encoding.
  • Side effect worth knowing: whenever a decoded dict contains the key "encoding", its value replaces the decoder's active encoding for every subsequent string in the stream — and, being instance state, it outlives the current parse (see the reuse caveat above). Torrent files use this to declare their charset mid-file.
  • errors is forwarded to bytes.decode, so any standard codec handler works ("strict", "ignore", "replace", ...). The library adds one custom handler, "usebytes" (alias BDecoder.ERROR_HANDLER_USEBYTES): decode strictly, but on failure return the raw bytes for that string instead of raising. It only affects strings that actually fail; valid strings still come back as str.
  • With any other handler, a UnicodeDecodeError is converted to InvalidTorrentDataException positioned at the first bad byte inside the string (current pos - string length + error.start), with message Fail to decode string at pos <pos> using encoding <encoding>. When the string is a dict value, the message additionally names the field and suggests registering it via hash_field("<field>").

Hash fields

A dict key registered in hash_fields (constructor mapping {name: (block_length, need_list)} or the chained hash_field method) makes its value's raw bytes skip text decoding entirely. Constraints:

  • The raw byte length must be an exact multiple of block_length, else InvalidTorrentDataException with Hash bit length not match at pos <pos>, anchored at the start of the value's bytes. Because short reads truncate silently, a value truncated at end-of-stream can still pass this check (e.g. only 20 of 40 declared bytes arrive and are hexlified as one 20-byte chunk).
  • By default the value is split into block_length chunks and each chunk is hexlified to an ASCII str. Result shape: zero chunks → "" (or [] when need_list is true); one chunk → that hex string (or [hex] when need_list); multiple chunks → always a list.
  • hash_raw=True bypasses splitting/hexlification and returns the raw bytes unchanged.

Malformed parameters raise ValueError with the literal messages shown in the profile ("Invalid hash field parameter" from the chained method; the longer dict-type message from the constructor).

Error positions and state

All structural failures raise InvalidTorrentDataException; its position is an absolute byte offset from the start of the stream (the decoder's running _pos, advanced by every read — including declared-length reads that overshoot a truncated stream), not a nesting-relative offset. Unexpected EOF when reading torrent file reports where a zero-byte read ran dry; hash-length errors report the value's start offset; decode errors report the offending byte inside the string. There is no dedicated unknown-type error — unrecognized bytes surface through the string-length scan with the default message. Because decode() restarts the stream, a failed parse leaves a file object seekable and re-parseable — but a bytes-backed decoder's internal BytesIO is simply left at EOF after success, and the active encoding (possibly switched by an "encoding" dict key) is not reset between calls on the same instance.

Test-sensitive checklist

  • decode(b'i12345e') == 12345 is the canonical assertion.
  • decode(b'3:ab') == 'ab': a declared length longer than the remaining input truncates silently instead of raising — do not assert an exception for truncated strings or hashes.
  • A torrent containing a string with invalid utf-8 raises InvalidTorrentDataException under decode's default errors='strict', but decodes fine with errors='ignore' (bad bytes dropped). Note the deliberate default mismatch: decode uses 'strict', while TorrentFileParser/parse_torrent_file use 'usebytes' so damaged fields surface as bytes instead of exceptions.
  • use_ordered_dict=True is required if callers rely on key order in a plain-dict environment or want OrderedDict explicitly.
  • Decoded results on Python 2 are unicode strings (the module uses unicode_literals); bytes results are str there.

Exact API Reference

torrent_parser.detect

  • Import Path: from torrent_parser import detect
  • Signature:
def detect(content)

torrent_parser.InvalidTorrentDataException

  • Import Path: from torrent_parser import InvalidTorrentDataException
  • Required Test Import Paths:
    • torrent_parser.InvalidTorrentDataException
  • Exact Test Import Statements:
    • from torrent_parser import InvalidTorrentDataException, TorrentFileParser, decode
  • Kind: exception
  • Signature:
class InvalidTorrentDataException(Exception):
    def __init__(self, pos, msg=None)

torrent_parser.BDecoder

  • Import Path: from torrent_parser import BDecoder
  • Signature:
class BDecoder:
    def hash_field(self, name, block_length=20, need_list=False)
    def decode(self)
  • Raises (implementation must reproduce these exact messages):
    • Invalid hash field parameter
    • Unexpected EOF when reading torrent file
    • Hash bit length not match at pos {pos}
    • Parameter data must be bytes or file like object
    • Invalid hash field parameter, it should be type of Dict[str, Tuple[int, bool]]

torrent_parser.BEncoder

  • Import Path: from torrent_parser import BEncoder
  • Required Test Import Paths:
    • torrent_parser.BEncoder
  • Exact Test Import Statements:
    • from torrent_parser import BEncoder, TorrentFileCreator, TorrentFileParser
  • Kind: class
  • Signature:
class BEncoder(object):
    TYPES: dict
    def __init__(self, data, encoding='utf-8', hash_fields=None)
    def hash_field(self, name)
    def encode(self)
    def encode_to_filelike(self)

torrent_parser.encode

  • Import Path: from torrent_parser import encode
  • Required Test Import Paths:
    • torrent_parser.encode
  • Exact Test Import Statements:
    • from torrent_parser import decode, encode
    • from torrent_parser import encode
    • from torrent_parser import encode, parse_torrent_file
  • Signature:
def encode(data, encoding='utf-8', hash_fields=None)
  • Behavior: Shortcut function for encode python object to torrent file format(bencode)

torrent_parser.decode

  • Import Path: from torrent_parser import decode
  • Required Test Import Paths:
    • torrent_parser.decode
  • Exact Test Import Statements:
    • from torrent_parser import InvalidTorrentDataException, TorrentFileParser, decode
    • from torrent_parser import TorrentFileParser, decode, parse_torrent_file
    • from torrent_parser import decode
    • from torrent_parser import decode, encode
  • Signature:
def decode(data, use_ordered_dict=False, encoding='utf-8', errors='strict', hash_fields=None, hash_raw=False)
  • Behavior: Shortcut function for decode bytes as torrent file format(bencode) to python

Capability: Torrent file parsing workflow

Torrent file parsing workflow

This capability turns a .torrent file — or any BEncoded byte stream — into ordinary Python objects with one call, applying the defaults real torrent files need: pre-registered hash fields, a tolerant string-decoding error handler, and optional ordered dicts. Two entry points share one engine:

  • parse_torrent_file(filename, ...) is the filename shortcut. It opens the file in binary mode itself, builds a TorrentFileParser, runs parse(), and closes the file before returning the result. Use it when the data is on disk and you want a one-liner.
  • TorrentFileParser(fp, ...) is the stream-oriented class. fp may be a binary file object (opened with mode 'b') or raw bytes — the underlying decoder wraps bytes in a BytesIO. Use it when data arrives from stdin, memory, or when you want to parse the same stream more than once.

Both forward an identical option surface (use_ordered_dict, encoding, errors, hash_fields, hash_raw) to an internal BDecoder. The class is a thin wrapper, not a subclass: all parsing behavior lives in the decoder; the wrapper only injects defaults and delegates.

Defaults that differ from the raw decoder

Two defaults distinguish this workflow from calling the raw decoder directly:

  1. errors='usebytes' (not 'strict'). Strings are decoded strictly, but any field that fails becomes raw bytes instead of raising. This is what makes real-world torrents parse: in BitTorrent v2 data the values under piece layers are SHA-256 blobs that are not valid UTF-8, and with the default they come back as bytes. Passing errors='strict' would turn the same file into InvalidTorrentDataException.
  2. Predefined hash fields. Before your hash_fields are considered, these are registered:
field block length forced list
pieces 20 yes
ed2k 16 no
filehash 20 no
pieces root 32 no (note the space)

A user-supplied hash_fields dict is merged over the defaults, so you can override a block length for pieces but you cannot unregister a default field through the constructor. Chaining hash_field(name, block_length, need_dict) after construction adds or replaces a single field and likewise overrides same-name defaults.

Hash field result shapes

A registered hash field is read without string decoding, its byte length must be an exact multiple of the block length (otherwise InvalidTorrentDataException with Hash bit length not match at pos {pos}), and the raw bytes are split into blocks, each hexlified to an ASCII hex string. Result shape depends on the (block_length, force_list) pair:

  • zero blocks and not forced-list → empty string ''
  • exactly one block and not forced-list → a single hex string
  • otherwise → a list of hex strings, even for one block

hash_raw=True bypasses grouping for every hash field (default and custom) and returns the undecoded bytes. Because pieces is registered with forced-list, a single-piece torrent still yields a one-element list; ed2k and filehash are single-hash fields and yield one string.

Encoding behavior and the encoding key

The default encoding is utf-8. encoding='auto' runs charset detection per decoded string (chardet; a warning plus a utf-8 fallback when chardet is absent), so different fields may decode with different encodings. Non-obvious and test-relevant: while walking a dict, if the key encoding is encountered, its decoded value replaces the parser's current encoding for every string parsed afterwards. The condition is on the key alone: the value's decoded type is never examined and the value replaces the encoding unconditionally, so a non-str value (e.g. raw bytes surviving usebytes) becomes the encoding and breaks all subsequent string decodes. A torrent that declares its own encoding therefore wins over the constructor argument for later fields — but only if that key itself decoded to str; with usebytes an undecodable key becomes bytes and the override does not fire.

State, ordering, and repeated parses

The parser owns the stream and a position counter. Every parse() starts by seeking the stream back to position 0, so a single TorrentFileParser instance can parse the same stream multiple times — but only the stream position and the internal offset counter are reset between passes, never the encoding. Identical results across parses are therefore guaranteed only when the content contains no encoding key: an override picked up on one pass leaks into every later pass, so a field stored before that key can decode to str on the first parse and to raw bytes on the second, when the leaked encoding cannot decode it. encoding='auto' does not itself leak — detection re-runs per string on every pass — though an encoding key still overrides it for the rest of that pass and all later ones. Error positions refer to the current pass. The stream must support read and seek — text-mode streams break everything, so files must be opened with 'b'.

With use_ordered_dict=True every dict, at every nesting level, becomes collections.OrderedDict preserving BEncode key order; otherwise plain dict is used and later duplicate keys overwrite earlier ones. A plain-dict result compares equal to an OrderedDict with the same items, so tests that assert container type must use assertIsInstance.

Result and error surface

The top level of the stream need not be a dict: a BEncoded string file parses to that string (e.g. 'announce'), and negative integers parse as negative ints. After the top-level value, parse() demands EOF; a single trailing byte raises InvalidTorrentDataException with Expect EOF, but get [<char>] at pos <pos>. Positions are absolute stream offsets from the current pass, which is what the error tests assert against.

The remaining InvalidTorrentDataException messages come from integer parsing and zero-byte reads, not from type dispatch:

  • Invalid torrent format when read at pos {pos} is raised from integer parsing when a non-digit byte (other than a leading -) appears where an integer-body digit or a string-length digit is expected. There is no reachable unknown-type branch: the string type's indicator is the empty byte string, so the type scan consumes every byte other than l, d, i, e as the start of a string length. A top-level x therefore does raise this message, but a top-level : parses as an empty string and a top-level digit begins a string length.
  • Unexpected EOF when reading torrent file is raised only when a read returns zero bytes: EOF at a type indicator, inside an integer body, or inside a string-length prefix. A string whose declared length exceeds the remaining bytes is not an error — the short payload is silently accepted as a shorter value (top-level 4:ab parses to 'ab') and the position advances by the full declared length, not the bytes actually read. The miscount surfaces later instead, as a hash-length mismatch or a trailing-byte error.

Separately, malformed hash-field registration — a non-str name, or a value that is not a two-element (int, bool) tuple — raises ValueError at construction or hash_field() time, not InvalidTorrentDataException.

When a normal string field fails to decode under a handler other than usebytes, the exception message names the field and suggests registering it with hash_field(...); registering the field (for example info_hash on a file that stores raw hashes) is the intended fix and makes previously failing files parse.

Typical workflow

Parse with the shortcut for one-shot inspection, or hold a parser for streams and repeated parses. Results are plain containers — dicts, lists, ints, strings, hex-string hash lists — safe to mutate and to hand to the creation-side API for a read-modify-write round trip. parse_torrent_file and the class form are interchangeable for correctness; the class form is required when input is not a filesystem path.

Exact API Reference

torrent_parser.TorrentFileParser

  • Import Path: from torrent_parser import TorrentFileParser
  • Required Test Import Paths:
    • torrent_parser.TorrentFileParser
  • Exact Test Import Statements:
    • from torrent_parser import BEncoder, TorrentFileCreator, TorrentFileParser
    • from torrent_parser import InvalidTorrentDataException, TorrentFileParser, decode
    • from torrent_parser import TorrentFileParser, decode, parse_torrent_file
    • from torrent_parser import TorrentFileParser, parse_torrent_file
  • Kind: class
  • Signature:
class TorrentFileParser(object):
    HASH_FIELD_DEFAULT_PARAMS: dict
    def __init__(self, fp, use_ordered_dict=False, encoding='utf-8', errors=BDecoder.ERROR_HANDLER_USEBYTES, hash_fields=None, hash_raw=False)
    def hash_field(self, name, block_length=20, need_dict=False)
    def parse(self)

torrent_parser.parse_torrent_file

  • Import Path: from torrent_parser import parse_torrent_file
  • Required Test Import Paths:
    • torrent_parser.parse_torrent_file
  • Exact Test Import Statements:
    • from torrent_parser import TorrentFileParser, decode, parse_torrent_file
    • from torrent_parser import TorrentFileParser, parse_torrent_file
    • from torrent_parser import encode, parse_torrent_file
  • Signature:
def parse_torrent_file(filename, use_ordered_dict=False, encoding='utf-8', errors='usebytes', hash_fields=None, hash_raw=False)
  • Behavior: Shortcut function for parse torrent object using TorrentFileParser

Capability: Torrent file creation and round-trip editing

Torrent file creation and round-trip editing

What this capability does

This is the write half of the library. Once a torrent has been parsed into ordinary Python data and edited, TorrentFileCreator and create_torrent_file serialize that data back into BEncoded bytes and write them to disk, completing the read-edit-write-back workflow demonstrated in the README: parse a .torrent file, change fields such as the announce URL or values inside the info dictionary, then save a new, valid torrent file.

The round-trip workflow

Reading and writing are symmetric. The structure you hand to the creator is the same nested structure the parser produced - dicts, lists, ints, strings, and (for hash fields) their decoded hex-string representation - with your edits applied:

import torrent_parser as tp

data = tp.parse_torrent_file('test.torrent')
data['announce'] = 'http://tracker.example.com:6881/announce'
data['comment'] = 'rebuilt with torrent_parser'
tp.create_torrent_file('new.torrent', data)

Any BEncodable mutation is allowed: overwrite values, add or delete keys anywhere in the tree, append list elements.

How the components relate

TorrentFileCreator is a thin configuration layer over BEncoder:

  • Constructing it stores your data by reference and builds one encoder configured with the given encoding (default utf-8) and hash_fields. The same default hash-field set the parser applies is always registered on the encoder, so data coming from a default parse re-encodes correctly with no extra arguments; an explicit hash_fields argument only adds further names on top of those defaults.
  • create_filelike() delegates to the encoder and returns a binary in-memory stream holding the complete BEncoded document with its read position at the start; call .read() on it to obtain the bytes (useful when the output should go somewhere other than a file).
  • create(filename) produces the same bytes and writes them to filename, opened in binary write mode (wb), creating or truncating the file.
  • create_torrent_file is the one-call convenience and the write-side twin of parse_torrent_file: it takes the target filename and the data (plus the same optional encoding/hash_fields arguments), constructs a creator, and immediately writes the file.
  • hash_field(name) registers one additional field name as a hash field on the underlying encoder, in addition to the always-registered defaults. It mutates the creator, so call it before the first output-producing call; output generated afterwards reflects it.

Encoding contract and defaults

  • encoding is applied when the document is generated, not at construction: string values and dict keys are encoded with it, ints/lists/dicts are emitted per the BEncode grammar, and bytes values pass through byte-for-byte. Consequently, encoding problems (characters not representable in the chosen codec) surface from create/create_filelike, not from the constructor.
  • Round-trip rule: create with the same encoding you parsed with. Re-encoding non-ASCII text under a different codec changes the emitted bytes, which changes the computed info-hash of the resulting file even though the in-memory data is identical.
  • Keys are not sorted. Output order follows the dict's iteration order; a dict returned by the parser preserves the original file's key order on Python 3.7+, so a round-tripped file keeps its field ordering and newly added keys appear at the end of their dict. (On Python 2, dict order is arbitrary.)

State, ordering, and repeatability

  • The creator holds a reference to your data and defers encoding until output is requested, so edits made after construction but before the first create/create_filelike call are included.
  • Output can be produced repeatedly: each create call re-encodes the current data and rewrites (truncating) the target file. hash_field registrations affect only output produced after the call.

Hash fields in a round trip

Hash fields such as the pieces value in the info dict hold binary data in the torrent file. The parse side decodes them into a plain hex-string representation - a single hex string or a list of hex strings; there is no special hash type in memory. The creator's encoder recognizes the registered field names and re-emits the original concatenated bytes unchanged: for each registered value it unhexifies every element and emits the concatenation of the resulting bytes - that is why a default parse, edit, create sequence preserves hash fields exactly without extra configuration.

Value contract: a registered hash field's value must be a hex string or a list of hex strings, each of even length. Any other shape raises InvalidTorrentDataException at output time - including raw bytes stored under a registered name (for example when a hash_raw=True parse configuration is mirrored onto the create side, since iterating bytes yields ints), odd-length strings, and strings that are not valid hex.

If you customized the parse side (calling hash_field(...) on the parser or passing a hash_fields argument), mirror that configuration on the create side by registering the same extra names; an unregistered field holding hex-string hash data is not recognized as a hash field. Fields kept as raw bytes (for example undecodable text retained by the parser's usebytes error handler) pass through the creator unchanged only while their names are not registered as hash fields - registering such a name subjects the value to the hex contract above, and output fails.

Edge cases and failure modes

  • No torrent-structure validation: any bencodable structure is accepted, so a dict without announce or info still produces a file. Whether real BitTorrent clients accept the result is outside the library's scope.
  • Only bencodable values are supported: dicts, lists, ints, strings/bytes, and hash-field values given as hex strings or lists of hex strings; anything else fails with an InvalidTorrentDataException naming the offending type, raised from the output call. Dict keys that are not str or bytes fail the same way.
  • The parent directory of filename must already exist; the creator never creates directories.
  • Nothing is written until create runs, and create truncates an existing target file.

Test-sensitive summary

  • Round-trip identity: parsing a created file yields data equal to what was passed in, under matching encoding settings.
  • Hash fields survive byte-for-byte with default settings; custom hash fields require symmetric registration on both sides, with registered values shaped as hex strings or lists of hex strings.
  • Key order is preserved, never sorted; encoding is lazy; the write target is opened in binary mode.

Exact API Reference

torrent_parser.TorrentFileCreator

  • Import Path: from torrent_parser import TorrentFileCreator
  • Required Test Import Paths:
    • torrent_parser.TorrentFileCreator
  • Exact Test Import Statements:
    • from torrent_parser import BEncoder, TorrentFileCreator, TorrentFileParser
  • Kind: class
  • Signature:
class TorrentFileCreator(object):
    def __init__(self, data, encoding='utf-8', hash_fields=None)
    def hash_field(self, name)
    def create_filelike(self)
    def create(self, filename)

Detailed Implementation Nodes

Node: Bencode decoding of torrent data

Implementation nodes

Functional constraints

  • Input: bytes or an object with both read and seek. The check uses bare getattr(data, "read") / getattr(data, "seek") without a default, so a missing attribute raises AttributeError (e.g. decode(123), or an object with read but no seek); ValueError("Parameter data must be bytes or file like object") fires only when an existing read/seek attribute is None. Text-mode streams are not supported despite passing the duck-type check.
  • Grammar: i<int>e, <len>:<bytes>, l<elems>e, d<key><val>*e; fully recursive. Exactly one top-level value must be followed by EOF (Expect EOF, but get [<byte>] at pos <pos> otherwise); empty input raises at pos 0. Reads fail with Unexpected EOF when reading torrent file only when a read returns zero bytes: a declared-length string/hash read with at least one byte left truncates silently and _pos advances by the requested count (b'3:ab' decodes to 'ab'), so end-of-stream truncation is undetected — and a truncated hash can still satisfy the block-length check (20 of 40 declared bytes hexlified as one chunk).
  • Unknown start bytes (non-l/d/i/e, non-digit) match the empty string indicator, fall into the string-length scan, and raise InvalidTorrentDataException with the default message at that byte's offset.
  • Integers scan until the terminator; one - negates anywhere, a second -/non-digit raises at that offset; empty/zero-padded forms decode to valid ints.
  • Dict keys must decode to str/bytes (else Type of dict key can't be <type> at the post-key position); duplicates overwrite; use_ordered_dict=True yields OrderedDict in wire order.
  • Strings decode with the active encoding; encoding="auto" per-string chardet detection (detection result not persisted); a decoded dict entry under key "encoding" switches the active encoding for all later strings.
  • errors: standard codec handlers, plus "usebytes" → strict decode returning raw bytes on failure. Other handlers convert UnicodeDecodeError to InvalidTorrentDataException at the first bad byte inside the string, naming the dict field when known.
  • Hash fields ({name: (block_length, need_list)} or chained hash_field): value read as raw bytes, length must be a multiple of block_length (else Hash bit length not match at pos <pos> at the value start); output is hexlified blocks — ""/single str unless need_list, list otherwise; hash_raw=True returns unsplit bytes. Invalid parameters → ValueError.
  • Every parse failure is InvalidTorrentDataException carrying an absolute stream byte offset (default message Invalid torrent format when read at pos {pos} when no custom message is supplied).
  • State: each decode() seeks the stream to 0 and resets _pos only — the _encoding mutated by an "encoding" dict key persists across decode() calls on the same BDecoder instance, so repeated decodes are not equivalent to a fresh decoder when the payload declares an encoding; hash_field() mutates the instance and returns self for chaining. TorrentFileParser.parse() is BDecoder.decode() with preset hash fields merged per key over the defaults (user entries override only same-named presets; the rest stay active) and errors="usebytes" replaced entirely when passed.

Example

from torrent_parser import BDecoder, InvalidTorrentDataException, decode

assert decode(b'i12345e') == 12345
assert decode(b'l4:spami1ee') == ['spam', 1]
assert decode(b'd3:bari42e3:foo4:spamee') == {'bar': 42, 'foo': 'spam'}
assert decode(b'3:ab') == 'ab'   # short read: silently truncated, no exception

dec = BDecoder(b'd6:pieces40:' + b'\x11' * 40 + b'e').hash_field('pieces', 20, True)
try:
    data = dec.decode()            # {'pieces': ['1111...', '1111...']}
except InvalidTorrentDataException as e:
    print(e)                       # message contains the offending byte position

Node: Torrent file parsing workflow

Functional constraints

  • Entry points: parse_torrent_file(filename, ...) opens the file itself in binary mode and returns the parse result; TorrentFileParser(fp, ...) accepts a binary file-like object (must support read and seek) or bytes.
  • Wrapper, not subclass: TorrentFileParser builds an internal BDecoder in __init__ and parse() is exactly self._decoder.decode(); options are forwarded positionally.
  • Defaults versus the raw decoder: errors defaults to 'usebytes' (strict decode, raw bytes fallback on UnicodeDecodeError); predefined hash fields pieces=(20, True), ed2k=(16, False), filehash=(20, False), 'pieces root'=(32, False) are always registered, and a user hash_fields dict is merged over them — same-name entries are overridden, defaults cannot be removed via the constructor.
  • Hash fields: the value is read undecoded; its byte length must be a multiple of the block length or InvalidTorrentDataException('Hash bit length not match at pos {pos}') is raised; results are hexlified per block — '' for empty, one hex string for a single block unless forced-list, a list otherwise; hash_raw=True returns raw bytes for all hash fields.
  • hash_field(name, block_length=20, need_dict=False) must be called before parse(), returns self for chaining, and replaces any same-name entry including defaults; its third parameter is named need_dict but semantically means 'force list result' and is passed positionally into the decoder.
  • Repeatability: every parse() seeks the stream to 0 and resets the position counter — nothing else is restored. Repeated parses therefore return identical results only when no encoding key mutates the parser encoding; an override assigned on one pass leaks into later passes because only the stream position is reset. The stream must be seekable.
  • Encoding: default utf-8; 'auto' detects per string (chardet, with a warning and utf-8 fallback if absent); detected values are never written back to the parser's encoding, so 'auto' re-detects every string on every pass. The encoding-key override fires whenever a decoded dict key equals 'encoding', regardless of the value's decoded type: the value replaces the encoding unconditionally, and a non-str value (e.g. bytes surviving usebytes) corrupts all later string decodes.
  • Dicts: use_ordered_dict=True yields collections.OrderedDict at every nesting level preserving BEncode key order; otherwise plain dict with last-wins duplicate keys.
  • Top level: need not be a dict — a bare BEncoded string or integer parses to that value; negative integers are supported.
  • EOF discipline: exactly EOF must follow the top-level value; trailing bytes raise InvalidTorrentDataException with Expect EOF, but get [<char>] at pos <pos>. Invalid torrent format when read at pos {pos} is raised from integer parsing when a non-digit byte (other than a leading -) appears where an integer-body digit or a string-length digit is expected — not from type dispatch; there is no reachable unknown-type branch (the empty string indicator makes the type scan treat every byte other than l/d/i/e as a length-prefix digit, and a bare : parses as an empty string). Unexpected EOF when reading torrent file fires only on zero-byte reads — EOF at a type indicator, inside an integer body, or within a length prefix; a string payload shorter than its declared length is silently accepted as a shorter value, with the position advanced by the declared length rather than raising, and can surface later as a hash-length mismatch or trailing-byte error. Positions are absolute offsets for the current pass.
  • Registration errors: a non-str hash-field name or a non-(int, bool) two-tuple value raises ValueError at construction or hash_field() time — not InvalidTorrentDataException.
  • Text-mode file objects are unsupported (bytes/str mismatch); open files with 'rb'.

Usage example

import collections
from torrent_parser import TorrentFileParser, parse_torrent_file

data = parse_torrent_file('real.torrent', use_ordered_dict=True)
assert isinstance(data, collections.OrderedDict)
data['pieces']  # list of 40-char hex strings via default hash field

with open('real.torrent', 'rb') as fp:   # binary mode required
    parser = TorrentFileParser(fp)
    parser.hash_field('info_hash')       # chain before parse()
    first = parser.parse()               # seeks to 0 first
    second = parser.parse()              # repeatable unless an 'encoding' key leaked

Node: Torrent file creation and round-trip editing

Functional constraints

  • TorrentFileCreator: constructed from the data to write plus optional encoding (default utf-8) and hash_fields. It keeps data by reference and encodes on demand, so edits made after construction are visible to later output calls. The parser's default hash-field names (pieces, ed2k, filehash, pieces root) are always registered on the underlying encoder; an explicit hash_fields argument adds further names on top of them (mirroring the parse side, which also merges user-supplied fields with the defaults), so custom registration only ever needs to supply the extra field names.
  • hash_field(name): adds one field name to the underlying encoder's hash-field registry, on top of the always-registered defaults; applies to output generated after the call, so call it before the first create/create_filelike.
  • create_filelike(): returns the full BEncoded document as a binary stream with its read position at the start; .read() yields the bytes. Encoding and unsupported-type failures surface here, not at construction.
  • create(filename): writes the same bytes to filename in binary mode, creating or truncating the file. The parent directory must already exist.
  • create_torrent_file: one-shot wrapper that takes the target filename and the data (plus the same optional encoding/hash_fields), constructs a creator, and calls create.

Behavioral constraints for re-implementation

  • The emitted document is standard BEncode: i<int>e for ints, <len>:<bytes> for strings, l...e for lists, d...e for dicts, produced by recursion over the data.
  • str values and dict keys are encoded with encoding; bytes values are emitted verbatim. Registered hash-field values must be hex strings or lists of even-length hex strings; each element is unhexified and the concatenation of the resulting bytes is emitted, which is what reproduces the original raw payload byte-for-byte.
  • No structural validation, no key sorting, no default values injected: dict iteration order defines output order, and missing announce/info keys are not an error.
  • Round-trip guarantee (default settings): decoding the bytes produced by create_filelike returns data equal to the input, and hash fields re-emit their original bytes because their names are pre-registered (each hex element is unhexified and the results concatenated); custom parse-side hash fields must be registered on the create side too, supplying only the extra names since the defaults are always present.
  • Characters not representable in encoding raise UnicodeEncodeError when output is produced.
  • Unsupported value types, and dict keys that are neither str nor bytes, raise InvalidTorrentDataException naming the offending type when output is produced.

Usage example (read, edit, write back)

import torrent_parser as tp

data = tp.parse_torrent_file('in.torrent')      # read side
data['announce'] = 'http://tracker.example.com/announce'
data['comment'] = 'edited'

tp.create_torrent_file('out.torrent', data)     # one-shot write-back

creator = tp.TorrentFileCreator(data)           # reusable configured writer
creator.hash_field('my_hash')                   # adds to the always-registered defaults
blob = creator.create_filelike().read()         # bytes in memory
with open('out2.torrent', 'wb') as f:
    f.write(blob)