import hashlib
import os
FILE_PATH = '/xxx.pdf' FILE_SIZE = 8669223
PIECE_INDEX = 132
PIECE_LENGTH = 65536
BLOCK_SIZE = 16384
def calculate_merkle_root():
start_offset = PIECE_INDEX * PIECE_LENGTH
remaining_size = FILE_SIZE - start_offset
print(f"Checking Piece {PIECE_INDEX}")
print(f"Piece Data Size: {remaining_size} bytes")
with open(FILE_PATH, 'rb') as f:
f.seek(start_offset)
data = f.read(remaining_size)
blocks = []
blocks.append(data[0:BLOCK_SIZE])
blocks.append(data[BLOCK_SIZE:])
print(f"Block 1 size: {len(blocks[0])} bytes")
print(f"Block 2 size: {len(blocks[1])} bytes")
leaf_hashes = [hashlib.sha256(b).digest() for b in blocks]
zero_hash = b'\x00' * 32
while len(leaf_hashes) < 4:
leaf_hashes.append(zero_hash)
print(f"Block {len(leaf_hashes)}: [PADDING - Zero Hash]")
node0 = hashlib.sha256(leaf_hashes[0] + leaf_hashes[1]).digest()
node1 = hashlib.sha256(leaf_hashes[2] + leaf_hashes[3]).digest()
merkle_root = hashlib.sha256(node0 + node1).digest()
print("-" * 30)
print(f"Calculated Merkle Root (Hex): {merkle_root.hex()}")
print("-" * 30)
print("Compare this hex string with the last 32 bytes of the 'piece layers' in your .torrent file.")
if __name__ == "__main__":
if os.path.exists(FILE_PATH):
calculate_merkle_root()
else:
print("File not found.")