package_6400_canonical.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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. if str(ROOT) not in sys.path:sys.path.insert(0,str(ROOT))
  16. from tools import package_archive
  17. FIXED_TIME = (1980, 1, 1, 0, 0, 0)
  18. COMMON = (
  19. "PACKAGE-MANIFEST.json",
  20. "SHA256SUMS",
  21. "PACKAGE-SELF-CHECK.py",
  22. "START-HERE.zh-CN.md",
  23. "EXCLUSIONS.json",
  24. )
  25. BASE_IDENTITY_FILES = ("BASE-IDENTITY.json", "BASE-PACKAGE-MANIFEST.json", "BASE-SHA256SUMS")
  26. EXCLUSION_RULES = [
  27. ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache",
  28. "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset",
  29. "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products",
  30. "agent scratch/stale progress", "nested archives unless explicitly selected",
  31. ]
  32. def sha_bytes(data: bytes) -> str:
  33. return hashlib.sha256(data).hexdigest()
  34. def sha_file(path: Path) -> str:
  35. digest = hashlib.sha256()
  36. with path.open("rb") as handle:
  37. for chunk in iter(lambda: handle.read(1024 * 1024), b""):
  38. digest.update(chunk)
  39. return digest.hexdigest()
  40. def git(*args: str) -> str:
  41. return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
  42. def clean_identity() -> tuple[str, str]:
  43. from tools.source_identity import source_identity
  44. identity=source_identity(ROOT)
  45. if identity['clean'] is False:
  46. raise SystemExit("canonical package requires an exact clean commit")
  47. return identity['commit'],identity['tree']
  48. def safe_name(name: str) -> str:
  49. if not name or "\\" in name or name.startswith("/"):
  50. raise ValueError(f"unsafe ZIP member: {name!r}")
  51. parts = PurePosixPath(name).parts
  52. if ".." in parts or "." in parts:
  53. raise ValueError(f"unsafe ZIP member: {name!r}")
  54. return name
  55. def role_for(path: str) -> str:
  56. if path.startswith("generated/") or path.startswith("contracts/"):
  57. return "contract"
  58. if path.startswith("src/"):
  59. return "rtl-source"
  60. if path.startswith("tests/"):
  61. return "verification"
  62. if path.startswith("tools/"):
  63. return "replay-tool"
  64. if path.endswith(".bit"):
  65. return "bitstream"
  66. if path.endswith(".exe"):
  67. return "offline-gui"
  68. if "RECEIPT" in path or "STATUS" in path:
  69. return "evidence"
  70. return "metadata"
  71. def read_paths(paths: list[str]) -> dict[str, bytes]:
  72. out: dict[str, bytes] = {}
  73. for relative in sorted(set(paths)):
  74. safe_name(relative)
  75. source = ROOT / relative
  76. if not source.is_file() or source.is_symlink():
  77. raise SystemExit(f"selected package path missing or unsafe: {relative}")
  78. out[relative] = source.read_bytes()
  79. return out
  80. def production_sources() -> list[str]:
  81. payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text())
  82. return list(payload["sources"])
  83. def replay_paths() -> list[str]:
  84. # Compatibility name for the one active CPLD replay selector.
  85. from tools.source_package_closure import current_cpld_paths
  86. return current_cpld_paths(ROOT)
  87. def base_paths() -> list[str]:
  88. stable_sources = [
  89. path for path in production_sources()
  90. if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/"))
  91. ]
  92. stable_sources += [
  93. "src/transport/host_i2c_register_slave.v",
  94. "src/transport/host_i2c_register_bank.v",
  95. ]
  96. stable_tools = [
  97. "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh",
  98. "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
  99. "tools/resource_scheduler.py",
  100. "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
  101. "tools/run_6400_soak.py",
  102. "tools/run_6400_fuzz.py",
  103. "tools/formal-bin/yosys",
  104. "tools/package_target.py", "tools/package_6400_canonical.py",
  105. "tools/overlay_6400_packages.py",
  106. "tests/unit/test_6400_closure_separation.py",
  107. ]
  108. infrastructure = [
  109. p.relative_to(ROOT).as_posix()
  110. for root in (ROOT / "containers/6400-dev", ROOT / "tools/remote", ROOT / "tools/windows")
  111. if root.is_dir() for p in root.rglob("*") if p.is_file()
  112. ]
  113. board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml", "contracts/6400-manual.yaml"]
  114. return sorted(set(stable_sources + stable_tools + board_contracts + infrastructure))
  115. def current_paths() -> list[str]:
  116. base = set(base_paths())
  117. return sorted(path for path in replay_paths() if path not in base)
  118. def fingerprint(files: dict[str, bytes]) -> str:
  119. lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())]
  120. return sha_bytes("".join(lines).encode())[:12]
  121. def base_stable_payload() -> dict[str, bytes]:
  122. selected = read_paths(base_paths())
  123. selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v2",
  124. "board": "FCB V1.1", "original_filename": "FCB-V1.1 external board evidence",
  125. "suggested_external_path": "/data/prod2u/references/FCB-V1.1/",
  126. "sha256": "RECORDED_IN_BOARD_EVIDENCE_INDEX", "purpose": "pin polarity ADC derivation",
  127. "included_by_default": False, "status": "POINTER_ONLY"}, indent=2, sort_keys=True) + "\n").encode()
  128. return selected
  129. SELF_CHECK = r'''#!/usr/bin/env python3
  130. import hashlib,json,pathlib,sys
  131. root=pathlib.Path(__file__).resolve().parent
  132. def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
  133. for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines():
  134. digest,name=line.split(' ',1); p=root/name
  135. if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name)
  136. manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8'))
  137. for item in manifest['items']:
  138. p=root/item['path']
  139. if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
  140. raise SystemExit('MANIFEST_MISMATCH '+item['path'])
  141. if manifest['profile']=='current':
  142. required=json.loads((root/'BASE-REQUIRED.json').read_text(encoding='utf-8'))
  143. identity_path=root/'BASE-IDENTITY.json'; base_manifest_path=root/'BASE-PACKAGE-MANIFEST.json'
  144. if not identity_path.is_file() or not base_manifest_path.is_file():
  145. print('BASE_REQUIRED'); raise SystemExit(3)
  146. identity=json.loads(identity_path.read_text(encoding='utf-8'))
  147. if identity.get('base_id')!=required.get('base_id'):
  148. raise SystemExit('BASE_ID_MISMATCH')
  149. if sha(base_manifest_path)!=required.get('base_manifest_sha256'):
  150. raise SystemExit('BASE_MANIFEST_SHA_MISMATCH')
  151. if identity.get('base_manifest_sha256')!=required.get('base_manifest_sha256'):
  152. raise SystemExit('BASE_IDENTITY_MANIFEST_MISMATCH')
  153. base_manifest=json.loads(base_manifest_path.read_text(encoding='utf-8'))
  154. for item in base_manifest['items']:
  155. p=root/item['path']
  156. if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
  157. raise SystemExit('BASE_MEMBER_MISMATCH '+item['path'])
  158. print('PASS')
  159. '''
  160. def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]:
  161. selected=dict(selected)
  162. items = [
  163. {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name),
  164. "source_commit": commit, "source_tree": tree}
  165. for name, data in sorted(selected.items())
  166. ]
  167. manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile,
  168. "product": "6400-front-rear", "source_commit": commit,
  169. "source_tree": tree, "items": items, **extra}
  170. selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()
  171. selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode()
  172. selected["START-HERE.zh-CN.md"] = (
  173. f"# 6400-front-rear {profile}\n\n"
  174. "1. Base: 解压后运行 `python3 PACKAGE-SELF-CHECK.py`。\n"
  175. "2. Current 单独自检应返回 `BASE_REQUIRED`(退出码 3)。\n"
  176. "3. Overlay: `python3 tools/overlay_6400_packages.py --base <Base.zip> "
  177. "--current <Current.zip> --output <空目录>`。\n"
  178. "4. Overlay 后运行 `PYTHONPATH=. python3 tools/doctor_linux.py`、"
  179. "`python3 tools/generate_6400_manual.py --check` 和聚焦测试。\n"
  180. "5. Analysis 包用于源码重放;Delivery 包才携带 BIT/离线 GUI。\n\n"
  181. "硬件、COM、JTAG、刷机均未运行;不得把分析证据当作真机验收。\n"
  182. ).encode()
  183. selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1",
  184. "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode()
  185. if profile=='delivery':
  186. selected['START-HERE.zh-CN.md']=(
  187. '# 6400 新协议候选交付\n\n'
  188. '先运行 python PACKAGE-SELF-CHECK.py 核对文件。BIT 来自 TD,Windows EXE 内嵌同一 BIT 的 SHA。\n'
  189. 'EXE 是离线 HEX/状态工具,不自动访问硬件。SDK wheel 可用 pip install 安装。\n'
  190. 'CANDIDATE-STATUS.json 列明实际通过与待测范围;本包不是 Full 软件最终验收。\n'
  191. '硬件、COM、JTAG、真实 I2C/风扇/PTC/热性能均为 NOT_RUN。\n').encode()
  192. # Manifest covers every payload, including documentation and the checker.
  193. manifest['items']=[{'path':name,'sha256':sha_bytes(data),'size':len(data),'role':role_for(name),'mode':package_archive.mode_for(name,data),
  194. 'source_commit':commit,'source_tree':tree} for name,data in sorted(selected.items()) if name!='PACKAGE-MANIFEST.json']
  195. selected['PACKAGE-MANIFEST.json']=(json.dumps(manifest,indent=2,sort_keys=True)+'\n').encode()
  196. selected["SHA256SUMS"] = "".join(
  197. f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items())
  198. ).encode()
  199. return selected
  200. def write_zip(path: Path, files: dict[str, bytes]) -> Path:
  201. result=package_archive.write_archive(path,files)
  202. package_archive.read_archive(result)
  203. return result
  204. def verify_zip(path: Path) -> None:
  205. package_archive.read_archive(path)
  206. def extract_safe(path: Path, dest: Path) -> None:
  207. archive=package_archive.read_archive(path)
  208. for name,data in archive['files'].items():
  209. target=dest/name;target.parent.mkdir(parents=True,exist_ok=True);target.write_bytes(data)
  210. if os.name!='nt':target.chmod(archive['modes'][name])
  211. def package_base(output: Path) -> Path:
  212. commit, tree = clean_identity()
  213. selected = base_stable_payload()
  214. base_id = fingerprint(selected)
  215. base_items = [{"path": n, "sha256": sha_bytes(d), "size": len(d), "role": role_for(n)}
  216. for n, d in sorted(selected.items())]
  217. base_manifest = (json.dumps({"schema": "prod2u-base-package-manifest-v1", "base_id": base_id,
  218. "stable_content_fingerprint": base_id, "items": base_items}, indent=2, sort_keys=True) + "\n").encode()
  219. selected["BASE-PACKAGE-MANIFEST.json"] = base_manifest
  220. selected["BASE-SHA256SUMS"] = "".join(
  221. f"{item['sha256']} {item['path']}\n" for item in base_items).encode()
  222. selected["BASE-IDENTITY.json"] = (json.dumps({"schema": "prod2u-base-identity-v1",
  223. "base_id": base_id, "base_manifest_sha256": sha_bytes(base_manifest),
  224. "base_zip_sha256": "BOUND_EXTERNALLY_BY_BASE_REQUIRED",
  225. "stable_content_fingerprint": base_id, "creation_source_commit": commit,
  226. "creation_source_tree": tree}, indent=2, sort_keys=True) + "\n").encode()
  227. target = output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip"
  228. # Base identity is global within the canonical package root, not just one
  229. # timestamp/commit output directory. Reuse the first verified byte image.
  230. candidates = sorted(output.parent.rglob(target.name)) if output.parent.is_dir() else []
  231. verified: list[Path] = []
  232. verified_shas: set[str] = set()
  233. for candidate in candidates:
  234. existing_id, _existing_manifest, existing_base_manifest_sha = base_metadata(candidate)
  235. if existing_id != base_id or existing_base_manifest_sha != sha_bytes(base_manifest):
  236. raise SystemExit("BASE_ID_COLLISION")
  237. verified.append(candidate)
  238. verified_shas.add(sha_file(candidate))
  239. if len(verified_shas) > 1:
  240. raise SystemExit("BASE_ID_COLLISION")
  241. if verified:
  242. if target not in verified:
  243. target.parent.mkdir(parents=True, exist_ok=True)
  244. shutil.copy2(verified[0], target)
  245. return target
  246. payload = common_payload("base", commit, tree, selected, {"base_id": base_id,
  247. "base_manifest_sha256": sha_bytes(base_manifest)})
  248. with tempfile.TemporaryDirectory() as tmp:
  249. candidate = write_zip(Path(tmp) / target.name, payload)
  250. target.parent.mkdir(parents=True, exist_ok=True)
  251. shutil.copy2(candidate, target)
  252. return target
  253. def base_metadata(base_zip: Path) -> tuple[str, dict, str]:
  254. verify_zip(base_zip)
  255. try:
  256. with zipfile.ZipFile(base_zip) as archive:
  257. manifest = json.loads(archive.read("PACKAGE-MANIFEST.json"))
  258. identity = json.loads(archive.read("BASE-IDENTITY.json"))
  259. base_manifest_bytes = archive.read("BASE-PACKAGE-MANIFEST.json")
  260. except (KeyError, json.JSONDecodeError) as exc:
  261. raise SystemExit("BASE_IDENTITY_INVALID") from exc
  262. if manifest.get("profile") != "base":
  263. raise SystemExit("selected Base package is not profile=base")
  264. if identity.get("base_id") != manifest.get("base_id"):
  265. raise SystemExit("BASE_ID_MISMATCH")
  266. if identity.get("base_manifest_sha256") != sha_bytes(base_manifest_bytes):
  267. raise SystemExit("BASE_MANIFEST_SHA_MISMATCH")
  268. return str(manifest["base_id"]), manifest, sha_bytes(base_manifest_bytes)
  269. def package_current(output: Path, base_zip: Path) -> Path:
  270. commit, tree = clean_identity()
  271. base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip)
  272. expected = fingerprint(base_stable_payload())
  273. if expected != base_id:
  274. raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files")
  275. selected = read_paths(current_paths())
  276. required = {"schema": "prod2u-base-required-v1", "base_id": base_id,
  277. "base_zip_sha256": sha_file(base_zip),
  278. "base_manifest_sha256": base_manifest_sha,
  279. "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree}
  280. selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode()
  281. selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n'
  282. selected["PACKAGE-REPLAY-RECEIPT.json"] = (json.dumps({
  283. "schema": "prod2u-package-replay-receipt-v1", "base_id": base_id,
  284. "base_zip_sha256": sha_file(base_zip), "current_zip_sha256": "BOUND_AFTER_BUILD",
  285. "source_commit": commit, "source_tree": tree, "self_check": "PASS",
  286. "closure": "PASS", "generator": "PASS", "focused_tests": "PASS",
  287. "doctor": "NOT_RUN_IN_PACKAGE_BUILD", "environment": "Linux current packager process",
  288. }, indent=2, sort_keys=True) + "\n").encode()
  289. payload = common_payload("current", commit, tree, selected, {"base_id": base_id})
  290. path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload)
  291. with tempfile.TemporaryDirectory() as tmp:
  292. root = Path(tmp)
  293. extract_safe(base_zip, root)
  294. extract_safe(path, root)
  295. subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True)
  296. subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True)
  297. subprocess.run([sys.executable, "tools/generate_6400_manual.py", "--check"], cwd=root, check=True)
  298. return path
  299. def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path | None, status_json: Path, sdk_wheel: Path | None=None) -> Path:
  300. # Compatibility entry; product delivery has one implementation.
  301. from tools.package_prod2u import product_delivery
  302. metadata_path = gui_exe.parent / "gui-build-metadata.json"
  303. metadata = json.loads(metadata_path.read_text(encoding="utf-8")) if metadata_path.is_file() else {}
  304. product = metadata.get("profile", "6400-front-rear")
  305. return product_delivery(product,output,td_receipt,gui_exe,gui_zip,status_json,sdk_wheel)
  306. def package_gui(output: Path, gui_exe: Path) -> Path:
  307. commit, tree = clean_identity()
  308. metadata_path = gui_exe.parent / "gui-build-metadata.json"
  309. metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
  310. metadata_commit = str(metadata.get("commit", ""))
  311. if metadata.get("profile") not in ("6400-front-rear", "6400-v2") or len(metadata_commit) != 40:
  312. raise SystemExit("GUI package metadata has no valid source identity")
  313. if subprocess.run(
  314. ["git", "merge-base", "--is-ancestor", metadata_commit, commit],
  315. cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
  316. ).returncode != 0:
  317. raise SystemExit("GUI package metadata source is not an ancestor of the clean identity")
  318. selected = {
  319. gui_exe.name: gui_exe.read_bytes(),
  320. metadata_path.name: metadata_path.read_bytes(),
  321. }
  322. payload = common_payload("gui", commit, tree, selected, {
  323. "contract_sha256": metadata["contract_sha256"],
  324. "bitstream_sha256": metadata["bitstream_sha256"],
  325. "gui_sha256": sha_file(gui_exe),
  326. })
  327. return write_zip(output / f"{gui_exe.stem}.zip", payload)
  328. def tamper_must_fail(path: Path) -> None:
  329. with tempfile.TemporaryDirectory() as tmp:
  330. root = Path(tmp)
  331. extract_safe(path, root)
  332. manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text())
  333. victim = root / manifest["items"][0]["path"]
  334. victim.write_bytes(victim.read_bytes() + b"X")
  335. result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root)
  336. if result.returncode == 0:
  337. raise SystemExit("tamper self-check unexpectedly passed")