Coverage for src/romfarmer/core/hashing.py: 29%
101 statements
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
« prev ^ index » next coverage.py v7.15.4, created at 2026-09-01 23:08 -0700
1"""
2Centralized ROM hashing utilities for metadata matching.
4This module provides the canonical implementation of ROM hashing for use
5throughout rom-farmer. The hashing strategy varies by system type:
7ARCADE SYSTEMS (FBNeo, MAME, Naomi, Atomiswave, Model2, Model3, etc.):
8 - Hash the ZIP/7z file itself (not the contents)
9 - This matches ARRM's behavior for arcade ROMs
10 - Arcade ROMs are multi-file archives that are hashed as a unit
12DISC-BASED SYSTEMS (CHD, ISO, CUE/BIN, etc.):
13 - Hash the file contents directly
14 - For compressed disc images, hash the compressed file
16CARTRIDGE-BASED SYSTEMS (NES, SNES, Genesis, etc.):
17 - For uncompressed ROMs: hash the file contents
18 - For ZIP/7z archives: extract largest file and hash its contents
19 - This matches ARRM's behavior (it hashes the ROM inside the archive)
21This matches the documented behavior in README.md under "ARRM Hashing Behavior".
22"""
24import hashlib
25import zipfile
26from dataclasses import dataclass
27from enum import Enum, auto
28from pathlib import Path
30import py7zr
33class HashingStrategy(Enum):
34 """Strategy for hashing a ROM file."""
36 # Hash the archive file itself (arcade systems)
37 ARCHIVE_AS_FILE = auto()
39 # Hash contents of the largest file inside archive
40 ARCHIVE_CONTENTS = auto()
42 # Hash the file directly
43 DIRECT = auto()
46@dataclass
47class HashResult:
48 """Result of hashing a ROM file."""
50 md5: str
51 sha1: str | None = None
52 crc32: str | None = None
53 strategy_used: HashingStrategy = HashingStrategy.DIRECT
54 inner_filename: str | None = None # For archive contents, the file that was hashed
57# Systems that hash the archive file itself (not contents)
58# These are arcade/MAME-style systems where the ZIP contains multiple ROM chips
59ARCADE_SYSTEMS = frozenset(
60 {
61 # Core arcade
62 "fbneo",
63 "fba", # Legacy name
64 "finalburn", # Legacy name
65 "mame",
66 "hbmame",
67 # MAME-derived arcade platforms
68 "naomi",
69 "naomigd",
70 "naomi2",
71 "atomiswave",
72 "triforce",
73 "hikaru",
74 "chihiro",
75 "gaelco",
76 "stv", # Sega ST-V
77 "model2",
78 "model3",
79 "system246",
80 "taito_type_x",
81 "lindbergh",
82 "ringedge",
83 "examu",
84 # Neo Geo (arcade mode)
85 "neogeo",
86 "neogeocd", # When using MAME/FBNeo
87 # Other arcade
88 "daphne",
89 "singe",
90 }
91)
93# File extensions that are always hashed directly (never extract)
94DIRECT_HASH_EXTENSIONS = frozenset(
95 {
96 # Disc images
97 ".chd",
98 ".iso",
99 ".cue",
100 ".bin",
101 ".img",
102 ".mdf",
103 ".nrg",
104 ".gdi",
105 ".cdi",
106 ".rvz",
107 ".wbfs",
108 ".wia",
109 ".gcz",
110 ".ciso",
111 ".wux", # Wii U
112 ".rpx", # Wii U
113 # Uncompressed ROMs
114 ".nes",
115 ".sfc",
116 ".smc",
117 ".gb",
118 ".gbc",
119 ".gba",
120 ".nds",
121 ".3ds",
122 ".cia",
123 ".n64",
124 ".z64",
125 ".v64",
126 ".md",
127 ".smd",
128 ".gen",
129 ".32x",
130 ".gg",
131 ".sms",
132 ".sg",
133 ".pce",
134 ".ngp",
135 ".ngc",
136 ".ws",
137 ".wsc",
138 ".a26",
139 ".a52",
140 ".a78",
141 ".lnx",
142 ".jag",
143 ".j64",
144 ".vec",
145 ".col",
146 ".int",
147 ".xex",
148 ".atr",
149 ".tap",
150 ".tzx",
151 ".dsk",
152 ".d64",
153 ".t64",
154 ".crt",
155 ".prg",
156 ".vb",
157 # Already "final form" compressed
158 ".pbp", # PSP EBOOT
159 ".pkg", # PS3/PSP packages
160 ".nsz", # Switch compressed
161 ".nsp", # Switch package
162 ".xci", # Switch cartridge
163 ".vpk", # PS Vita
164 }
165)
168def is_arcade_system(system_name: str) -> bool:
169 """
170 Check if a system uses arcade-style hashing (hash archive, not contents).
172 Args:
173 system_name: System identifier (e.g., 'fbneo', 'mame', 'naomi')
175 Returns:
176 True if this system hashes the archive file itself
177 """
178 if not system_name:
179 return False
180 return system_name.lower().strip() in ARCADE_SYSTEMS
183def get_hashing_strategy(
184 file_path: Path,
185 system_name: str | None = None,
186) -> HashingStrategy:
187 """
188 Determine the appropriate hashing strategy for a file.
190 Args:
191 file_path: Path to the ROM file
192 system_name: System identifier for context (optional)
194 Returns:
195 HashingStrategy indicating how to hash the file
196 """
197 suffix = file_path.suffix.lower()
199 # Check for arcade systems first
200 if system_name and is_arcade_system(system_name):
201 # Arcade systems hash the archive file itself
202 if suffix in (".zip", ".7z"):
203 return HashingStrategy.ARCHIVE_AS_FILE
204 # Non-archive arcade files (CHD companions) hash directly
205 return HashingStrategy.DIRECT
207 # Non-archive files always hash directly
208 if suffix in DIRECT_HASH_EXTENSIONS:
209 return HashingStrategy.DIRECT
211 # Archives on non-arcade systems extract and hash contents
212 if suffix in (".zip", ".7z"):
213 return HashingStrategy.ARCHIVE_CONTENTS
215 # Default to direct hashing
216 return HashingStrategy.DIRECT
219def calculate_md5(
220 file_path: Path,
221 system_name: str | None = None,
222 chunk_size: int = 8192,
223) -> str:
224 """
225 Calculate MD5 hash of a ROM file using the appropriate strategy.
227 This is the primary entry point for ROM hashing. It automatically
228 determines the correct hashing strategy based on system type and
229 file format.
231 Args:
232 file_path: Path to the ROM file
233 system_name: System identifier for context (e.g., 'fbneo', 'nes')
234 chunk_size: Size of chunks for reading large files
236 Returns:
237 MD5 hash as lowercase hex string
238 """
239 result = calculate_hash(file_path, system_name, include_sha1=False, chunk_size=chunk_size)
240 return result.md5
243def calculate_hash(
244 file_path: Path,
245 system_name: str | None = None,
246 include_sha1: bool = True,
247 chunk_size: int = 8192,
248) -> HashResult:
249 """
250 Calculate hash(es) of a ROM file using the appropriate strategy.
252 This function determines the correct hashing approach based on:
253 1. System type (arcade systems hash archive files)
254 2. File extension (some files always hash directly)
255 3. Archive format (ZIP vs 7z vs plain file)
257 Args:
258 file_path: Path to the ROM file
259 system_name: System identifier for context (e.g., 'fbneo', 'nes')
260 include_sha1: Whether to calculate SHA1 in addition to MD5
261 chunk_size: Size of chunks for reading large files
263 Returns:
264 HashResult with MD5 (and optionally SHA1) hash
265 """
266 strategy = get_hashing_strategy(file_path, system_name)
268 if strategy == HashingStrategy.ARCHIVE_AS_FILE:
269 return _hash_file_direct(file_path, include_sha1, chunk_size, strategy)
271 elif strategy == HashingStrategy.ARCHIVE_CONTENTS:
272 suffix = file_path.suffix.lower()
273 if suffix == ".zip":
274 return _hash_zip_contents(file_path, include_sha1, chunk_size)
275 elif suffix == ".7z":
276 return _hash_7z_contents(file_path, include_sha1, chunk_size)
277 # Fallback to direct if not recognized archive
278 return _hash_file_direct(file_path, include_sha1, chunk_size, HashingStrategy.DIRECT)
280 else: # HashingStrategy.DIRECT
281 return _hash_file_direct(file_path, include_sha1, chunk_size, strategy)
284def _hash_file_direct(
285 file_path: Path,
286 include_sha1: bool,
287 chunk_size: int,
288 strategy: HashingStrategy,
289) -> HashResult:
290 """Hash a file directly (not extracting any contents)."""
291 md5 = hashlib.md5()
292 sha1 = hashlib.sha1() if include_sha1 else None
294 with open(file_path, "rb") as f:
295 while chunk := f.read(chunk_size):
296 md5.update(chunk)
297 if sha1:
298 sha1.update(chunk)
300 return HashResult(
301 md5=md5.hexdigest(),
302 sha1=sha1.hexdigest() if sha1 else None,
303 strategy_used=strategy,
304 )
307def _hash_zip_contents(
308 zip_path: Path,
309 include_sha1: bool,
310 chunk_size: int,
311) -> HashResult:
312 """Extract and hash the largest file inside a ZIP archive."""
313 try:
314 with zipfile.ZipFile(zip_path, "r") as zf:
315 # Get list of files (not directories)
316 files = [f for f in zf.namelist() if not f.endswith("/")]
318 if not files:
319 # Empty archive - hash the file itself
320 return _hash_file_direct(
321 zip_path, include_sha1, chunk_size, HashingStrategy.ARCHIVE_AS_FILE
322 )
324 # Find the largest file (most likely the actual ROM)
325 largest_file = max(files, key=lambda f: zf.getinfo(f).file_size)
327 # Read and hash
328 rom_data = zf.read(largest_file)
329 md5 = hashlib.md5(rom_data).hexdigest()
330 sha1 = hashlib.sha1(rom_data).hexdigest() if include_sha1 else None
332 return HashResult(
333 md5=md5,
334 sha1=sha1,
335 strategy_used=HashingStrategy.ARCHIVE_CONTENTS,
336 inner_filename=largest_file,
337 )
339 except (OSError, zipfile.BadZipFile):
340 # Corrupted or invalid archive - hash file itself
341 return _hash_file_direct(
342 zip_path, include_sha1, chunk_size, HashingStrategy.ARCHIVE_AS_FILE
343 )
346def _hash_7z_contents(
347 archive_path: Path,
348 include_sha1: bool,
349 chunk_size: int,
350) -> HashResult:
351 """Extract and hash the largest file inside a 7z archive."""
352 import tempfile
354 try:
355 with py7zr.SevenZipFile(archive_path, mode="r") as zf:
356 # Get file info
357 file_infos = [(f.filename, f.uncompressed) for f in zf.list() if not f.is_directory]
359 if not file_infos:
360 # Empty archive - hash the file itself
361 return _hash_file_direct(
362 archive_path, include_sha1, chunk_size, HashingStrategy.ARCHIVE_AS_FILE
363 )
365 # Find the largest file
366 largest_file = max(file_infos, key=lambda x: x[1])[0]
368 # Extract to temp directory (py7zr 1.0+ API)
369 with tempfile.TemporaryDirectory() as tmpdir:
370 zf.extract(path=tmpdir, targets=[largest_file])
371 extracted_path = Path(tmpdir) / largest_file
372 rom_data = extracted_path.read_bytes()
374 md5 = hashlib.md5(rom_data).hexdigest()
375 sha1 = hashlib.sha1(rom_data).hexdigest() if include_sha1 else None
377 return HashResult(
378 md5=md5,
379 sha1=sha1,
380 strategy_used=HashingStrategy.ARCHIVE_CONTENTS,
381 inner_filename=largest_file,
382 )
384 except Exception:
385 # Any error - fallback to direct hash
386 return _hash_file_direct(
387 archive_path, include_sha1, chunk_size, HashingStrategy.ARCHIVE_AS_FILE
388 )
391def hash_for_metadata_lookup(
392 file_path: Path,
393 system_name: str | None = None,
394) -> str:
395 """
396 Get the MD5 hash for metadata database lookup.
398 This is a convenience function that's semantically clear about
399 the purpose - matching against the metadata database.
401 Args:
402 file_path: Path to the ROM file
403 system_name: System identifier for context
405 Returns:
406 MD5 hash suitable for database lookup
407 """
408 return calculate_md5(file_path, system_name)
411def detect_system_from_path(file_path: Path) -> str | None:
412 """
413 Attempt to detect the system from a file path.
415 Looks for common system folder names in the path hierarchy.
416 This is a heuristic fallback when system name isn't provided.
418 Args:
419 file_path: Path to analyze
421 Returns:
422 Detected system name or None
423 """
424 path_lower = str(file_path).lower()
426 # Check each arcade system
427 for system in ARCADE_SYSTEMS:
428 if f"/{system}/" in path_lower or f"\\{system}\\" in path_lower:
429 return system
430 if path_lower.endswith(f"/{system}") or path_lower.endswith(f"\\{system}"):
431 return system
433 return None
436def calculate_md5_with_auto_detect(file_path: Path) -> str:
437 """
438 Calculate MD5 with automatic system detection from path.
440 Use this when the system isn't known but might be inferrable
441 from the file path (e.g., /roms/fbneo/kinst.zip).
443 Args:
444 file_path: Path to the ROM file
446 Returns:
447 MD5 hash as lowercase hex string
448 """
449 system = detect_system_from_path(file_path)
450 return calculate_md5(file_path, system)