l0_contract_check.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. #!/usr/bin/env python3
  2. """L0: contract SHA snapshot, gen_profile drift, gofmt, optional buf lint."""
  3. from __future__ import annotations
  4. import argparse
  5. import hashlib
  6. import json
  7. import subprocess
  8. import sys
  9. import tempfile
  10. from pathlib import Path
  11. HOST = Path(__file__).resolve().parents[1]
  12. REPO = HOST.parent
  13. SKIP_GO_PREFIXES = ("internal/gen/",)
  14. def sha256(path: Path) -> str:
  15. return hashlib.sha256(path.read_bytes()).hexdigest()
  16. def check_gofmt() -> list[str]:
  17. files: list[str] = []
  18. for path in HOST.rglob("*.go"):
  19. rel = path.relative_to(HOST).as_posix()
  20. if rel.startswith(SKIP_GO_PREFIXES) or "/gen/" in rel:
  21. continue
  22. files.append(str(path))
  23. if not files:
  24. return []
  25. out = subprocess.check_output(["gofmt", "-l", *files], text=True)
  26. return [line for line in out.splitlines() if line.strip()]
  27. def check_profile_drift() -> str | None:
  28. gen = HOST / "tools" / "gen_profile.py"
  29. committed = HOST / "profiles" / "prod2u-door-temp" / "profile.json"
  30. with tempfile.TemporaryDirectory() as tmp:
  31. out = Path(tmp) / "profile.json"
  32. subprocess.check_call([sys.executable, str(gen), "--repo-root", str(REPO), "--out", str(out)])
  33. got = json.loads(out.read_text(encoding="utf-8"))
  34. want = json.loads(committed.read_text(encoding="utf-8"))
  35. if got != want:
  36. return "gen_profile.py output differs from host/profiles/prod2u-door-temp/profile.json"
  37. return None
  38. def evidence() -> dict[str, str]:
  39. paths = {
  40. "host-contract.json": REPO / "src" / "generated" / "host-contract.json",
  41. "golden-vectors.json": REPO / "src" / "generated" / "golden-vectors.json",
  42. "prod2u-door-temp-protocol.zh-CN.md": REPO / "docs" / "prod2u-door-temp-protocol.zh-CN.md",
  43. "project.json": REPO / "projects" / "prod2u-door-temp" / "project.json",
  44. "profile.json": HOST / "profiles" / "prod2u-door-temp" / "profile.json",
  45. "hth.proto": HOST / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
  46. }
  47. out: dict[str, str] = {}
  48. for name, path in paths.items():
  49. if path.is_file():
  50. out[name] = sha256(path)
  51. else:
  52. out[name] = "MISSING"
  53. return out
  54. def maybe_buf() -> str:
  55. try:
  56. buf = subprocess.run(["buf", "--version"], capture_output=True, text=True)
  57. except FileNotFoundError:
  58. return "buf: NOT RUN (binary missing)"
  59. if buf.returncode != 0:
  60. return "buf: NOT RUN (binary missing)"
  61. lint = subprocess.run(["buf", "lint"], cwd=HOST, capture_output=True, text=True)
  62. if lint.returncode != 0:
  63. return f"buf lint FAIL\n{lint.stdout}\n{lint.stderr}"
  64. desc = HOST / "api" / "proto" / "hth.api.v1.desc.prev"
  65. if desc.is_file():
  66. against = f"{desc}#format=binpb"
  67. brk = subprocess.run(
  68. ["buf", "breaking", "--against", against],
  69. cwd=HOST,
  70. capture_output=True,
  71. text=True,
  72. )
  73. if brk.returncode != 0:
  74. return f"buf breaking FAIL\n{brk.stdout}\n{brk.stderr}"
  75. return f"buf lint PASS; buf breaking PASS against {desc.name}"
  76. return "buf lint PASS; buf breaking NOT RUN (no previous descriptor)"
  77. def main() -> int:
  78. ap = argparse.ArgumentParser()
  79. ap.add_argument("--repo-root", type=Path, default=None)
  80. ap.add_argument("--evidence-root", type=Path, default=None)
  81. args = ap.parse_args()
  82. global HOST, REPO
  83. if args.repo_root is not None:
  84. REPO = args.repo_root.resolve()
  85. if (REPO / "host" / "go.mod").is_file():
  86. HOST = REPO / "host"
  87. elif (REPO / "go.mod").is_file():
  88. HOST = REPO
  89. ev_root = args.evidence_root.resolve() if args.evidence_root else None
  90. ev = evidence()
  91. if ev_root is not None:
  92. for name in list(ev):
  93. alt = ev_root / name
  94. if alt.is_file():
  95. ev[name] = sha256(alt)
  96. print("L0_EVIDENCE_SHA256")
  97. for k, v in ev.items():
  98. print(f"{v} {k}")
  99. if v == "MISSING":
  100. print("L0_FAIL missing evidence file", k, file=sys.stderr)
  101. return 1
  102. dirty = check_gofmt()
  103. if dirty:
  104. print("L0_FAIL gofmt", file=sys.stderr)
  105. print("\n".join(dirty), file=sys.stderr)
  106. return 1
  107. print("gofmt: clean")
  108. drift = check_profile_drift()
  109. if drift:
  110. print("L0_FAIL", drift, file=sys.stderr)
  111. return 1
  112. print("gen_profile: no drift")
  113. oracle = HOST / "tools" / "protocol_oracle.py"
  114. golden = REPO / "src" / "generated" / "golden-vectors.json"
  115. if ev_root is not None and (ev_root / "golden-vectors.json").is_file():
  116. golden = ev_root / "golden-vectors.json"
  117. elif not golden.is_file() and (REPO / "evidence" / "golden-vectors.json").is_file():
  118. golden = REPO / "evidence" / "golden-vectors.json"
  119. o = subprocess.run(
  120. [
  121. sys.executable,
  122. str(oracle),
  123. "--golden",
  124. str(golden),
  125. "--min-positive",
  126. "8",
  127. "--min-negative",
  128. "2",
  129. "--min-frames",
  130. "6",
  131. ],
  132. capture_output=True,
  133. text=True,
  134. )
  135. print(o.stdout.strip())
  136. if o.returncode != 0:
  137. print("L0_FAIL oracle", file=sys.stderr)
  138. print(o.stderr, file=sys.stderr)
  139. return 1
  140. print(maybe_buf())
  141. print("L0_CONTRACT_CHECK_PASS")
  142. return 0
  143. if __name__ == "__main__":
  144. raise SystemExit(main())