| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357 |
- #!/usr/bin/env python3
- """Deterministic Base/Current/Delivery packager for 6400-front-rear."""
- from __future__ import annotations
- import hashlib
- import json
- import os
- import shutil
- import stat
- import subprocess
- import sys
- import tempfile
- import zipfile
- from pathlib import Path, PurePosixPath
- ROOT = Path(__file__).resolve().parents[1]
- FIXED_TIME = (1980, 1, 1, 0, 0, 0)
- COMMON = (
- "PACKAGE-MANIFEST.json",
- "SHA256SUMS",
- "PACKAGE-SELF-CHECK.py",
- "START-HERE.zh-CN.md",
- "EXCLUSIONS.json",
- )
- EXCLUSION_RULES = [
- ".git/.repo/worktrees", ".cursor/.codex/Playwright cache", "__pycache__/pytest cache",
- "venv/node_modules", "build/dist/TD/Formal workdir", "fuzz corpus/raw dataset",
- "raw BRD/PDF/DSN", "old bitstream/GUI/logs", "unrelated products",
- "agent scratch/stale progress", "nested archives unless explicitly selected",
- ]
- def sha_bytes(data: bytes) -> str:
- return hashlib.sha256(data).hexdigest()
- def sha_file(path: Path) -> str:
- digest = hashlib.sha256()
- with path.open("rb") as handle:
- for chunk in iter(lambda: handle.read(1024 * 1024), b""):
- digest.update(chunk)
- return digest.hexdigest()
- def git(*args: str) -> str:
- return subprocess.check_output(["git", *args], cwd=ROOT, text=True).strip()
- def clean_identity() -> tuple[str, str]:
- if git("status", "--porcelain"):
- raise SystemExit("canonical package requires an exact clean commit")
- return git("rev-parse", "HEAD"), git("rev-parse", "HEAD^{tree}")
- def safe_name(name: str) -> str:
- if not name or "\\" in name or name.startswith("/"):
- raise ValueError(f"unsafe ZIP member: {name!r}")
- parts = PurePosixPath(name).parts
- if ".." in parts or "." in parts:
- raise ValueError(f"unsafe ZIP member: {name!r}")
- return name
- def role_for(path: str) -> str:
- if path.startswith("generated/") or path.startswith("contracts/"):
- return "contract"
- if path.startswith("src/"):
- return "rtl-source"
- if path.startswith("tests/"):
- return "verification"
- if path.startswith("tools/"):
- return "replay-tool"
- if path.endswith(".bit"):
- return "bitstream"
- if path.endswith(".exe"):
- return "offline-gui"
- if "RECEIPT" in path or "STATUS" in path:
- return "evidence"
- return "metadata"
- def read_paths(paths: list[str]) -> dict[str, bytes]:
- out: dict[str, bytes] = {}
- for relative in sorted(set(paths)):
- safe_name(relative)
- source = ROOT / relative
- if not source.is_file() or source.is_symlink():
- raise SystemExit(f"selected package path missing or unsafe: {relative}")
- out[relative] = source.read_bytes()
- return out
- def production_sources() -> list[str]:
- payload = json.loads((ROOT / "products/6400-front-rear/source-closure.json").read_text())
- return list(payload["sources"])
- def replay_paths() -> list[str]:
- payload = json.loads((ROOT / "products/6400-front-rear/analysis-replay-closure.json").read_text())
- return list(payload["paths"])
- def base_paths() -> list[str]:
- stable_sources = [
- path for path in production_sources()
- if path.startswith(("src/common/", "src/modules/", "src/rtl/", "src/actuator/"))
- ]
- stable_sources += [
- "src/transport/host_i2c_register_slave.v",
- "src/transport/host_i2c_register_bank.v",
- ]
- stable_tools = [
- "tools/bootstrap-linux.sh", "tools/bootstrap_oss_cad_suite.py", "tools/doctor.sh",
- "tools/doctor_linux.py", "tools/check_6400_closures.py", "tools/generate_target.py",
- "tools/generate_6400_manual.py", "tools/target_registry.py", "tools/run_6400_td.py",
- "tools/package_target.py", "tools/package_6400_canonical.py",
- "tests/unit/test_6400_closure_separation.py",
- ]
- board_contracts = ["contracts/channel-map.yaml", "contracts/fan-control-parameters.yaml", "contracts/6400-manual.yaml"]
- return sorted(set(stable_sources + stable_tools + board_contracts))
- def current_paths() -> list[str]:
- base = set(base_paths())
- product = [
- "contracts/6400-snapshot.yaml", "contracts/6400-wire.yaml",
- "products/6400-front-rear/project.json", "products/6400-front-rear/source-closure.json",
- "products/6400-front-rear/analysis-replay-closure.json", "projects/registry.json",
- "constraints/prod2u_6400_front_back.adc", "constraints/prod2u_6400_front_back.sdc",
- "td/prod2u_6400_front_back.prj", "td/syn/prod2u_6400_front_back.tcl",
- "td/phy/prod2u_6400_front_back.tcl", "td/bitgen/prod2u_6400_front_back.tcl",
- ]
- generated_names = {
- "host-contract.json", "manual-uart-contract.json", "host-i2c-register-map.json",
- "golden-vectors.json", "snapshot-layout.json", "channel-map.json",
- "fan-control-parameters.json", "contract-sha256.txt", "prod2u_6400_v1_params.vh",
- "host-i2c-pin-evidence.json",
- }
- generated = [
- (ROOT / "generated/6400" / name).relative_to(ROOT).as_posix()
- for name in sorted(generated_names)
- if (ROOT / "generated/6400" / name).is_file()
- ]
- generated.append("docs/electrical/host-i2c-pin-evidence-lock.md")
- generated.append("docs/generated/6400-channel-map.md")
- specific_sources = [p for p in production_sources() if p not in base]
- focused = [p for p in replay_paths() if p not in base]
- focused.append("tests/unit/test_6400_canonical_packages.py")
- return sorted(set(product + generated + specific_sources + focused))
- def fingerprint(files: dict[str, bytes]) -> str:
- lines = [f"{name}\0{sha_bytes(data)}\0{role_for(name)}\n" for name, data in sorted(files.items())]
- return sha_bytes("".join(lines).encode())[:12]
- SELF_CHECK = r'''#!/usr/bin/env python3
- import hashlib,json,pathlib,sys,zipfile
- root=pathlib.Path(__file__).resolve().parent
- def sha(p): return hashlib.sha256(p.read_bytes()).hexdigest()
- for line in (root/'SHA256SUMS').read_text(encoding='utf-8').splitlines():
- digest,name=line.split(' ',1); p=root/name
- if not p.is_file() or sha(p)!=digest: raise SystemExit('HASH_MISMATCH '+name)
- manifest=json.loads((root/'PACKAGE-MANIFEST.json').read_text(encoding='utf-8'))
- for item in manifest['items']:
- p=root/item['path']
- if not p.is_file() or sha(p)!=item['sha256'] or p.stat().st_size!=item['size']:
- raise SystemExit('MANIFEST_MISMATCH '+item['path'])
- if manifest['profile']=='current' and not (root/'.base-overlay-present').exists():
- print('BASE_REQUIRED'); raise SystemExit(3)
- print('PASS')
- '''
- def common_payload(profile: str, commit: str, tree: str, selected: dict[str, bytes], extra: dict) -> dict[str, bytes]:
- items = [
- {"path": name, "sha256": sha_bytes(data), "size": len(data), "role": role_for(name),
- "source_commit": commit, "source_tree": tree}
- for name, data in sorted(selected.items())
- ]
- manifest = {"schema": "prod2u-package-manifest-v1", "profile": profile,
- "product": "6400-front-rear", "source_commit": commit,
- "source_tree": tree, "items": items, **extra}
- selected["PACKAGE-MANIFEST.json"] = (json.dumps(manifest, indent=2, sort_keys=True) + "\n").encode()
- selected["PACKAGE-SELF-CHECK.py"] = SELF_CHECK.encode()
- selected["START-HERE.zh-CN.md"] = (
- f"# 6400-front-rear {profile}\n\n先运行 `python3 PACKAGE-SELF-CHECK.py`。"
- "硬件、COM、JTAG 均未运行;不得把分析证据当作真机验收。\n"
- ).encode()
- selected["EXCLUSIONS.json"] = (json.dumps({"schema": "prod2u-package-exclusions-v1",
- "excluded": EXCLUSION_RULES}, indent=2, ensure_ascii=False, sort_keys=True) + "\n").encode()
- selected["SHA256SUMS"] = "".join(
- f"{sha_bytes(data)} {name}\n" for name, data in sorted(selected.items())
- ).encode()
- return selected
- def write_zip(path: Path, files: dict[str, bytes]) -> Path:
- path.parent.mkdir(parents=True, exist_ok=True)
- if path.exists():
- path.unlink()
- seen: set[str] = set()
- with zipfile.ZipFile(path, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as archive:
- for name, data in sorted(files.items()):
- safe_name(name)
- if name in seen:
- raise SystemExit(f"duplicate ZIP member: {name}")
- seen.add(name)
- info = zipfile.ZipInfo(name, FIXED_TIME)
- info.create_system = 3
- info.external_attr = (stat.S_IFREG | (0o755 if name == "PACKAGE-SELF-CHECK.py" else 0o644)) << 16
- archive.writestr(info, data, compress_type=zipfile.ZIP_DEFLATED, compresslevel=9)
- verify_zip(path)
- return path
- def verify_zip(path: Path) -> None:
- with zipfile.ZipFile(path) as archive:
- names = archive.namelist()
- if names != sorted(names) or len(names) != len(set(names)):
- raise SystemExit("ZIP members are not sorted/unique")
- for name in names:
- safe_name(name)
- for line in archive.read("SHA256SUMS").decode().splitlines():
- digest, name = line.split(" ", 1)
- if sha_bytes(archive.read(name)) != digest:
- raise SystemExit(f"package hash mismatch: {name}")
- if not set(COMMON).issubset(names):
- raise SystemExit("package common files missing")
- def extract_safe(path: Path, dest: Path) -> None:
- with zipfile.ZipFile(path) as archive:
- for info in archive.infolist():
- safe_name(info.filename)
- archive.extractall(dest)
- def package_base(output: Path) -> Path:
- commit, tree = clean_identity()
- selected = read_paths(base_paths())
- base_id = fingerprint(selected)
- selected["REFERENCE-POINTER.json"] = (json.dumps({"schema": "prod2u-reference-pointer-v1",
- "raw_reference_included": False, "source_status": "pointer-only",
- "board": "FCB V1.1"}, indent=2, sort_keys=True) + "\n").encode()
- payload = common_payload("base", commit, tree, selected, {"base_id": base_id})
- return write_zip(output / f"Prod2U-CPLD-Analysis-Base-{base_id}.zip", payload)
- def base_metadata(base_zip: Path) -> tuple[str, dict, str]:
- verify_zip(base_zip)
- with zipfile.ZipFile(base_zip) as archive:
- manifest_bytes = archive.read("PACKAGE-MANIFEST.json")
- manifest = json.loads(manifest_bytes)
- if manifest.get("profile") != "base":
- raise SystemExit("selected Base package is not profile=base")
- return str(manifest["base_id"]), manifest, sha_bytes(manifest_bytes)
- def package_current(output: Path, base_zip: Path) -> Path:
- commit, tree = clean_identity()
- base_id, _base_manifest, base_manifest_sha = base_metadata(base_zip)
- expected = fingerprint(read_paths(base_paths()))
- if expected != base_id:
- raise SystemExit(f"BASE_CHANGED expected {expected}; rebuild Base instead of overlaying changed Base files")
- selected = read_paths(current_paths())
- required = {"schema": "prod2u-base-required-v1", "base_id": base_id,
- "base_zip_sha256": sha_file(base_zip),
- "base_manifest_sha256": base_manifest_sha,
- "overlay_order": ["base", "current"], "current_commit": commit, "current_tree": tree}
- selected["BASE-REQUIRED.json"] = (json.dumps(required, indent=2, sort_keys=True) + "\n").encode()
- selected["OVERLAY-DELETIONS.json"] = b'{"schema":"prod2u-overlay-deletions-v1","paths":[]}\n'
- payload = common_payload("current", commit, tree, selected, {"base_id": base_id})
- path = write_zip(output / f"Prod2U-6400-Analysis-Current-{commit[:8]}-base-{base_id}.zip", payload)
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- extract_safe(base_zip, root)
- extract_safe(path, root)
- (root / ".base-overlay-present").write_text("base+current\n")
- subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root, check=True)
- subprocess.run([sys.executable, "tools/check_6400_closures.py"], cwd=root, check=True)
- subprocess.run([sys.executable, "tools/generate_6400_manual.py", "--check"], cwd=root, check=True)
- return path
- def package_delivery(output: Path, td_receipt: Path, gui_exe: Path, gui_zip: Path, status_json: Path) -> Path:
- package_commit, package_tree = clean_identity()
- receipt = json.loads(td_receipt.read_text())
- source_commit = str(receipt.get("commit", ""))
- if receipt.get("status") != "PASS" or len(source_commit) != 40:
- raise SystemExit("delivery TD receipt has no exact PASS source commit")
- if subprocess.run(
- ["git", "merge-base", "--is-ancestor", source_commit, package_commit],
- cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- ).returncode != 0:
- raise SystemExit("delivery source commit is not an ancestor of packager commit")
- bit = Path(str(receipt["bitstream"]))
- if not bit.is_absolute(): bit = td_receipt.parent / bit
- if sha_file(bit) != receipt.get("bitstream_sha256"):
- raise SystemExit("delivery bitstream hash mismatch")
- gui_meta = json.loads((gui_exe.parent / "gui-build-metadata.json").read_text())
- contract_sha = json.loads((ROOT / "generated/6400/host-contract.json").read_text())["contract_sha256"]
- if gui_meta != {"profile": "6400-front-rear", "commit": source_commit,
- "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit)}:
- raise SystemExit("delivery GUI metadata binding mismatch")
- external = {bit.name: bit, gui_exe.name: gui_exe, gui_zip.name: gui_zip,
- "TD-BUILD-RECEIPT.json": td_receipt, "CANDIDATE-STATUS.json": status_json}
- selected = {name: path.read_bytes() for name, path in external.items()}
- for relative in ["generated/6400/host-contract.json", "generated/6400/golden-vectors.json",
- "generated/6400/contract-sha256.txt"]:
- selected[relative] = (ROOT / relative).read_bytes()
- source_tree = git("rev-parse", f"{source_commit}^{{tree}}")
- binding = {"schema": "prod2u-artifact-delivery-binding-v1",
- "source_commit": source_commit, "source_tree": source_tree,
- "packager_commit": package_commit, "packager_tree": package_tree,
- "contract_sha256": contract_sha, "bitstream_sha256": sha_file(bit),
- "gui_sha256": sha_file(gui_exe), "hardware": "NOT_RUN"}
- selected["ARTIFACT-TO-DELIVERY-BINDING.json"] = (json.dumps(binding, indent=2, sort_keys=True) + "\n").encode()
- payload = common_payload("delivery", package_commit, package_tree, selected, binding)
- return write_zip(output / f"Prod2U-6400-Delivery-{source_commit[:8]}.zip", payload)
- def package_gui(output: Path, gui_exe: Path) -> Path:
- commit, tree = clean_identity()
- metadata_path = gui_exe.parent / "gui-build-metadata.json"
- metadata = json.loads(metadata_path.read_text(encoding="utf-8"))
- metadata_commit = str(metadata.get("commit", ""))
- if metadata.get("profile") != "6400-front-rear" or len(metadata_commit) != 40:
- raise SystemExit("GUI package metadata has no valid source identity")
- if subprocess.run(
- ["git", "merge-base", "--is-ancestor", metadata_commit, commit],
- cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
- ).returncode != 0:
- raise SystemExit("GUI package metadata source is not an ancestor of the clean identity")
- selected = {
- gui_exe.name: gui_exe.read_bytes(),
- metadata_path.name: metadata_path.read_bytes(),
- }
- payload = common_payload("gui", commit, tree, selected, {
- "contract_sha256": metadata["contract_sha256"],
- "bitstream_sha256": metadata["bitstream_sha256"],
- "gui_sha256": sha_file(gui_exe),
- })
- return write_zip(output / f"{gui_exe.stem}.zip", payload)
- def tamper_must_fail(path: Path) -> None:
- with tempfile.TemporaryDirectory() as tmp:
- root = Path(tmp)
- extract_safe(path, root)
- manifest = json.loads((root / "PACKAGE-MANIFEST.json").read_text())
- victim = root / manifest["items"][0]["path"]
- victim.write_bytes(victim.read_bytes() + b"X")
- result = subprocess.run([sys.executable, str(root / "PACKAGE-SELF-CHECK.py")], cwd=root)
- if result.returncode == 0:
- raise SystemExit("tamper self-check unexpectedly passed")
|