TorrentFile#
API and Source#
Torrent
Module#
torrentfile.
torrent
Classes and procedures pertaining to the creation of torrent meta files.
Classes#
-
TorrentFile
construct .torrent file. -
TorrentFileV2
construct .torrent v2 files using provided data. -
MetaFile
base class for all MetaFile classes.
Constants#
-
BLOCK_SIZE : int size of leaf hashes for merkle tree.
-
HASH_SIZE : int Length of a sha256 hash.
Bittorrent V2#
From Bittorrent.org Documentation pages.
Implementation details for Bittorrent Protocol v2.
Note
All strings in a .torrent file that contain text must be UTF-8 encoded.
Meta Version 2 Dictionary:#
-
“announce”: The URL of the tracker.
-
“info”: This maps to a dictionary, with keys described below.
-
“name”: A display name for the torrent. It is purely advisory.
-
“piece length”: The number of bytes that each logical piece in the peer protocol refers to. I.e. it sets the granularity of piece, request, bitfield and have messages. It must be a power of two and at least 6KiB.
-
“meta version”: An integer value, set to 2 to indicate compatibility with the current revision of this specification. Version 1 is not assigned to avoid confusion with BEP3. Future revisions will only increment this issue to indicate an incompatible change has been made, for example that hash algorithms were changed due to newly discovered vulnerabilities. Lementations must check this field first and indicate that a torrent is of a newer version than they can handle before performing other idations which may result in more general messages about invalid files. Files are mapped into this piece address space so that each non-empty
-
“file tree”: A tree of dictionaries where dictionary keys represent UTF-8 encoded path elements. Entries with zero-length keys describe the properties of the composed path at that point. ‘UTF-8 encoded’ context only means that if the native encoding is known at creation time it must be converted to UTF-8. Keys may contain invalid UTF-8 sequences or characters and names that are reserved on specific filesystems. Implementations must be prepared to sanitize them. On platforms path components exactly matching ‘.’ and ‘..’ must be sanitized since they could lead to directory traversal attacks and conflicting path descriptions. On platforms that require UTF-8 path components this sanitizing step must happen after normalizing overlong UTF-8 encodings. File is aligned to a piece boundary and occurs in same order as the file tree. The last piece of each file may be shorter than the specified piece length, resulting in an alignment gap.
-
“length”: Length of the file in bytes. Presence of this field indicates that the dictionary describes a file, not a directory. Which means it must not have any sibling entries.
-
“pieces root”: For non-empty files this is the the root hash of a merkle tree with a branching factor of 2, constructed from 16KiB blocks of the file. The last block may be shorter than 16KiB. The remaining leaf hashes beyond the end of the file required to construct upper layers of the merkle tree are set to zero. As of meta version 2 SHA2-256 is used as digest function for the merkle tree. The hash is stored in its binary form, not as human-readable string.
-
-
“piece layers”: A dictionary of strings. For each file in the file tree that is larger than the piece size it contains one string value. The keys are the merkle roots while the values consist of concatenated hashes of one layer within that merkle tree. The layer is chosen so that one hash covers piece length bytes. For example if the piece size is 16KiB then the leaf hashes are used. If a piece size of 128KiB is used then 3rd layer up from the leaf hashes is used. Layer hashes which exclusively cover data beyond the end of file, i.e. are only needed to balance the tree, are omitted. All hashes are stored in their binary format. A torrent is not valid if this field is absent, the contained hashes do not match the merkle roots or are not from the correct layer.
Important
The file tree root dictionary itself must not be a file, i.e. it must not contain a zero-length key with a dictionary containing a length key.
Bittorrent V1#
v1 meta-dictionary#
-
announce: The URL of the tracker.
-
info: This maps to a dictionary, with keys described below.
-
name
: maps to a UTF-8 encoded string which is the suggested name to save the file (or directory) as. It is purely advisory. -
piece length
: maps to the number of bytes in each piece the file is split into. For the purposes of transfer, files are split into fixed-size pieces which are all the same length except for possibly the last one which may be truncated. -
piece length
: is almost always a power of two, most commonly 2^18 = 256 K -
pieces
: maps to a string whose length is a multiple of 20. It is to be subdivided into strings of length 20, each of which is the SHA1 hash of the piece at the corresponding index. -
length
: In the single file case, maps to the length of the file in bytes. -
files
: If present then the download represents a single file, otherwise it represents a set of files which go in a directory structure. For the purposes of the other keys, the multi-file case is treated as only having a single file by concatenating the files in the order they appear in the files list. The files list is the valuefiles
maps to, and is a list of dictionaries containing the following keys:-
path
: A list of UTF-8 encoded strings corresponding to subdirectory names, the last of which is the actual file name -
length
: Maps to the length of the file in bytes.
-
-
length
: Only present if the content is a single file. Maps to the length of the file in bytes.
-
Note
In the single file case, the name key is the name of a file, in the muliple file case, it’s the name of a directory.
MetaFile
— Base Class for all TorrentFile classes.TorrentFile
— Class for creating Bittorrent meta files.TorrentFileV2
— Class for creating Bittorrent meta v2 files.TorrentFileHybrid
— Construct the Hybrid torrent meta file with provided parameters.TorrentAssembler
— Assembler class for Bittorrent version 2 and hybrid meta files.
Utils
Module#
torrentfile.
utils
Utility functions and classes used throughout package.
Memo
— Memoize cache.MissingPathError
— Path parameter is required to specify target content.PieceLengthValueError
— Piece Length parameter must equal a perfect power of 2.ArgumentError
— Exception for mismatched or mistyped CLI arguments.
check_path_writable
(
path
)
(bool) — Test if output path is writable.colored
(
string
,key
)
(str) — Output terminal content with formatting.copypath
(
source
,dest
)
— Copy the file located at source to dest.debug_is_on
(
)
(bool) — Return True if debug mode is on in environment variables.get_file_list
(
path
)
(list :) — Return a sorted list of file paths contained in directory.get_piece_length
(
size
)
(int) — Calculate the ideal piece length for bittorrent data.green
(
string
)
(str) — Output terminal content in green color.humanize_bytes
(
amount
)
(str) — Convert integer into human readable memory sized denomination.next_power_2
(
value
)
(int) — Calculate the next perfect power of 2 equal to or greater than value.normalize_piece_length
(
piece_length
)
(int) — Verify input piece_length is valid and convert accordingly.path_piece_length
(
path
)
(int) — Calculate piece length for input path and contents.path_size
(
path
)
(int) — Return the total size of all files in path recursively.path_stat
(
path
)
(Tuple[list, int, int] :) — Calculate directory statistics.toggle_debug_mode
(
switch_on
)
— Switch the environment variable debug indicator on or off.
Edit
Module#
torrentfile.
edit
Edit torrent module.
Provides a facility by which certain properties of a torrent meta file can be edited by the user. The various command line arguments indicate which fields should be edited, and what the new value should be. Depending on what fields are chosen to edit, this command can trigger a new info hash which means the torrent will no longer be able to participate in the same swarm as the original unedited torrent.
edit_torrent
(
metafile
,args
)
(dict) — Edit the properties and values in a torrent meta file.filter_empty
(
args
,meta
,info
)
— Remove the fields that were not used by the original file creator.
Interactive
Module#
torrentfile.
interactive
Module contains the procedures used for Interactive Mode.
This module has been deprecated.#
InteractiveEditor
— Interactive dialog class for torrent editing.InteractiveCreator
— Class namespace for interactive program options.
create_torrent
(
)
— Create new torrent file interactively.edit_action
(
)
— Edit the editable values of the torrent meta file.get_input
(
*args
)
(str) — Determine appropriate input function to call.recheck_torrent
(
)
— Check torrent download completed percentage.select_action
(
)
— Operate TorrentFile program interactively through terminal.showcenter
(
txt
)
— Print text to screen in the center position of the terminal.showtext
(
txt
)
— Print contents of txt to screen.
CLI
Module#
torrentfile.
cli
Command Line Interface for TorrentFile project.
This module provides the primary command line argument parser for the torrentfile package. The main_script function is automatically invoked when called from command line, and parses accompanying arguments.
Functions#
main_script : process command line arguments and run program. activate_logger : turns on debug mode and logging facility.
Classes#
Config : class controls logging configuration TorrentFileHelpFormatter : HelpFormatter the command line help message formatter
Config
— Class the controls the logging configuration and output settings.TorrentFileHelpFormatter
— Formatting class for help tips provided by the CLI.
execute
(
args
)
(list) — Execute program with provided list of arguments.execute
(
args
)
(list) — Execute program with provided list of arguments.main
(
)
— Initiate main function for CLI script.
Recheck
Module#
torrentfile.
recheck
Module container Checker Class.
The CheckerClass takes a torrentfile and tha path to it’s contents. It will then iterate through every file and directory contained and compare their data to values contained within the torrent file. Completion percentages will be printed to screen for each file and at the end for the torrentfile as a whole.
Checker
— Check a given file or directory to see if it matches a torrentfile.FeedChecker
— Validates torrent content.HashChecker
— Iterate through contents of meta data and verify with file contents.
Hasher
Module#
torrentfile.
hasher
Piece/File Hashers for Bittorrent meta file contents.
Hasher
— Piece hasher for Bittorrent V1 files.HasherV2
— Calculate the root hash and piece layers for file contents.HasherHybrid
— Calculate root and piece hashes for creating hybrid torrent file.FileHasher
— Calculate root and piece hashes for creating hybrid torrent file.
merkle_root
(
blocks
)
(bytes) — Calculate the merkle root for a seq of sha256 hash digests.