Created
September 13, 2021 01:42
-
-
Save Cartmanishere/2ce5d200ca94d410e94bd9639e3b1913 to your computer and use it in GitHub Desktop.
A python script to verify hash of torrent downloaded files
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This code is taken from: https://stackoverflow.com/a/2573715 | |
# Use python 2.7 | |
# Install Bencode package: https://pypi.org/project/BitTorrent-bencode/5.0.8/#files | |
# Usage: python torrent-verify.py <torrent-file> | |
import sys | |
import os | |
import hashlib | |
import bencode | |
import StringIO | |
def pieces_generator(info): | |
"""Yield pieces from download file(s).""" | |
piece_length = info['piece length'] | |
if 'files' in info: # yield pieces from a multi-file torrent | |
piece = "" | |
for file_info in info['files']: | |
path = os.sep.join([info['name']] + file_info['path']) | |
print(path) | |
sfile = open(path.decode('UTF-8'), "rb") | |
while True: | |
piece += sfile.read(piece_length-len(piece)) | |
if len(piece) != piece_length: | |
sfile.close() | |
break | |
yield piece | |
piece = "" | |
if piece != "": | |
yield piece | |
else: # yield pieces from a single file torrent | |
path = info['name'] | |
print(path) | |
sfile = open(path.decode('UTF-8'), "rb") | |
while True: | |
piece = sfile.read(piece_length) | |
if not piece: | |
sfile.close() | |
return | |
yield piece | |
def corruption_failure(): | |
"""Display error message and exit""" | |
print("download corrupted") | |
exit(1) | |
def main(): | |
# Open torrent file | |
torrent_file = open(sys.argv[1], "rb") | |
metainfo = bencode.bdecode(torrent_file.read()) | |
info = metainfo['info'] | |
pieces = StringIO.StringIO(info['pieces']) | |
# Iterate through pieces | |
for piece in pieces_generator(info): | |
print(piece) | |
# Compare piece hash with expected hash | |
piece_hash = hashlib.sha1(piece).digest() | |
if (piece_hash != pieces.read(20)): | |
corruption_failure() | |
# ensure we've read all pieces | |
if pieces.read(): | |
corruption_failure() | |
if __name__ == "__main__": | |
main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment