Files
romm/backend/handler/snapshots/hashing.py
MMagTech ac9f5ab505 fix(saves): hash bytes that only end like a zip as one file (#5719)
* fix(saves): hash bytes that only end like a zip as one file

zipfile.is_zipfile is true for any file whose last 64 KB hold a zip's end
record. An emulator state can: Power Stone's Flycast (Naomi) state holds
the tail of the game's own TorrentZip archive. Reading such a file as a
zip fails, so compute_content_hash returned None, and a snapshot push
carrying the state was refused whole with "does not hash to the
manifest's value".

When the bytes cannot be read as a zip (BadZipFile), compute_content_hash,
hash_save_content and the memory card hash now hash them as one file, as
the web player's saveContentHash and the snapshot identity hash already
do. A real zip they cannot read within the limits stays unknown.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: code-review

Hash bytes as one file when the copied central directory points an entry
before the bytes start, as the tail of an archive longer than the state does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* pr-ready: plain-prose

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* fix(saves): decide what is a zip archive by one rule

Bytes are a zip archive only when their entries start at the first byte.
A state or save holding another archive, whole or only its tail, after
data of its own is hashed, shaped, uploaded and unpacked as one raw file
everywhere: the content hashers, the identity hash, save_shape_of,
check_upload and unpack_save_unit. A real archive with a corrupt entry
stays unknown to the content hashers, and the identity hash falls back to
the bytes for one past the limits too.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Georges-Antoine Assi <contact@me.gantoine.com>
2026-11-22 10:00:16 -05:00

42 lines
1.1 KiB
Python

"""A save unit's identity hash: its content hash without its clock members."""
import asyncio
import hashlib
import io
import zipfile
import zlib
from pathlib import Path
from handler.filesystem.assets_handler import (
ArchiveTooLarge,
open_zip_archive,
zip_identity_hash,
)
from logger.logger import log
def _identity(content: bytes) -> str:
try:
with open_zip_archive(io.BytesIO(content)) as zf:
if zf is not None:
return zip_identity_hash(zf)
except (
zipfile.BadZipFile,
ArchiveTooLarge,
EOFError,
OSError,
RuntimeError,
zlib.error,
) as exc:
log.debug(f"Hashing the save unit as one file: {exc}")
return hashlib.md5(content, usedforsecurity=False).hexdigest()
async def identity_hash(content: bytes) -> str:
"""The unit's content hash without its clock members, by sigil's rule."""
return await asyncio.to_thread(_identity, content)
async def identity_hash_of_file(path: Path) -> str:
return await identity_hash(await asyncio.to_thread(path.read_bytes))