| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132 |
- #!/usr/bin/env python3
- """Optional hardware/RTL evidence zip. No BRD/PDF/schematics."""
- from __future__ import annotations
- import hashlib
- import json
- import os
- import subprocess
- import time
- import zipfile
- from datetime import datetime, timezone
- from pathlib import Path
- from package_hth_review import write_zip_file, zip_file_mode
- def git_info(repo: Path) -> tuple[str, str]:
- env_head = os.environ.get("HTH_GIT_COMMIT", "").strip()
- if env_head:
- return env_head, os.environ.get("HTH_GIT_SHORT", env_head[:12])
- def run(args: list[str]) -> str:
- try:
- return subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True).strip()
- except (subprocess.CalledProcessError, FileNotFoundError):
- return "unknown"
- return run(["git", "rev-parse", "HEAD"]), run(["git", "rev-parse", "--short", "HEAD"])
- def main() -> int:
- host_root = Path(__file__).resolve().parents[1]
- repo = host_root.parent
- head, short = git_info(repo)
- run_id = os.environ.get("HTH_RUN_ID") or datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
- epoch = os.environ.get("SOURCE_DATE_EPOCH") or "1764000000"
- try:
- epoch = subprocess.check_output(["git", "log", "-1", "--format=%ct"], cwd=repo, text=True).strip()
- except (subprocess.CalledProcessError, FileNotFoundError):
- pass
- zip_date = time.gmtime(int(epoch))[:6]
- out_dir = Path(os.environ.get("HTH_PACKAGE_DIR") or "/tmp")
- out_dir.mkdir(parents=True, exist_ok=True)
- out = out_dir / f"hth-platform-hw-evidence-r6-{short}-{run_id}.zip"
- root = "hth-platform-hw-r6"
- files: list[tuple[str, bytes, int]] = []
- def add_file(rel: str, path: Path, mode: int | None = None) -> None:
- if not path.is_file() or path.stat().st_size >= 32 * 1024 * 1024:
- return
- files.append((f"{root}/{rel}", path.read_bytes(), mode or zip_file_mode(path)))
- rtl_allow = (
- "src/generated/host-contract.json",
- "src/generated/golden-vectors.json",
- "docs/prod2u-door-temp-protocol.zh-CN.md",
- "projects/prod2u-door-temp/project.json",
- )
- for rel in rtl_allow:
- add_file(rel, repo / rel)
- rtl_src = repo / "src"
- if rtl_src.is_dir():
- for p in sorted(rtl_src.rglob("*")):
- if not p.is_file():
- continue
- if p.suffix.lower() not in {".v", ".sv", ".vh", ".svh", ".vhdl", ".vhd"}:
- continue
- rel = str(p.relative_to(repo))
- if any(tok in rel for tok in ("build/", "sim_build/", "__pycache__", ".git")):
- continue
- add_file(rel, p)
- run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
- if run_dir:
- rd = Path(run_dir)
- for name in (
- "rtl-production-uart.log",
- "rtl-production-uart.meta",
- "rtl-raw.log",
- "rtl-frames.log",
- "rtl-result.txt",
- ):
- add_file(f"run/{name}", rd / name)
- for p in sorted(rd.glob("rtl*")):
- add_file(f"run/{p.name}", p)
- ident = {
- "package": "hth-platform-hw-evidence-r6",
- "git_commit": head,
- "git_short": short,
- "run_id": run_id,
- "note": "RTL/sim evidence only. BRD/PDF/schematics are not included.",
- }
- files.append((f"{root}/PACKAGE_IDENTITY.json", json.dumps(ident, indent=2).encode() + b"\n", 0o644))
- files.sort(key=lambda x: x[0])
- sha_lines = []
- man = []
- with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
- for name, data, mode in files:
- info_name = name
- zi = zipfile.ZipInfo(info_name)
- zi.create_system = 3
- zi.date_time = zip_date
- zi.external_attr = (mode & 0o777) << 16
- zi.compress_type = zipfile.ZIP_DEFLATED
- zf.writestr(zi, data)
- key = name[len(root) + 1 :]
- digest = hashlib.sha256(data).hexdigest()
- sha_lines.append(f"{digest} {key}")
- man.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": "hw"})
- write_zip_file(zf, f"{root}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode(), 0o644)
- write_zip_file(zf, f"{root}/MANIFEST.json", json.dumps(man, indent=2).encode() + b"\n", 0o644)
- digest = hashlib.sha256(out.read_bytes()).hexdigest()
- Path(str(out) + ".sha256").write_text(f"{digest} {out.name}\n", encoding="utf-8")
- att = {
- "filename": out.name,
- "bytes": out.stat().st_size,
- "sha256": digest,
- "git_commit": head,
- "run_id": run_id,
- "packager": "host/tools/package_hth_hw_evidence.py",
- "packager_version": "r6",
- }
- Path(str(out) + ".attestation.json").write_text(json.dumps(att, indent=2) + "\n", encoding="utf-8")
- print(f"zip={out}")
- print(f"bytes={out.stat().st_size}")
- print(f"sha256={digest}")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|