diff --git a/.github/workflows/deploy-site.yml b/.github/workflows/deploy-site.yml index 98fd57f5b..8acb07ab8 100644 --- a/.github/workflows/deploy-site.yml +++ b/.github/workflows/deploy-site.yml @@ -17,7 +17,6 @@ on: - "scripts/core/artifacts.py" - "scripts/core/cli.py" - "scripts/core/crypto_verify.py" - - "scripts/core/deterministic_zip.py" - "scripts/core/github.py" - "scripts/core/hashing.py" - "scripts/core/options.py" diff --git a/scripts/core/deterministic_zip.py b/scripts/core/deterministic_zip.py deleted file mode 100644 index 2a4e828e9..000000000 --- a/scripts/core/deterministic_zip.py +++ /dev/null @@ -1,91 +0,0 @@ -"""Deterministic ZIP rebuilding for arcade BIOS and sample archives. - -A ZIP's hash depends on entry order, timestamps, compression level, and -permission bits as much as on content. Packs ship archives rebuilt with -all of that fixed, so the same ROMs always produce the same pack hash -regardless of how the source set was assembled. - -Usage: - from deterministic_zip import rebuild_zip_deterministic - - sha1 = rebuild_zip_deterministic("neogeo.zip", "out/neogeo.zip") -""" - -from __future__ import annotations - -import hashlib -import os -import shutil -import tempfile -import zipfile -from pathlib import Path - -# Fixed metadata for deterministic ZIPs -FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) # minimum ZIP timestamp -_FIXED_CREATE_SYSTEM = 0 # FAT/DOS (most compatible) -_FIXED_EXTERNAL_ATTR = 0o100644 << 16 # -rw-r--r-- -_COMPRESS_LEVEL = 9 # deflate level 9 for determinism -_COPY_CHUNK = 1024 * 1024 - - -def _sha1_file(path: str | Path) -> str: - sha1 = hashlib.sha1() - with open(path, "rb") as f: - for chunk in iter(lambda: f.read(65536), b""): - sha1.update(chunk) - return sha1.hexdigest() - - -def rebuild_zip_deterministic( - source_zip: str | Path, - output_zip: str | Path, -) -> str: - """Rebuild a ZIP with fixed metadata and entries sorted by name. - - Copies one chunk at a time rather than loading the archive: arcade - sample sets reach 279 MB, and holding a whole set plus its rebuilt - copy in memory costs hundreds of megabytes per pack for no benefit. - - Reading through ZipFile.open verifies each entry against the CRC - recorded in the source archive, so a corrupt entry raises - BadZipFile instead of being copied through. - - Returns the SHA1 of the new ZIP. - """ - with zipfile.ZipFile(str(source_zip)) as src: - entries = sorted( - (i for i in src.infolist() if not i.is_dir()), - key=lambda i: i.filename, - ) - with zipfile.ZipFile( - str(output_zip), - "w", - zipfile.ZIP_DEFLATED, - compresslevel=_COMPRESS_LEVEL, - ) as dst: - for info in entries: - out_info = zipfile.ZipInfo( - filename=info.filename, date_time=FIXED_DATE_TIME - ) - out_info.compress_type = zipfile.ZIP_DEFLATED - out_info.create_system = _FIXED_CREATE_SYSTEM - out_info.external_attr = _FIXED_EXTERNAL_ATTR - with src.open(info) as fsrc, dst.open(out_info, "w") as fdst: - shutil.copyfileobj(fsrc, fdst, _COPY_CHUNK) - - return _sha1_file(output_zip) - - -def verify_zip_determinism(zip_path: str | Path) -> tuple[bool, str, str]: - """Check whether a ZIP already matches its deterministic rebuild. - - Returns (is_deterministic, original_sha1, rebuilt_sha1). - """ - original = _sha1_file(zip_path) - fd, tmp_path = tempfile.mkstemp(suffix=".zip") - os.close(fd) - try: - rebuilt = rebuild_zip_deterministic(zip_path, tmp_path) - finally: - Path(tmp_path).unlink(missing_ok=True) - return original == rebuilt, original, rebuilt diff --git a/scripts/packs/archive.py b/scripts/packs/archive.py index 11f140cea..bcb7cafa6 100644 --- a/scripts/packs/archive.py +++ b/scripts/packs/archive.py @@ -12,12 +12,15 @@ from dataclasses import dataclass, field from pathlib import Path from core.artifacts import set_plain_mode -from core.deterministic_zip import FIXED_DATE_TIME from core.hashing import compute_hashes from core.paths import comparable_destination, sanitize_pack_path from packs.paths import has_path_conflict, register_path, placement_block +# The minimum ZIP timestamp, carried by every pack member so a pack is a +# function of its inputs and not of the clock. +FIXED_DATE_TIME = (1980, 1, 1, 0, 0, 0) + # Formats that are already compressed: deflating them again took 28 s of the # RetroArch build for 2.1 GB of members and saved 9.6 MB (0.45 %), 16 GB and # about 72 MB across all packs. Measured per extension on the 2026-10-20 diff --git a/tests/test_deterministic_zip.py b/tests/test_deterministic_zip.py index 92e988467..9f0578a91 100644 --- a/tests/test_deterministic_zip.py +++ b/tests/test_deterministic_zip.py @@ -1,4 +1,4 @@ -"""Tests for deterministic ZIP rebuilding.""" +"""A pack is a function of its inputs, not of the clock it was built on.""" from __future__ import annotations @@ -12,150 +12,7 @@ import unittest import zipfile from pathlib import Path -from scripts.core.deterministic_zip import ( - FIXED_DATE_TIME, - rebuild_zip_deterministic, - verify_zip_determinism, -) - -CONTENT = { - "03.wav": b"\x00\x01\x02" * 500, - "01.wav": b"sample one", - "sub/02.wav": b"sample two", -} - - -def _make_source(path: Path, date_time=(2021, 6, 5, 4, 3, 2), compression=None) -> None: - """Write a ZIP with deliberately non-deterministic metadata.""" - comp = zipfile.ZIP_STORED if compression is None else compression - with zipfile.ZipFile(path, "w", comp) as zf: - for name in ("sub/02.wav", "03.wav", "01.wav"): # unsorted on purpose - info = zipfile.ZipInfo(filename=name, date_time=date_time) - info.compress_type = comp - info.external_attr = 0o100777 << 16 - info.create_system = 3 # Unix - zf.writestr(info, CONTENT[name]) - - -class TestRebuild(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.tmp = Path(self._tmp.name) - self.src = self.tmp / "src.zip" - _make_source(self.src) - - def tearDown(self): - self._tmp.cleanup() - - def _rebuild(self, out_name="out.zip", src=None): - out = self.tmp / out_name - sha1 = rebuild_zip_deterministic(src or self.src, out) - return out, sha1 - - def test_content_is_preserved(self): - out, _ = self._rebuild() - with zipfile.ZipFile(out) as zf: - for name, data in CONTENT.items(): - self.assertEqual(zf.read(name), data) - - def test_entries_sorted_by_name(self): - out, _ = self._rebuild() - with zipfile.ZipFile(out) as zf: - self.assertEqual(zf.namelist(), ["01.wav", "03.wav", "sub/02.wav"]) - - def test_metadata_is_normalized(self): - out, _ = self._rebuild() - with zipfile.ZipFile(out) as zf: - for info in zf.infolist(): - self.assertEqual(info.date_time, FIXED_DATE_TIME) - self.assertEqual(info.create_system, 0) - self.assertEqual(info.external_attr, 0o100644 << 16) - self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED) - - def test_same_input_gives_same_hash(self): - _, first = self._rebuild("a.zip") - _, second = self._rebuild("b.zip") - self.assertEqual(first, second) - - def test_source_metadata_does_not_affect_hash(self): - """Different timestamps and compression, identical rebuild.""" - other = self.tmp / "other.zip" - _make_source(other, date_time=(1999, 1, 1, 1, 1, 2), compression=zipfile.ZIP_DEFLATED) - _, from_first = self._rebuild("a.zip") - _, from_other = self._rebuild("b.zip", src=other) - self.assertEqual(from_first, from_other) - - def test_returns_sha1_of_output(self): - import hashlib - - out, sha1 = self._rebuild() - self.assertEqual(sha1, hashlib.sha1(out.read_bytes()).hexdigest()) - - def test_directory_entries_are_dropped(self): - src = self.tmp / "withdir.zip" - with zipfile.ZipFile(src, "w") as zf: - zf.writestr(zipfile.ZipInfo("adir/"), b"") - zf.writestr("adir/file.bin", b"x") - out, _ = self._rebuild("nodir.zip", src=src) - with zipfile.ZipFile(out) as zf: - self.assertEqual(zf.namelist(), ["adir/file.bin"]) - - def test_corrupt_entry_raises(self): - """A tampered payload must fail the source CRC, not copy through.""" - raw = bytearray(self.src.read_bytes()) - marker = CONTENT["01.wav"] - idx = raw.find(marker) - self.assertGreater(idx, 0) - raw[idx : idx + len(marker)] = b"tampered!!" - corrupt = self.tmp / "corrupt.zip" - corrupt.write_bytes(bytes(raw)) - with self.assertRaises(zipfile.BadZipFile): - rebuild_zip_deterministic(corrupt, self.tmp / "never.zip") - - def test_empty_zip(self): - src = self.tmp / "empty.zip" - with zipfile.ZipFile(src, "w"): - pass - out, sha1 = self._rebuild("emptyout.zip", src=src) - with zipfile.ZipFile(out) as zf: - self.assertEqual(zf.namelist(), []) - self.assertTrue(sha1) - - def test_larger_than_copy_chunk(self): - """Streaming path must handle payloads bigger than one chunk.""" - src = self.tmp / "big.zip" - payload = bytes(range(256)) * 8192 # 2 MiB, two chunks - with zipfile.ZipFile(src, "w") as zf: - zf.writestr("big.bin", payload) - out, _ = self._rebuild("bigout.zip", src=src) - with zipfile.ZipFile(out) as zf: - self.assertEqual(zf.read("big.bin"), payload) - - -class TestVerifyDeterminism(unittest.TestCase): - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.tmp = Path(self._tmp.name) - - def tearDown(self): - self._tmp.cleanup() - - def test_non_deterministic_source_reported(self): - src = self.tmp / "src.zip" - _make_source(src) - ok, original, rebuilt = verify_zip_determinism(src) - self.assertFalse(ok) - self.assertNotEqual(original, rebuilt) - - def test_already_deterministic_source_reported(self): - src = self.tmp / "src.zip" - _make_source(src) - normalized = self.tmp / "norm.zip" - rebuild_zip_deterministic(src, normalized) - ok, original, rebuilt = verify_zip_determinism(normalized) - self.assertTrue(ok) - self.assertEqual(original, rebuilt) - +from scripts.packs.archive import FIXED_DATE_TIME class TestPackDeterminism(unittest.TestCase): """A pack is a function of its inputs, not of the clock it was built on.""" diff --git a/wiki/tools.md b/wiki/tools.md index e01bf27d0..851c9cc07 100644 --- a/wiki/tools.md +++ b/wiki/tools.md @@ -1394,7 +1394,6 @@ before a release (wiki/release-process.md). Its lines stay in | `indexnow.py` | List the pages a deploy changes, read against the `digests.json` the live site serves, as the IndexNow request the deploy posts once the new site is live. `--dist` names the built site, `--output` appends the request to a step output | | `romset_recipes.py` | Identify which emulator version an arcade archive matches, rebuild a pinned archive from ROMs already held, record a recipe for every archive the collection holds and build any of them from the members it holds (see [Archive recipes](#archive-recipes)) | | `scraper/romset_dat_importer.py` | Fetch and import per-set recipes from MAME `-listxml` or FBNeo DATs into `recipes/`. `--fetch` alone takes the newest MAME release, and FBNeo DATs are refreshed by git blob sha. `--fetch ` reads FBNeo at that tag, branch or commit | -| `core/deterministic_zip.py` | The fixed date pack members carry. Its archive rebuild is no longer called by the pack, which copies each ZIP byte for byte | | `core/torrentzip.py` | Build TorrentZip archives for MAME/FBNeo ROM sets (archive bytes depend only on contents, with stock zlib), streaming one member at a time | | `core/crypto_verify.py` | 3DS RSA signature and AES crypto verification | | `core/sect233r1.py` | Pure Python ECDSA verification on sect233r1 curve (3DS OTP cert) |