package_6400_canonical.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. EXCLUSION_RULES = [
  24. ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache",
  25. "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset",
  26. "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products",
  27. "agent scratch/stale progress", "nested archives unless explicitly selected",
  28. ]
  29. def sha_bytes(data: bytes) -> str:
  30. return hashlib.sha256(data).hexdigest()
  31. def sha_file(path: Path) -> str:
  32. digest = hashlib.sha256()
  33. with path.open("rb") as handle:
  34. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  35. digest.update(chunk)
  36. return digest.hexdigest()
  37. def git(*args: str) -> str:
  38. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  39. def clean_identity() -> tuple[str, str]:
  40. if git("status", "--porcelain"):
  41. raise SystemExit("canonical package requires an exact clean commit")
  42. return git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
  43. def safe_name(name: str) -> str:
  44. if not name or "\\" in name or name.startswith("/"):
  45. raise ValueError(f"unsafe ZIP member: {name!r}")
  46. parts = PurePosixPath(name).parts
  47. if ".." in parts or "." in parts:
  48. raise ValueError(f"unsafe ZIP member: {name!r}")
  49. return name
  50. def role_for(path: str) -> str:
  51. if path.startswith("generated/") or path.startswith("contracts/"):
  52. return "contract"
  53. if path.startswith("src/"):
  54. return "rtl-source"
  55. if path.startswith("tests/"):
  56. return "verification"
  57. if path.startswith("tools/"):
  58. return "replay-tool"
  59. if path.endswith(".bit"):
  60. return "bitstream"
  61. if path.endswith(".exe"):
  62. return "offline-gui"
  63. if "RECEIPT" in path or "STATUS" in path:
  64. return "evidence"
  65. return "metadata"
  66. def read_paths(paths: list[str]) -> dict[str, bytes]:
  67. out: dict[str, bytes] = {}
  68. for relative in sorted(set(paths)):
  69. safe_name(relative)
  70. source = ROOT / relative
  71. if not source.is_file() or source.is_symlink():
  72. raise SystemExit(f"selected package path missing or unsafe: {relative}")
  73. out[relative] = source.read_bytes()
  74. return out
  75. def production_sources() -> list[str]:
  76. payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text())
  77. return list(payload["sources"])
  78. def replay_paths() -> list[str]:
  79. payload = json.loads((ROOT / "products/6400-front-rear/analysis-replay-closure.json").read_text())
  80. return list(payload["paths"])
  81. def base_paths() -> list[str]:
  82. stable_sources = [
  83. path for path in production_sources()
  84. if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/"))
  85. ]
  86. stable_tools = [
  87. "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh",
  88. "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
  89. "tools/generate_6400_v1.py", "tools/target_registry.py", "tools/run_6400_td.py",
  90. "tools/package_target.py", "tools/package_6400_canonical.py",
  91. "tests/unit/test_6400_closure_separation.py",
  92. ]
  93. board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml"]
  94. return sorted(set(stable_sources + stable_tools + board_contracts))
  95. def current_paths() -> list[str]:
  96. base = set(base_paths())
  97. product = [
  98. "contracts/6400-fixed-point.yaml", "contracts/6400-snapshot.yaml", "contracts/6400-wire.yaml",
  99. "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
  100. "products/6400-front-rear/analysis-replay-closure.json", "projects/registry.json",
  101. ]
  102. generated = [p.relative_to(ROOT).as_posix() for p in (ROOT / "generated/6400").glob("*") if p.is_file()]
  103. specific_sources = [p for p in production_sources() if p not in base]
  104. focused = [p for p in replay_paths() if p not in base]
  105. focused.append("tests/unit/test_6400_canonical_packages.py")
  106. return sorted(set(product + generated + specific_sources + focused))
  107. def fingerprint(files: dict[str, bytes]) -> str:
  108. lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())]
  109. return sha_bytes("".join(lines).encode())[:12]
  110. SELF_CHECK = r'''#!/usr/bin/env python3
  111. import hashlib,json,pathlib,sys,zipfile
  112. root=pathlib.Path(__file__).resolve().parent
  113. def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
  114. for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines():
  115. digest,name=line.split(' ',1); p=root/name
  116. if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name)
  117. manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8'))
  118. for item in manifest['items']:
  119. p=root/item['path']
  120. if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
  121. raise SystemExit('MANIFEST_MISMATCH '+item['path'])
  122. if manifest['profile']=='current' and not (root/'.base-overlay-present').exists():
  123. print('BASE_REQUIRED'); raise SystemExit(3)
  124. print('PASS')
  125. '''
  126. def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]:
  127. items = [
  128. {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name),
  129. "source_commit": commit, "source_tree": tree}
  130. for name, data in sorted(selected.items())
  131. ]
  132. manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile,
  133. "product": "6400-front-rear", "source_commit": commit,
  134. "source_tree": tree, "items": items, **extra}
  135. selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()
  136. selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode()
  137. selected["START-HERE.zh-CN.md"] = (
  138. f"# 6400-front-rear {profile}\n\n先运行 `python3 PACKAGE-SELF-CHECK.py`。"
  139. "硬件、COM、JTAG 均未运行;不得把分析证据当作真机验收。\n"
  140. ).encode()
  141. selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1",
  142. "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode()
  143. selected["SHA256SUMS"] = "".join(
  144. f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items())
  145. ).encode()
  146. return selected
  147. def write_zip(path: Path, files: dict[str, bytes]) -> Path:
  148. path.parent.mkdir(parents=True, exist_ok=True)
  149. if path.exists():
  150. path.unlink()
  151. seen: set[str] = set()
  152. with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
  153. for name, data in sorted(files.items()):
  154. safe_name(name)
  155. if name in seen:
  156. raise SystemExit(f"duplicate ZIP member: {name}")
  157. seen.add(name)
  158. info = zipfile.ZipInfo(name, FIXED_TIME)
  159. info.create_system = 3
  160. info.external_attr = (stat.S_IFREG | (0o755 if name == "PACKAGE-SELF-CHECK.py" else 0o644)) << 16
  161. archive.writestr(info, data, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
  162. verify_zip(path)
  163. return path
  164. def verify_zip(path: Path) -> None:
  165. with zipfile.ZipFile(path) as archive:
  166. names = archive.namelist()
  167. if names != sorted(names) or len(names) != len(set(names)):
  168. raise SystemExit("ZIP members are not sorted/unique")
  169. for name in names:
  170. safe_name(name)
  171. for line in archive.read("SHA256SUMS").decode().splitlines():
  172. digest, name = line.split(" ", 1)
  173. if sha_bytes(archive.read(name)) != digest:
  174. raise SystemExit(f"package hash mismatch: {name}")
  175. if not set(COMMON).issubset(names):
  176. raise SystemExit("package common files missing")
  177. def extract_safe(path: Path, dest: Path) -> None:
  178. with zipfile.ZipFile(path) as archive:
  179. for info in archive.infolist():
  180. safe_name(info.filename)
  181. archive.extractall(dest)
  182. def package_base(output: Path) -> Path:
  183. commit, tree = clean_identity()
  184. selected = read_paths(base_paths())
  185. base_id = fingerprint(selected)
  186. selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v1",
  187. "raw_reference_included": False, "source_status": "pointer-only",
  188. "board": "FCB V1.1"}, indent=2, sort_keys=True) + "\n").encode()
  189. payload = common_payload("base", commit, tree, selected, {"base_id": base_id})
  190. return write_zip(output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip", payload)
  191. def base_metadata(base_zip: Path) -> tuple[str, dict, str]:
  192. verify_zip(base_zip)
  193. with zipfile.ZipFile(base_zip) as archive:
  194. manifest_bytes = archive.read("PACKAGE-MANIFEST.json")
  195. manifest = json.loads(manifest_bytes)
  196. if manifest.get("profile") != "base":
  197. raise SystemExit("selected Base package is not profile=base")
  198. return str(manifest["base_id"]), manifest, sha_bytes(manifest_bytes)
  199. def package_current(output: Path, base_zip: Path) -> Path:
  200. commit, tree = clean_identity()
  201. base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip)
  202. expected = fingerprint(read_paths(base_paths()))
  203. if expected != base_id:
  204. raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files")
  205. selected = read_paths(current_paths())
  206. required = {"schema": "prod2u-base-required-v1", "base_id": base_id,
  207. "base_zip_sha256": sha_file(base_zip),
  208. "base_manifest_sha256": base_manifest_sha,
  209. "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree}
  210. selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode()
  211. selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n'
  212. payload = common_payload("current", commit, tree, selected, {"base_id": base_id})
  213. path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload)
  214. with tempfile.TemporaryDirectory() as tmp:
  215. root = Path(tmp)
  216. extract_safe(base_zip, root)
  217. extract_safe(path, root)
  218. (root / ".base-overlay-present").write_text("base+current\n")
  219. subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True)
  220. subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True)
  221. subprocess.run([sys.executable, "tools/generate_6400_v1.py", "--check"], cwd=root, check=True)
  222. subprocess.run([sys.executable, "-m", "pytest", "-q", "tests/unit/test_6400_canonical_packages.py"], cwd=root, check=True)
  223. return path
  224. def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path, status_json: Path) -> Path:
  225. commit, tree = clean_identity()
  226. receipt = json.loads(td_receipt.read_text())
  227. if receipt.get("status") != "PASS" or receipt.get("commit") != commit:
  228. raise SystemExit("delivery TD receipt is not bound to current clean commit")
  229. bit = Path(str(receipt["bitstream"]))
  230. if not bit.is_absolute(): bit = td_receipt.parent / bit
  231. if sha_file(bit) != receipt.get("bitstream_sha256"):
  232. raise SystemExit("delivery bitstream hash mismatch")
  233. gui_meta = json.loads((gui_exe.parent / "gui-build-metadata.json").read_text())
  234. contract_sha = json.loads((ROOT / "generated/6400/host-contract.json").read_text())["contract_sha256"]
  235. if gui_meta != {"profile": "6400-front-rear", "commit": commit,
  236. "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit)}:
  237. raise SystemExit("delivery GUI metadata binding mismatch")
  238. external = {bit.name: bit, gui_exe.name: gui_exe, gui_zip.name: gui_zip,
  239. "TD-BUILD-RECEIPT.json": td_receipt, "CANDIDATE-STATUS.json": status_json}
  240. selected = {name: path.read_bytes() for name, path in external.items()}
  241. for relative in ["generated/6400/host-contract.json", "generated/6400/golden-vectors.json",
  242. "generated/6400/contract-sha256.txt"]:
  243. selected[relative] = (ROOT / relative).read_bytes()
  244. binding = {"schema": "prod2u-artifact-delivery-binding-v1", "commit": commit,
  245. "tree": tree, "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit),
  246. "gui_sha256": sha_file(gui_exe), "hardware": "NOT_RUN"}
  247. selected["ARTIFACT-TO-DELIVERY-BINDING.json"] = (json.dumps(binding, indent=2, sort_keys=True) + "\n").encode()
  248. payload = common_payload("delivery", commit, tree, selected, binding)
  249. return write_zip(output / f"Prod2U-6400-Delivery-{commit[:8]}.zip", payload)
  250. def tamper_must_fail(path: Path) -> None:
  251. with tempfile.TemporaryDirectory() as tmp:
  252. root = Path(tmp)
  253. extract_safe(path, root)
  254. manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text())
  255. victim = root / manifest["items"][0]["path"]
  256. victim.write_bytes(victim.read_bytes() + b"X")
  257. result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root)
  258. if result.returncode == 0:
  259. raise SystemExit("tamper self-check unexpectedly passed")