package_hth_hw_evidence.py 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132
  1. #!/usr/bin/env python3
  2. """Optional hardware/RTL evidence zip. No BRD/PDF/schematics."""
  3. from __future__ import annotations
  4. import hashlib
  5. import json
  6. import os
  7. import subprocess
  8. import time
  9. import zipfile
  10. from datetime import datetime, timezone
  11. from pathlib import Path
  12. from package_hth_review import write_zip_file, zip_file_mode
  13. def git_info(repo: Path) -> tuple[str, str]:
  14. env_head = os.environ.get("HTH_GIT_COMMIT", "").strip()
  15. if env_head:
  16. return env_head, os.environ.get("HTH_GIT_SHORT", env_head[:12])
  17. def run(args: list[str]) -> str:
  18. try:
  19. return subprocess.check_output(args, cwd=repo, stderr=subprocess.DEVNULL, text=True).strip()
  20. except (subprocess.CalledProcessError, FileNotFoundError):
  21. return "unknown"
  22. return run(["git", "rev-parse", "HEAD"]), run(["git", "rev-parse", "--short", "HEAD"])
  23. def main() -> int:
  24. host_root = Path(__file__).resolve().parents[1]
  25. repo = host_root.parent
  26. head, short = git_info(repo)
  27. run_id = os.environ.get("HTH_RUN_ID") or datetime.now(timezone.utc).strftime("%Y%m%dT%H%M%SZ")
  28. epoch = os.environ.get("SOURCE_DATE_EPOCH") or "1764000000"
  29. try:
  30. epoch = subprocess.check_output(["git", "log", "-1", "--format=%ct"], cwd=repo, text=True).strip()
  31. except (subprocess.CalledProcessError, FileNotFoundError):
  32. pass
  33. zip_date = time.gmtime(int(epoch))[:6]
  34. out_dir = Path(os.environ.get("HTH_PACKAGE_DIR") or "/tmp")
  35. out_dir.mkdir(parents=True, exist_ok=True)
  36. out = out_dir / f"hth-platform-hw-evidence-r6-{short}-{run_id}.zip"
  37. root = "hth-platform-hw-r6"
  38. files: list[tuple[str, bytes, int]] = []
  39. def add_file(rel: str, path: Path, mode: int | None = None) -> None:
  40. if not path.is_file() or path.stat().st_size >= 32 * 1024 * 1024:
  41. return
  42. files.append((f"{root}/{rel}", path.read_bytes(), mode or zip_file_mode(path)))
  43. rtl_allow = (
  44. "src/generated/host-contract.json",
  45. "src/generated/golden-vectors.json",
  46. "docs/prod2u-door-temp-protocol.zh-CN.md",
  47. "projects/prod2u-door-temp/project.json",
  48. )
  49. for rel in rtl_allow:
  50. add_file(rel, repo / rel)
  51. rtl_src = repo / "src"
  52. if rtl_src.is_dir():
  53. for p in sorted(rtl_src.rglob("*")):
  54. if not p.is_file():
  55. continue
  56. if p.suffix.lower() not in {".v", ".sv", ".vh", ".svh", ".vhdl", ".vhd"}:
  57. continue
  58. rel = str(p.relative_to(repo))
  59. if any(tok in rel for tok in ("build/", "sim_build/", "__pycache__", ".git")):
  60. continue
  61. add_file(rel, p)
  62. run_dir = os.environ.get("HTH_RUN_DIR", "").strip()
  63. if run_dir:
  64. rd = Path(run_dir)
  65. for name in (
  66. "rtl-production-uart.log",
  67. "rtl-production-uart.meta",
  68. "rtl-raw.log",
  69. "rtl-frames.log",
  70. "rtl-result.txt",
  71. ):
  72. add_file(f"run/{name}", rd / name)
  73. for p in sorted(rd.glob("rtl*")):
  74. add_file(f"run/{p.name}", p)
  75. ident = {
  76. "package": "hth-platform-hw-evidence-r6",
  77. "git_commit": head,
  78. "git_short": short,
  79. "run_id": run_id,
  80. "note": "RTL/sim evidence only. BRD/PDF/schematics are not included.",
  81. }
  82. files.append((f"{root}/PACKAGE_IDENTITY.json", json.dumps(ident, indent=2).encode() + b"\n", 0o644))
  83. files.sort(key=lambda x: x[0])
  84. sha_lines = []
  85. man = []
  86. with zipfile.ZipFile(out, "w", compression=zipfile.ZIP_DEFLATED, compresslevel=9) as zf:
  87. for name, data, mode in files:
  88. info_name = name
  89. zi = zipfile.ZipInfo(info_name)
  90. zi.create_system = 3
  91. zi.date_time = zip_date
  92. zi.external_attr = (mode & 0o777) << 16
  93. zi.compress_type = zipfile.ZIP_DEFLATED
  94. zf.writestr(zi, data)
  95. key = name[len(root) + 1 :]
  96. digest = hashlib.sha256(data).hexdigest()
  97. sha_lines.append(f"{digest} {key}")
  98. man.append({"path": key, "size": len(data), "mode": f"{mode:04o}", "sha256": digest, "source_class": "hw"})
  99. write_zip_file(zf, f"{root}/SHA256SUMS", ("\n".join(sha_lines) + "\n").encode(), 0o644)
  100. write_zip_file(zf, f"{root}/MANIFEST.json", json.dumps(man, indent=2).encode() + b"\n", 0o644)
  101. digest = hashlib.sha256(out.read_bytes()).hexdigest()
  102. Path(str(out) + ".sha256").write_text(f"{digest} {out.name}\n", encoding="utf-8")
  103. att = {
  104. "filename": out.name,
  105. "bytes": out.stat().st_size,
  106. "sha256": digest,
  107. "git_commit": head,
  108. "run_id": run_id,
  109. "packager": "host/tools/package_hth_hw_evidence.py",
  110. "packager_version": "r6",
  111. }
  112. Path(str(out) + ".attestation.json").write_text(json.dumps(att, indent=2) + "\n", encoding="utf-8")
  113. print(f"zip={out}")
  114. print(f"bytes={out.stat().st_size}")
  115. print(f"sha256={digest}")
  116. return 0
  117. if __name__ == "__main__":
  118. raise SystemExit(main())