#!/usr/bin/env python3 """Reassemble the nine immutable S4 transport parts after verifying each part.""" from __future__ import annotations import argparse import csv import hashlib from pathlib import Path LOGICAL_BYTES = 66_637_933_197 LOGICAL_SHA256 = "44086cd8c71bfe5469b2d9f76a3270fc2b1fe1bf72c49c581633a9142e04a6fb" def sha256_file(path: Path) -> str: digest = hashlib.sha256() with path.open("rb") as handle: for chunk in iter(lambda: handle.read(8 * 1024 * 1024), b""): digest.update(chunk) return digest.hexdigest() def main() -> int: root = Path(__file__).resolve().parents[1] parser = argparse.ArgumentParser() parser.add_argument("--parts-dir", type=Path, required=True) parser.add_argument("--output", type=Path, required=True) parser.add_argument("--dependencies", type=Path, default=root / "dependencies" / "DEPENDENCIES.tsv") args = parser.parse_args() with args.dependencies.open("r", encoding="utf-8", newline="") as handle: rows = [row for row in csv.DictReader(handle, delimiter="\t") if row["component"] == "S4"] rows.sort(key=lambda row: row["repository_path"]) if len(rows) != 9 or any(row["assembly_method"] != "concat_s4_v1" for row in rows): raise ValueError("S4 dependency lock is not the approved nine-part concat_s4_v1 layout") digest = hashlib.sha256() size = 0 partial = args.output.with_suffix(args.output.suffix + ".partial") with partial.open("wb") as out: for row in rows: part = args.parts_dir / Path(row["repository_path"]).name if part.stat().st_size != int(row["bytes"]) or sha256_file(part) != row["sha256"]: raise ValueError(f"part verification failed: {part}") with part.open("rb") as source: for chunk in iter(lambda: source.read(8 * 1024 * 1024), b""): out.write(chunk) digest.update(chunk) size += len(chunk) actual = digest.hexdigest() if size != LOGICAL_BYTES or actual != LOGICAL_SHA256: partial.unlink(missing_ok=True) raise ValueError(f"logical S4 mismatch: bytes={size}, sha256={actual}") partial.replace(args.output) print(f"PASS: {args.output} ({size:,} bytes; SHA-256 {actual})") return 0 if __name__ == "__main__": raise SystemExit(main())