package_6400_canonical.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #!/usr/bin/env python3
  2. """Deterministic Base/Current/Delivery packager for 6400-front-rear."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import shutil
  8. import stat
  9. import subprocess
  10. import sys
  11. import tempfile
  12. import zipfile
  13. from pathlib import Path, PurePosixPath
  14. ROOT = Path(__file__).resolve().parents[1]
  15. FIXED_TIME = (1980, 1, 1, 0, 0, 0)
  16. COMMON = (
  17. "PACKAGE-MANIFEST.json",
  18. "SHA256SUMS",
  19. "PACKAGE-SELF-CHECK.py",
  20. "START-HERE.zh-CN.md",
  21. "EXCLUSIONS.json",
  22. )
  23. BASE_IDENTITY_FILES = ("BASE-IDENTITY.json", "BASE-PACKAGE-MANIFEST.json", "BASE-SHA256SUMS")
  24. EXCLUSION_RULES = [
  25. ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache",
  26. "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset",
  27. "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products",
  28. "agent scratch/stale progress", "nested archives unless explicitly selected",
  29. ]
  30. def sha_bytes(data: bytes) -> str:
  31. return hashlib.sha256(data).hexdigest()
  32. def sha_file(path: Path) -> str:
  33. digest = hashlib.sha256()
  34. with path.open("rb") as handle:
  35. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  36. digest.update(chunk)
  37. return digest.hexdigest()
  38. def git(*args: str) -> str:
  39. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  40. def clean_identity() -> tuple[str, str]:
  41. if git("status", "--porcelain"):
  42. raise SystemExit("canonical package requires an exact clean commit")
  43. return git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
  44. def safe_name(name: str) -> str:
  45. if not name or "\\" in name or name.startswith("/"):
  46. raise ValueError(f"unsafe ZIP member: {name!r}")
  47. parts = PurePosixPath(name).parts
  48. if ".." in parts or "." in parts:
  49. raise ValueError(f"unsafe ZIP member: {name!r}")
  50. return name
  51. def role_for(path: str) -> str:
  52. if path.startswith("generated/") or path.startswith("contracts/"):
  53. return "contract"
  54. if path.startswith("src/"):
  55. return "rtl-source"
  56. if path.startswith("tests/"):
  57. return "verification"
  58. if path.startswith("tools/"):
  59. return "replay-tool"
  60. if path.endswith(".bit"):
  61. return "bitstream"
  62. if path.endswith(".exe"):
  63. return "offline-gui"
  64. if "RECEIPT" in path or "STATUS" in path:
  65. return "evidence"
  66. return "metadata"
  67. def read_paths(paths: list[str]) -> dict[str, bytes]:
  68. out: dict[str, bytes] = {}
  69. for relative in sorted(set(paths)):
  70. safe_name(relative)
  71. source = ROOT / relative
  72. if not source.is_file() or source.is_symlink():
  73. raise SystemExit(f"selected package path missing or unsafe: {relative}")
  74. out[relative] = source.read_bytes()
  75. return out
  76. def production_sources() -> list[str]:
  77. payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text())
  78. return list(payload["sources"])
  79. def replay_paths() -> list[str]:
  80. payload = json.loads((ROOT / "products/6400-front-rear/analysis-replay-closure.json").read_text())
  81. return list(payload["paths"])
  82. def base_paths() -> list[str]:
  83. stable_sources = [
  84. path for path in production_sources()
  85. if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/"))
  86. ]
  87. stable_sources += [
  88. "src/transport/host_i2c_register_slave.v",
  89. "src/transport/host_i2c_register_bank.v",
  90. ]
  91. stable_tools = [
  92. "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh",
  93. "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
  94. "tools/resource_scheduler.py",
  95. "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
  96. "tools/run_6400_soak.py",
  97. "tools/run_6400_fuzz.py",
  98. "tools/formal-bin/yosys",
  99. "tools/package_target.py", "tools/package_6400_canonical.py",
  100. "tools/overlay_6400_packages.py",
  101. "tests/unit/test_6400_closure_separation.py",
  102. ]
  103. infrastructure = [
  104. p.relative_to(ROOT).as_posix()
  105. for root in (ROOT / "containers/6400-dev", ROOT / "tools/remote", ROOT / "tools/windows")
  106. if root.is_dir() for p in root.rglob("*") if p.is_file()
  107. ]
  108. board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml", "contracts/6400-manual.yaml"]
  109. return sorted(set(stable_sources + stable_tools + board_contracts + infrastructure))
  110. def current_paths() -> list[str]:
  111. base = set(base_paths())
  112. product = [
  113. "contracts/6400-snapshot.yaml", "contracts/6400-wire.yaml",
  114. "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
  115. "products/6400-front-rear/analysis-replay-closure.json", "projects/registry.json",
  116. "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc",
  117. "td/prod2u_6400_front_back.prj", "td/syn/prod2u_6400_front_back.tcl",
  118. "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl",
  119. ]
  120. generated_names = {
  121. "host-contract.json", "manual-uart-contract.json", "host-i2c-register-map.json",
  122. "golden-vectors.json", "snapshot-layout.json", "channel-map.json",
  123. "fan-control-parameters.json", "contract-sha256.txt", "prod2u_6400_v1_params.vh",
  124. "host-i2c-pin-evidence.json",
  125. }
  126. generated = [
  127. (ROOT / "generated/6400" / name).relative_to(ROOT).as_posix()
  128. for name in sorted(generated_names)
  129. if (ROOT / "generated/6400" / name).is_file()
  130. ]
  131. generated.append("docs/electrical/host-i2c-pin-evidence-lock.md")
  132. generated.append("docs/generated/6400-channel-map.md")
  133. specific_sources = [p for p in production_sources() if p not in base]
  134. focused = [p for p in replay_paths() if p not in base]
  135. focused.append("tests/unit/test_6400_canonical_packages.py")
  136. return sorted(set(product + generated + specific_sources + focused))
  137. def fingerprint(files: dict[str, bytes]) -> str:
  138. lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())]
  139. return sha_bytes("".join(lines).encode())[:12]
  140. def base_stable_payload() -> dict[str, bytes]:
  141. selected = read_paths(base_paths())
  142. selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v2",
  143. "board": "FCB V1.1", "original_filename": "FCB-V1.1 external board evidence",
  144. "suggested_external_path": "/data/prod2u/references/FCB-V1.1/",
  145. "sha256": "RECORDED_IN_BOARD_EVIDENCE_INDEX", "purpose": "pin polarity ADC derivation",
  146. "included_by_default": False, "status": "POINTER_ONLY"}, indent=2, sort_keys=True) + "\n").encode()
  147. return selected
  148. SELF_CHECK = r'''#!/usr/bin/env python3
  149. import hashlib,json,pathlib,sys
  150. root=pathlib.Path(__file__).resolve().parent
  151. def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
  152. for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines():
  153. digest,name=line.split(' ',1); p=root/name
  154. if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name)
  155. manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8'))
  156. for item in manifest['items']:
  157. p=root/item['path']
  158. if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
  159. raise SystemExit('MANIFEST_MISMATCH '+item['path'])
  160. if manifest['profile']=='current':
  161. required=json.loads((root/'BASE-REQUIRED.json').read_text(encoding='utf-8'))
  162. identity_path=root/'BASE-IDENTITY.json'; base_manifest_path=root/'BASE-PACKAGE-MANIFEST.json'
  163. if not identity_path.is_file() or not base_manifest_path.is_file():
  164. print('BASE_REQUIRED'); raise SystemExit(3)
  165. identity=json.loads(identity_path.read_text(encoding='utf-8'))
  166. if identity.get('base_id')!=required.get('base_id'):
  167. raise SystemExit('BASE_ID_MISMATCH')
  168. if sha(base_manifest_path)!=required.get('base_manifest_sha256'):
  169. raise SystemExit('BASE_MANIFEST_SHA_MISMATCH')
  170. if identity.get('base_manifest_sha256')!=required.get('base_manifest_sha256'):
  171. raise SystemExit('BASE_IDENTITY_MANIFEST_MISMATCH')
  172. base_manifest=json.loads(base_manifest_path.read_text(encoding='utf-8'))
  173. for item in base_manifest['items']:
  174. p=root/item['path']
  175. if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
  176. raise SystemExit('BASE_MEMBER_MISMATCH '+item['path'])
  177. print('PASS')
  178. '''
  179. def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]:
  180. items = [
  181. {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name),
  182. "source_commit": commit, "source_tree": tree}
  183. for name, data in sorted(selected.items())
  184. ]
  185. manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile,
  186. "product": "6400-front-rear", "source_commit": commit,
  187. "source_tree": tree, "items": items, **extra}
  188. selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()
  189. selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode()
  190. selected["START-HERE.zh-CN.md"] = (
  191. f"# 6400-front-rear {profile}\n\n"
  192. "1. Base: 解压后运行 `python3 PACKAGE-SELF-CHECK.py`。\n"
  193. "2. Current 单独自检应返回 `BASE_REQUIRED`(退出码 3)。\n"
  194. "3. Overlay: `python3 tools/overlay_6400_packages.py --base <Base.zip> "
  195. "--current <Current.zip> --output <空目录>`。\n"
  196. "4. Overlay 后运行 `PYTHONPATH=. python3 tools/doctor_linux.py`、"
  197. "`python3 tools/generate_6400_v1.py --check` 和聚焦测试。\n"
  198. "5. Analysis 包用于源码重放;Delivery 包才携带 BIT/离线 GUI。\n\n"
  199. "硬件、COM、JTAG、刷机均未运行;不得把分析证据当作真机验收。\n"
  200. ).encode()
  201. selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1",
  202. "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode()
  203. selected["SHA256SUMS"] = "".join(
  204. f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items())
  205. ).encode()
  206. return selected
  207. def write_zip(path: Path, files: dict[str, bytes]) -> Path:
  208. path.parent.mkdir(parents=True, exist_ok=True)
  209. if path.exists():
  210. path.unlink()
  211. seen: set[str] = set()
  212. with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
  213. for name, data in sorted(files.items()):
  214. safe_name(name)
  215. if name in seen:
  216. raise SystemExit(f"duplicate ZIP member: {name}")
  217. seen.add(name)
  218. info = zipfile.ZipInfo(name, FIXED_TIME)
  219. info.create_system = 3
  220. info.external_attr = (stat.S_IFREG | (0o755 if name == "PACKAGE-SELF-CHECK.py" else 0o644)) << 16
  221. archive.writestr(info, data, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
  222. verify_zip(path)
  223. return path
  224. def verify_zip(path: Path) -> None:
  225. with zipfile.ZipFile(path) as archive:
  226. names = archive.namelist()
  227. if names != sorted(names) or len(names) != len(set(names)):
  228. raise SystemExit("ZIP members are not sorted/unique")
  229. for name in names:
  230. safe_name(name)
  231. for line in archive.read("SHA256SUMS").decode().splitlines():
  232. digest, name = line.split(" ", 1)
  233. if sha_bytes(archive.read(name)) != digest:
  234. raise SystemExit(f"package hash mismatch: {name}")
  235. if not set(COMMON).issubset(names):
  236. raise SystemExit("package common files missing")
  237. def extract_safe(path: Path, dest: Path) -> None:
  238. with zipfile.ZipFile(path) as archive:
  239. for info in archive.infolist():
  240. safe_name(info.filename)
  241. archive.extractall(dest)
  242. def package_base(output: Path) -> Path:
  243. commit, tree = clean_identity()
  244. selected = base_stable_payload()
  245. base_id = fingerprint(selected)
  246. base_items = [{"path": n, "sha256": sha_bytes(d), "size": len(d), "role": role_for(n)}
  247. for n, d in sorted(selected.items())]
  248. base_manifest = (json.dumps({"schema": "prod2u-base-package-manifest-v1", "base_id": base_id,
  249. "stable_content_fingerprint": base_id, "items": base_items}, indent=2, sort_keys=True) + "\n").encode()
  250. selected["BASE-PACKAGE-MANIFEST.json"] = base_manifest
  251. selected["BASE-SHA256SUMS"] = "".join(
  252. f"{item['sha256']} {item['path']}\n" for item in base_items).encode()
  253. selected["BASE-IDENTITY.json"] = (json.dumps({"schema": "prod2u-base-identity-v1",
  254. "base_id": base_id, "base_manifest_sha256": sha_bytes(base_manifest),
  255. "base_zip_sha256": "BOUND_EXTERNALLY_BY_BASE_REQUIRED",
  256. "stable_content_fingerprint": base_id, "creation_source_commit": commit,
  257. "creation_source_tree": tree}, indent=2, sort_keys=True) + "\n").encode()
  258. target = output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip"
  259. # Base identity is global within the canonical package root, not just one
  260. # timestamp/commit output directory. Reuse the first verified byte image.
  261. candidates = sorted(output.parent.rglob(target.name)) if output.parent.is_dir() else []
  262. verified: list[Path] = []
  263. verified_shas: set[str] = set()
  264. for candidate in candidates:
  265. existing_id, _existing_manifest, existing_base_manifest_sha = base_metadata(candidate)
  266. if existing_id != base_id or existing_base_manifest_sha != sha_bytes(base_manifest):
  267. raise SystemExit("BASE_ID_COLLISION")
  268. verified.append(candidate)
  269. verified_shas.add(sha_file(candidate))
  270. if len(verified_shas) > 1:
  271. raise SystemExit("BASE_ID_COLLISION")
  272. if verified:
  273. if target not in verified:
  274. target.parent.mkdir(parents=True, exist_ok=True)
  275. shutil.copy2(verified[0], target)
  276. return target
  277. payload = common_payload("base", commit, tree, selected, {"base_id": base_id,
  278. "base_manifest_sha256": sha_bytes(base_manifest)})
  279. with tempfile.TemporaryDirectory() as tmp:
  280. candidate = write_zip(Path(tmp) / target.name, payload)
  281. target.parent.mkdir(parents=True, exist_ok=True)
  282. shutil.copy2(candidate, target)
  283. return target
  284. def base_metadata(base_zip: Path) -> tuple[str, dict, str]:
  285. verify_zip(base_zip)
  286. try:
  287. with zipfile.ZipFile(base_zip) as archive:
  288. manifest = json.loads(archive.read("PACKAGE-MANIFEST.json"))
  289. identity = json.loads(archive.read("BASE-IDENTITY.json"))
  290. base_manifest_bytes = archive.read("BASE-PACKAGE-MANIFEST.json")
  291. except (KeyError, json.JSONDecodeError) as exc:
  292. raise SystemExit("BASE_IDENTITY_INVALID") from exc
  293. if manifest.get("profile") != "base":
  294. raise SystemExit("selected Base package is not profile=base")
  295. if identity.get("base_id") != manifest.get("base_id"):
  296. raise SystemExit("BASE_ID_MISMATCH")
  297. if identity.get("base_manifest_sha256") != sha_bytes(base_manifest_bytes):
  298. raise SystemExit("BASE_MANIFEST_SHA_MISMATCH")
  299. return str(manifest["base_id"]), manifest, sha_bytes(base_manifest_bytes)
  300. def package_current(output: Path, base_zip: Path) -> Path:
  301. commit, tree = clean_identity()
  302. base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip)
  303. expected = fingerprint(base_stable_payload())
  304. if expected != base_id:
  305. raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files")
  306. selected = read_paths(current_paths())
  307. required = {"schema": "prod2u-base-required-v1", "base_id": base_id,
  308. "base_zip_sha256": sha_file(base_zip),
  309. "base_manifest_sha256": base_manifest_sha,
  310. "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree}
  311. selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode()
  312. selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n'
  313. selected["PACKAGE-REPLAY-RECEIPT.json"] = (json.dumps({
  314. "schema": "prod2u-package-replay-receipt-v1", "base_id": base_id,
  315. "base_zip_sha256": sha_file(base_zip), "current_zip_sha256": "BOUND_AFTER_BUILD",
  316. "source_commit": commit, "source_tree": tree, "self_check": "PASS",
  317. "closure": "PASS", "generator": "PASS", "focused_tests": "PASS",
  318. "doctor": "NOT_RUN_IN_PACKAGE_BUILD", "environment": "Linux current packager process",
  319. }, indent=2, sort_keys=True) + "\n").encode()
  320. payload = common_payload("current", commit, tree, selected, {"base_id": base_id})
  321. path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload)
  322. with tempfile.TemporaryDirectory() as tmp:
  323. root = Path(tmp)
  324. extract_safe(base_zip, root)
  325. extract_safe(path, root)
  326. subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True)
  327. subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True)
  328. subprocess.run([sys.executable, "tools/generate_6400_manual.py", "--check"], cwd=root, check=True)
  329. return path
  330. def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path, status_json: Path) -> Path:
  331. package_commit, package_tree = clean_identity()
  332. receipt = json.loads(td_receipt.read_text())
  333. source_commit = str(receipt.get("commit", ""))
  334. if receipt.get("status") != "PASS" or len(source_commit) != 40:
  335. raise SystemExit("delivery TD receipt has no exact PASS source commit")
  336. if subprocess.run(
  337. ["git", "merge-base", "--is-ancestor", source_commit, package_commit],
  338. cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  339. ).returncode != 0:
  340. raise SystemExit("delivery source commit is not an ancestor of packager commit")
  341. bit = Path(str(receipt["bitstream"]))
  342. if not bit.is_absolute(): bit = td_receipt.parent / bit
  343. if sha_file(bit) != receipt.get("bitstream_sha256"):
  344. raise SystemExit("delivery bitstream hash mismatch")
  345. gui_meta = json.loads((gui_exe.parent / "gui-build-metadata.json").read_text())
  346. contract_sha = json.loads((ROOT / "generated/6400/host-contract.json").read_text())["contract_sha256"]
  347. if gui_meta != {"profile": "6400-front-rear", "commit": source_commit,
  348. "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit)}:
  349. raise SystemExit("delivery GUI metadata binding mismatch")
  350. external = {bit.name: bit, gui_exe.name: gui_exe, gui_zip.name: gui_zip,
  351. "TD-BUILD-RECEIPT.json": td_receipt, "CANDIDATE-STATUS.json": status_json}
  352. selected = {name: path.read_bytes() for name, path in external.items()}
  353. for relative in ["generated/6400/host-contract.json", "generated/6400/golden-vectors.json",
  354. "generated/6400/contract-sha256.txt"]:
  355. selected[relative] = (ROOT / relative).read_bytes()
  356. source_tree = git("rev-parse", f"{source_commit}^{{tree}}")
  357. binding = {"schema": "prod2u-artifact-delivery-binding-v1",
  358. "source_commit": source_commit, "source_tree": source_tree,
  359. "packager_commit": package_commit, "packager_tree": package_tree,
  360. "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit),
  361. "gui_sha256": sha_file(gui_exe), "hardware": "NOT_RUN"}
  362. selected["ARTIFACT-TO-DELIVERY-BINDING.json"] = (json.dumps(binding, indent=2, sort_keys=True) + "\n").encode()
  363. payload = common_payload("delivery", package_commit, package_tree, selected, binding)
  364. return write_zip(output / f"Prod2U-6400-Delivery-{source_commit[:8]}.zip", payload)
  365. def package_gui(output: Path, gui_exe: Path) -> Path:
  366. commit, tree = clean_identity()
  367. metadata_path = gui_exe.parent / "gui-build-metadata.json"
  368. metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
  369. metadata_commit = str(metadata.get("commit", ""))
  370. if metadata.get("profile") != "6400-front-rear" or len(metadata_commit) != 40:
  371. raise SystemExit("GUI package metadata has no valid source identity")
  372. if subprocess.run(
  373. ["git", "merge-base", "--is-ancestor", metadata_commit, commit],
  374. cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  375. ).returncode != 0:
  376. raise SystemExit("GUI package metadata source is not an ancestor of the clean identity")
  377. selected = {
  378. gui_exe.name: gui_exe.read_bytes(),
  379. metadata_path.name: metadata_path.read_bytes(),
  380. }
  381. payload = common_payload("gui", commit, tree, selected, {
  382. "contract_sha256": metadata["contract_sha256"],
  383. "bitstream_sha256": metadata["bitstream_sha256"],
  384. "gui_sha256": sha_file(gui_exe),
  385. })
  386. return write_zip(output / f"{gui_exe.stem}.zip", payload)
  387. def tamper_must_fail(path: Path) -> None:
  388. with tempfile.TemporaryDirectory() as tmp:
  389. root = Path(tmp)
  390. extract_safe(path, root)
  391. manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text())
  392. victim = root / manifest["items"][0]["path"]
  393. victim.write_bytes(victim.read_bytes() + b"X")
  394. result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root)
  395. if result.returncode == 0:
  396. raise SystemExit("tamper self-check unexpectedly passed")