diff --git a/backend/handler/filesystem/roms_handler.py b/backend/handler/filesystem/roms_handler.py index 24df43780..87a6ded8e 100644 --- a/backend/handler/filesystem/roms_handler.py +++ b/backend/handler/filesystem/roms_handler.py @@ -414,9 +414,6 @@ class FSRomsHandler(FSHandler): crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread( self._calculate_rom_hashes, Path(f_path, file_name), - 0, - hashlib.md5(usedforsecurity=False), - hashlib.sha1(usedforsecurity=False), ) except zlib.error: crc_c = 0 @@ -545,20 +542,19 @@ class FSRomsHandler(FSHandler): ) elif hashable_platform: try: - crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = ( - await asyncio.to_thread( - self._calculate_rom_hashes, - Path(abs_fs_path, rom.fs_name), - rom_crc_c, - rom_md5_h, - rom_sha1_h, - ) + crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread( + self._calculate_rom_hashes, + Path(abs_fs_path, rom.fs_name), ) except zlib.error: crc_c = 0 md5_h = hashlib.md5(usedforsecurity=False) sha1_h = hashlib.sha1(usedforsecurity=False) + # A single-file ROM spans exactly one file, so its ROM-level hashes + # are that file's hashes. + rom_crc_c, rom_md5_h, rom_sha1_h = crc_c, md5_h, sha1_h + # Calculate the RA hash if the platform has a slug that matches a known RA slug if calculate_hashes: ra_platform = meta_ra_handler.get_platform(rom.platform_slug) @@ -619,10 +615,17 @@ class FSRomsHandler(FSHandler): def _calculate_rom_hashes( self, file_path: Path, - rom_crc_c: int, - rom_md5_h: Any, - rom_sha1_h: Any, + rom_crc_c: int = 0, + rom_md5_h: Any = None, + rom_sha1_h: Any = None, ) -> tuple[int, int, Any, Any, Any, Any]: + """Hash one file, optionally folding its bytes into ROM-level accumulators. + + A ROM-level hash spans every top-level file of a multi-file ROM, so it + can only be built by feeding each file through a second set of hashers. + Callers that don't need one pass no accumulators, because a second pass + over a chunk costs as much as the first. + """ extension = Path(file_path).suffix.lower() try: file_type = detect_mime_type(file_path) @@ -630,18 +633,19 @@ class FSRomsHandler(FSHandler): crc_c = 0 md5_h = hashlib.md5(usedforsecurity=False) sha1_h = hashlib.sha1(usedforsecurity=False) + accumulate = rom_md5_h is not None and rom_sha1_h is not None def update_hashes(chunk: bytes | bytearray): + nonlocal crc_c, rom_crc_c + md5_h.update(chunk) - rom_md5_h.update(chunk) - sha1_h.update(chunk) - rom_sha1_h.update(chunk) - - nonlocal crc_c crc_c = binascii.crc32(chunk, crc_c) - nonlocal rom_crc_c - rom_crc_c = binascii.crc32(chunk, rom_crc_c) + + if accumulate: + rom_md5_h.update(chunk) + rom_sha1_h.update(chunk) + rom_crc_c = binascii.crc32(chunk, rom_crc_c) if extension == ".zip" or file_type == "application/zip": for chunk in read_zip_file(file_path): diff --git a/backend/tests/handler/filesystem/test_roms_handler.py b/backend/tests/handler/filesystem/test_roms_handler.py index b58bd46b3..04f5d2b8a 100644 --- a/backend/tests/handler/filesystem/test_roms_handler.py +++ b/backend/tests/handler/filesystem/test_roms_handler.py @@ -1,3 +1,4 @@ +import hashlib import os import shutil import tempfile @@ -480,6 +481,54 @@ class TestFSRomsHandler: assert rom_file.file_size_bytes > 0 assert rom_file.last_modified is not None + @pytest.mark.asyncio + async def test_get_rom_files_single_rom_hashes_match_its_only_file( + self, handler: FSRomsHandler, rom_single, config + ): + """A single-file ROM's hashes are its one file's hashes. + + The ROM-level values reuse that file's hashers instead of streaming the + same bytes through a second set, so pin the identity that allows it. + """ + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + m.setattr("os.path.exists", lambda x: False) + + parsed_rom_files = await handler.get_rom_files(rom_single) + + assert len(parsed_rom_files.rom_files) == 1 + only_file = parsed_rom_files.rom_files[0] + assert parsed_rom_files.crc_hash == only_file.crc_hash + assert parsed_rom_files.md5_hash == only_file.md5_hash + assert parsed_rom_files.sha1_hash == only_file.sha1_hash + + @pytest.mark.asyncio + async def test_get_rom_files_multi_rom_hash_spans_every_part( + self, handler: FSRomsHandler, rom_multi, config + ): + """A multi-file ROM hashes the concatenation of its top-level files. + + That composite cannot be derived from the per-file digests, so the parts + are streamed through a second set of hashers. Pin that it still covers + every part rather than collapsing to a single file's hash. + """ + with pytest.MonkeyPatch.context() as m: + m.setattr("handler.filesystem.roms_handler.cm.get_config", lambda: config) + m.setattr("os.path.exists", lambda x: False) + + parsed_rom_files = await handler.get_rom_files(rom_multi) + + rom_dir = Path(LIBRARY_BASE_PATH, "n64", "roms", rom_multi.fs_name) + expected_md5 = hashlib.md5(usedforsecurity=False) + for rom_file in parsed_rom_files.rom_files: + expected_md5.update((rom_dir / rom_file.file_name).read_bytes()) + + assert len(parsed_rom_files.rom_files) >= 2 + assert parsed_rom_files.md5_hash == expected_md5.hexdigest() + assert parsed_rom_files.md5_hash not in { + rom_file.md5_hash for rom_file in parsed_rom_files.rom_files + } + @pytest.mark.asyncio async def test_get_rom_files_multi_rom_multi_dot_exclusion( self, handler: FSRomsHandler, rom_multi