mirror of
https://github.com/rommapp/romm.git
synced 2026-12-05 05:07:31 +01:00
feat(hashing): compute raw CHD hashes and route disc-data SHA1 to Hasheous
CHD files now follow the same hash logic as all other file types — CRC32, MD5, and SHA1 are computed from raw container bytes. This allows ScreenScraper to log KO entries for unrecognised CHD files, which it could not do when only the disc-data SHA1 was being computed. The CHD header SHA1 (disc-data SHA1) is separately extracted and stored in a new chd_sha1_hash field on RomFile, with a migration adding the column to rom_files. Hasheous receives only this disc-data SHA1 (no CRC/MD5) since it indexes disc-based games by disc-data SHA1, not raw file hashes. The RAHasher multi-file path now passes the largest CHD directly instead of a /* wildcard, which RAHasher cannot expand. Hash computations are wrapped in asyncio.to_thread to avoid blocking the event loop during large reads. Hash-lookup metadata handlers (ScreenScraper, Hasheous, Playmatch) now fall back to rom.files (stored DB hashes) when fs_rom files are not rehashed, fixing hash-based matching for UNMATCHED and UPDATE scan types. The Disc SHA-1 is displayed in the ROM detail view for both single-file (FileInfo.vue) and multi-file (FileSelectItem.vue) CHD games.
This commit is contained in:
28
backend/alembic/versions/0080_add_chd_sha1_hash.py
Normal file
28
backend/alembic/versions/0080_add_chd_sha1_hash.py
Normal file
@@ -0,0 +1,28 @@
|
||||
"""Add chd_sha1_hash to rom_files
|
||||
|
||||
Revision ID: 0080_add_chd_sha1_hash
|
||||
Revises: 0079_add_rom_files_rom_id_index
|
||||
Create Date: 2026-04-24 00:00:00.000000
|
||||
|
||||
"""
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision = "0080_add_chd_sha1_hash"
|
||||
down_revision = "0079_add_rom_files_rom_id_index"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.add_column(
|
||||
sa.Column("chd_sha1_hash", sa.String(length=100), nullable=True),
|
||||
if_not_exists=True,
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
with op.batch_alter_table("rom_files", schema=None) as batch_op:
|
||||
batch_op.drop_column("chd_sha1_hash", if_exists=True)
|
||||
@@ -163,6 +163,7 @@ class RomFileSchema(BaseModel):
|
||||
md5_hash: str | None
|
||||
sha1_hash: str | None
|
||||
ra_hash: str | None
|
||||
chd_sha1_hash: str | None
|
||||
category: RomFileCategory | None
|
||||
|
||||
|
||||
|
||||
@@ -347,6 +347,7 @@ async def _identify_rom(
|
||||
md5_hash=file.md5_hash,
|
||||
sha1_hash=file.sha1_hash,
|
||||
ra_hash=file.ra_hash,
|
||||
chd_sha1_hash=file.chd_sha1_hash,
|
||||
)
|
||||
for file in fs_rom["files"]
|
||||
]
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import asyncio
|
||||
import binascii
|
||||
import bz2
|
||||
import fnmatch
|
||||
@@ -10,7 +11,7 @@ import zlib
|
||||
from collections.abc import Callable, Iterator
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
from typing import IO, Any, Final, Literal, TypedDict, cast
|
||||
from typing import IO, Any, Final, Literal, TypedDict
|
||||
|
||||
import magic
|
||||
import zipfile_inflate64 # trunk-ignore(ruff/F401): Patches zipfile to support Enhanced Deflate
|
||||
@@ -114,6 +115,7 @@ class FileHash(TypedDict):
|
||||
crc_hash: str
|
||||
md5_hash: str
|
||||
sha1_hash: str
|
||||
chd_sha1_hash: str
|
||||
|
||||
|
||||
def is_compressed_file(file_path: str) -> bool:
|
||||
@@ -247,34 +249,6 @@ def extract_chd_hash(file_path: Path) -> str | None:
|
||||
return None
|
||||
|
||||
|
||||
class CHDHashWrapper:
|
||||
"""
|
||||
Wrapper class that mimics hashlib hash objects but returns a pre-computed hash.
|
||||
|
||||
This class provides a hashlib-compatible interface for pre-computed hashes
|
||||
extracted from CHD v5 file headers. It implements the same methods and attributes
|
||||
as hashlib hash objects (digest(), hexdigest(), update(), and name).
|
||||
"""
|
||||
|
||||
def __init__(self, hash_hex: str, name: str):
|
||||
self.hash_hex = hash_hex
|
||||
self.name = name
|
||||
# Store the digest as bytes
|
||||
self._digest = bytes.fromhex(hash_hex)
|
||||
|
||||
def hexdigest(self) -> str:
|
||||
"""Return the hash as a hexadecimal string."""
|
||||
return self.hash_hex
|
||||
|
||||
def digest(self) -> bytes:
|
||||
"""Return the hash as bytes."""
|
||||
return self._digest
|
||||
|
||||
def update(self, data: bytes | bytearray) -> None:
|
||||
"""No-op update method for compatibility with hashlib interface."""
|
||||
pass
|
||||
|
||||
|
||||
def category_matches(category: str, path_parts: list[str]):
|
||||
return category in path_parts or f"{category}s" in path_parts
|
||||
|
||||
@@ -414,6 +388,7 @@ class FSRomsHandler(FSHandler):
|
||||
crc_hash=file_hash["crc_hash"],
|
||||
md5_hash=file_hash["md5_hash"],
|
||||
sha1_hash=file_hash["sha1_hash"],
|
||||
chd_sha1_hash=file_hash["chd_sha1_hash"] or None,
|
||||
)
|
||||
|
||||
async def get_rom_files(
|
||||
@@ -448,9 +423,28 @@ class FSRomsHandler(FSHandler):
|
||||
if calculate_hashes:
|
||||
ra_platform = meta_ra_handler.get_platform(rom.platform_slug)
|
||||
if ra_platform and ra_platform["ra_id"]:
|
||||
rom_dir = Path(abs_fs_path, rom.fs_name)
|
||||
# RAHasher can't process CHD files via the /* wildcard — it expects
|
||||
# track files (bin/cue/etc.). For CHD-only folders, find the largest
|
||||
# CHD and pass it directly, matching single-file CHD behaviour.
|
||||
|
||||
def _list_chd_by_size() -> list[Path]:
|
||||
chds = [
|
||||
f for f in rom_dir.iterdir() if f.suffix.lower() == ".chd"
|
||||
]
|
||||
return sorted(
|
||||
chds, key=lambda f: f.stat().st_size, reverse=True
|
||||
)
|
||||
|
||||
chd_files = await asyncio.to_thread(_list_chd_by_size)
|
||||
ra_path = (
|
||||
str(chd_files[0])
|
||||
if chd_files
|
||||
else f"{abs_fs_path}/{rom.fs_name}/*"
|
||||
)
|
||||
rom_ra_h = await RAHasherService().calculate_hash(
|
||||
ra_platform,
|
||||
f"{abs_fs_path}/{rom.fs_name}/*",
|
||||
ra_path,
|
||||
)
|
||||
|
||||
for f_path, file_name in iter_files(
|
||||
@@ -478,7 +472,8 @@ class FSRomsHandler(FSHandler):
|
||||
if is_top_level:
|
||||
# Include this file in the main ROM hash calculation
|
||||
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
|
||||
self._calculate_rom_hashes(
|
||||
await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(f_path, file_name),
|
||||
rom_crc_c,
|
||||
rom_md5_h,
|
||||
@@ -487,7 +482,8 @@ class FSRomsHandler(FSHandler):
|
||||
)
|
||||
else:
|
||||
# Calculate individual file hash only
|
||||
crc_c, _, md5_h, _, sha1_h, _ = self._calculate_rom_hashes(
|
||||
crc_c, _, md5_h, _, sha1_h, _ = await asyncio.to_thread(
|
||||
self._calculate_rom_hashes,
|
||||
Path(f_path, file_name),
|
||||
0,
|
||||
hashlib.md5(usedforsecurity=False),
|
||||
@@ -498,6 +494,9 @@ class FSRomsHandler(FSHandler):
|
||||
md5_h = hashlib.md5(usedforsecurity=False)
|
||||
sha1_h = hashlib.sha1(usedforsecurity=False)
|
||||
|
||||
chd_sha1 = ""
|
||||
if Path(file_name).suffix.lower() == ".chd":
|
||||
chd_sha1 = extract_chd_hash(Path(f_path, file_name)) or ""
|
||||
file_hash = FileHash(
|
||||
crc_hash=crc32_to_hex(crc_c) if crc_c != DEFAULT_CRC_C else "",
|
||||
md5_hash=(
|
||||
@@ -510,12 +509,14 @@ class FSRomsHandler(FSHandler):
|
||||
if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
|
||||
else ""
|
||||
),
|
||||
chd_sha1_hash=chd_sha1,
|
||||
)
|
||||
else:
|
||||
file_hash = FileHash(
|
||||
crc_hash="",
|
||||
md5_hash="",
|
||||
sha1_hash="",
|
||||
chd_sha1_hash="",
|
||||
)
|
||||
|
||||
rom_files.append(
|
||||
@@ -529,8 +530,12 @@ class FSRomsHandler(FSHandler):
|
||||
elif hashable_platform:
|
||||
try:
|
||||
crc_c, rom_crc_c, md5_h, rom_md5_h, sha1_h, rom_sha1_h = (
|
||||
self._calculate_rom_hashes(
|
||||
Path(abs_fs_path, rom.fs_name), rom_crc_c, rom_md5_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,
|
||||
)
|
||||
)
|
||||
except zlib.error:
|
||||
@@ -547,6 +552,9 @@ class FSRomsHandler(FSHandler):
|
||||
f"{abs_fs_path}/{rom.fs_name}",
|
||||
)
|
||||
|
||||
chd_sha1 = ""
|
||||
if Path(rom.fs_name).suffix.lower() == ".chd":
|
||||
chd_sha1 = extract_chd_hash(Path(abs_fs_path, rom.fs_name)) or ""
|
||||
file_hash = FileHash(
|
||||
crc_hash=crc32_to_hex(crc_c) if crc_c != DEFAULT_CRC_C else "",
|
||||
md5_hash=(
|
||||
@@ -557,6 +565,7 @@ class FSRomsHandler(FSHandler):
|
||||
if sha1_h.digest() != DEFAULT_SHA1_H_DIGEST
|
||||
else ""
|
||||
),
|
||||
chd_sha1_hash=chd_sha1,
|
||||
)
|
||||
rom_files.append(
|
||||
self._build_rom_file(
|
||||
@@ -571,6 +580,7 @@ class FSRomsHandler(FSHandler):
|
||||
crc_hash="",
|
||||
md5_hash="",
|
||||
sha1_hash="",
|
||||
chd_sha1_hash="",
|
||||
)
|
||||
rom_files.append(
|
||||
self._build_rom_file(
|
||||
@@ -647,17 +657,6 @@ class FSRomsHandler(FSHandler):
|
||||
for chunk in read_bz2_file(file_path):
|
||||
update_hashes(chunk)
|
||||
|
||||
elif extension == ".chd" or file_type == "application/x-mame-chd":
|
||||
chd_hash = extract_chd_hash(file_path)
|
||||
if chd_hash:
|
||||
sha1_h = cast(Any, CHDHashWrapper(chd_hash, name="sha1"))
|
||||
rom_sha1_h = cast(Any, CHDHashWrapper(chd_hash, name="sha1"))
|
||||
else:
|
||||
# Not a valid v5 CHD, treat as basic file
|
||||
# This ensures CRC32 and MD5 are still calculated for non-v5 CHDs
|
||||
for chunk in read_basic_file(file_path):
|
||||
update_hashes(chunk)
|
||||
|
||||
else:
|
||||
for chunk in read_basic_file(file_path):
|
||||
update_hashes(chunk)
|
||||
|
||||
@@ -258,9 +258,16 @@ class HasheousHandler(MetadataHandler):
|
||||
if first_file is None:
|
||||
return fallback_rom
|
||||
|
||||
md5_hash = first_file.md5_hash
|
||||
sha1_hash = first_file.sha1_hash
|
||||
crc_hash = first_file.crc_hash
|
||||
if first_file.chd_sha1_hash:
|
||||
# For CHD files, Hasheous indexes by disc-data SHA1 only.
|
||||
# Raw file MD5/CRC are hashes of the container and won't match.
|
||||
md5_hash = None
|
||||
sha1_hash = first_file.chd_sha1_hash
|
||||
crc_hash = None
|
||||
else:
|
||||
md5_hash = first_file.md5_hash
|
||||
sha1_hash = first_file.sha1_hash
|
||||
crc_hash = first_file.crc_hash
|
||||
|
||||
if not (md5_hash or sha1_hash or crc_hash):
|
||||
log.warning(
|
||||
|
||||
@@ -385,7 +385,7 @@ async def scan_rom(
|
||||
or scan_type == ScanType.UNMATCHED
|
||||
)
|
||||
):
|
||||
return await meta_playmatch_handler.lookup_rom(fs_rom["files"])
|
||||
return await meta_playmatch_handler.lookup_rom(fs_rom["files"] or rom.files)
|
||||
|
||||
return PlaymatchRomMatch(
|
||||
igdb_id=None,
|
||||
@@ -418,7 +418,7 @@ async def scan_rom(
|
||||
)
|
||||
):
|
||||
return await meta_hasheous_handler.lookup_rom(
|
||||
platform.slug, fs_rom["files"]
|
||||
platform.slug, fs_rom["files"] or rom.files
|
||||
)
|
||||
|
||||
return HasheousRom(hasheous_id=None, igdb_id=None, tgdb_id=None, ra_id=None)
|
||||
@@ -635,7 +635,7 @@ async def scan_rom(
|
||||
|
||||
# Use the file hashes for lookup
|
||||
game_by_hash = await meta_ss_handler.lookup_rom(
|
||||
rom, platform.ss_id, fs_rom["files"]
|
||||
rom, platform.ss_id, fs_rom["files"] or rom.files
|
||||
)
|
||||
if game_by_hash.get("ss_id"):
|
||||
return game_by_hash
|
||||
|
||||
@@ -76,6 +76,7 @@ class RomFile(BaseModel):
|
||||
md5_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
sha1_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
ra_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
chd_sha1_hash: Mapped[str | None] = mapped_column(String(100))
|
||||
category: Mapped[RomFileCategory | None] = mapped_column(
|
||||
Enum(RomFileCategory), default=None
|
||||
)
|
||||
|
||||
@@ -7,7 +7,6 @@ import pytest
|
||||
|
||||
from config.config_manager import LIBRARY_BASE_PATH, Config
|
||||
from handler.filesystem.roms_handler import (
|
||||
CHDHashWrapper,
|
||||
FileHash,
|
||||
FSRomsHandler,
|
||||
extract_chd_hash,
|
||||
@@ -259,6 +258,7 @@ class TestFSRomsHandler:
|
||||
"crc_hash": "ABCD1234",
|
||||
"md5_hash": "def456",
|
||||
"sha1_hash": "789ghi",
|
||||
"chd_sha1_hash": "",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -284,6 +284,7 @@ class TestFSRomsHandler:
|
||||
"crc_hash": "12345678",
|
||||
"md5_hash": "abcdef",
|
||||
"sha1_hash": "123456",
|
||||
"chd_sha1_hash": "",
|
||||
}
|
||||
)
|
||||
|
||||
@@ -712,13 +713,11 @@ class TestFSRomsHandler:
|
||||
async def test_get_rom_files_with_chd_v5_uses_internal_hash(
|
||||
self, handler: FSRomsHandler, platform, tmp_path
|
||||
):
|
||||
"""Test that a CHD v5 file uses its internal hash and skips other hashing.
|
||||
"""Test that a CHD v5 file stores the header SHA1 in chd_sha1_hash.
|
||||
|
||||
This integration test verifies the complete CHD v5 hashing logic:
|
||||
1. For valid CHD v5 files, the embedded SHA1 hash from the file header is used
|
||||
2. CRC32 and MD5 hashes are NOT calculated from file contents
|
||||
3. The file is not double-processed by read_basic_file
|
||||
4. This prevents regressions in the if/elif archive type chain
|
||||
CHD files are hashed like any other file type (CRC32, MD5, SHA1 from
|
||||
raw bytes). The embedded disc-data SHA1 from the CHD v5 header is
|
||||
separately stored in chd_sha1_hash for metadata providers that need it.
|
||||
"""
|
||||
# Create a mock CHD v5 file in a temporary directory
|
||||
chd_file = tmp_path / "test.chd"
|
||||
@@ -751,22 +750,19 @@ class TestFSRomsHandler:
|
||||
# Run the hashing process
|
||||
parsed_rom_files = await test_handler.get_rom_files(rom)
|
||||
|
||||
# Assert that only SHA1 is populated, and it's from the header
|
||||
# All three raw-file hashes should be populated
|
||||
assert len(parsed_rom_files.rom_files) == 1
|
||||
assert parsed_rom_files.crc_hash != "", "CRC should be computed from raw bytes"
|
||||
assert parsed_rom_files.md5_hash != "", "MD5 should be computed from raw bytes"
|
||||
assert (
|
||||
parsed_rom_files.sha1_hash == internal_sha1
|
||||
), "SHA1 should be from CHD v5 header"
|
||||
assert parsed_rom_files.rom_files[0].sha1_hash == internal_sha1
|
||||
parsed_rom_files.sha1_hash != ""
|
||||
), "SHA1 should be computed from raw bytes"
|
||||
|
||||
# CRC32 and MD5 should be empty/zero (not calculated)
|
||||
assert (
|
||||
parsed_rom_files.crc_hash == ""
|
||||
), f"CRC hash should be empty, got: {parsed_rom_files.crc_hash}"
|
||||
assert (
|
||||
parsed_rom_files.md5_hash == ""
|
||||
), f"MD5 hash should be empty, got: {parsed_rom_files.md5_hash}"
|
||||
assert parsed_rom_files.rom_files[0].crc_hash == ""
|
||||
assert parsed_rom_files.rom_files[0].md5_hash == ""
|
||||
# Raw file SHA1 is NOT the header SHA1
|
||||
assert parsed_rom_files.sha1_hash != internal_sha1
|
||||
|
||||
# Header SHA1 stored separately in chd_sha1_hash
|
||||
assert parsed_rom_files.rom_files[0].chd_sha1_hash == internal_sha1
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_get_rom_files_with_non_v5_chd_fallback_to_std_hashing(
|
||||
@@ -975,28 +971,6 @@ class TestExtractCHDHash:
|
||||
# Verify it's 40 characters (SHA1 is 20 bytes = 40 hex chars)
|
||||
assert len(result) == 40
|
||||
|
||||
def test_extract_chd_hash_with_wrapper(self, tmp_path):
|
||||
"""Test that extracted hash integrates properly with CHDHashWrapper"""
|
||||
chd_file = tmp_path / "test_wrapper.chd"
|
||||
|
||||
header = bytearray(124)
|
||||
header[0:8] = b"MComprHD"
|
||||
header[12:16] = int(5).to_bytes(4, "big")
|
||||
test_sha1 = bytes.fromhex("0123456789abcdef0123456789abcdef01234567")
|
||||
header[84:104] = test_sha1
|
||||
|
||||
chd_file.write_bytes(header)
|
||||
|
||||
extracted_hash = extract_chd_hash(chd_file)
|
||||
assert extracted_hash is not None
|
||||
|
||||
# Should be usable with CHDHashWrapper
|
||||
wrapper = CHDHashWrapper(extracted_hash, "sha1")
|
||||
assert wrapper.hexdigest() == extracted_hash
|
||||
assert len(wrapper.digest()) == 20
|
||||
# Verify digest bytes match the original
|
||||
assert wrapper.digest() == test_sha1
|
||||
|
||||
def test_extract_chd_hash_unknown_version(self, tmp_path):
|
||||
"""Test that unknown CHD versions are rejected"""
|
||||
chd_file = tmp_path / "test_unknown.chd"
|
||||
|
||||
@@ -17,6 +17,7 @@ export type RomFileSchema = {
|
||||
md5_hash: (string | null);
|
||||
sha1_hash: (string | null);
|
||||
ra_hash: (string | null);
|
||||
chd_sha1_hash: (string | null);
|
||||
category: (RomFileCategory | null);
|
||||
};
|
||||
|
||||
|
||||
@@ -19,6 +19,12 @@ const romUser = ref(props.rom.rom_user);
|
||||
const romInfo = ref([
|
||||
{ label: "Size", value: formatBytes(props.rom.fs_size_bytes) },
|
||||
{ label: "SHA-1", value: props.rom.sha1_hash },
|
||||
{
|
||||
label: "Disc SHA-1",
|
||||
value: props.rom.has_simple_single_file
|
||||
? (props.rom.files[0]?.chd_sha1_hash ?? null)
|
||||
: null,
|
||||
},
|
||||
{ label: "MD5", value: props.rom.md5_hash },
|
||||
{ label: "CRC", value: props.rom.crc_hash },
|
||||
{ label: "Revision", value: props.rom.revision },
|
||||
|
||||
@@ -20,6 +20,14 @@ const fileInfo = ref([
|
||||
props.item.sha1_hash.substring(props.item.sha1_hash.length - 6)
|
||||
: null,
|
||||
},
|
||||
{
|
||||
label: "Disc SHA-1",
|
||||
value: props.item.chd_sha1_hash
|
||||
? props.item.chd_sha1_hash.substring(0, 6) +
|
||||
"..." +
|
||||
props.item.chd_sha1_hash.substring(props.item.chd_sha1_hash.length - 6)
|
||||
: null,
|
||||
},
|
||||
{
|
||||
label: "MD5",
|
||||
value: props.item.md5_hash
|
||||
|
||||
Reference in New Issue
Block a user