| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214 |
- #!/usr/bin/env python3
- """L0: contract SHA snapshot, gen_profile drift, gofmt, optional buf lint."""
- from __future__ import annotations
- import argparse
- import hashlib
- import json
- import os
- import subprocess
- import sys
- import tempfile
- from pathlib import Path
- HOST = Path(__file__).resolve().parents[1]
- REPO = HOST.parent
- SKIP_GO_PREFIXES = ("internal/gen/",)
- TOOLCHAIN_PATH_PREFIX = (
- "/data/prod2u/bin",
- "/data/prod2u/opt/go1.25.13/bin",
- "/opt/python-3.12/bin",
- "/usr/bin",
- "/bin",
- )
- def _ensure_toolchain_path() -> None:
- cur = os.environ.get("PATH", "")
- parts = [p for p in TOOLCHAIN_PATH_PREFIX if p]
- for p in cur.split(os.pathsep):
- if p and p not in parts:
- parts.append(p)
- os.environ["PATH"] = os.pathsep.join(parts)
- def sha256(path: Path) -> str:
- return hashlib.sha256(path.read_bytes()).hexdigest()
- def check_gofmt() -> list[str]:
- files: list[str] = []
- for path in HOST.rglob("*.go"):
- rel = path.relative_to(HOST).as_posix()
- if rel.startswith(SKIP_GO_PREFIXES) or "/gen/" in rel:
- continue
- files.append(str(path))
- if not files:
- return []
- out = subprocess.check_output(["gofmt", "-l", *files], text=True)
- return [line for line in out.splitlines() if line.strip()]
- def check_profile_drift() -> str | None:
- gen = HOST / "tools" / "gen_profile.py"
- committed = HOST / "profiles" / "prod2u-door-temp" / "profile.json"
- with tempfile.TemporaryDirectory() as tmp:
- out = Path(tmp) / "profile.json"
- subprocess.check_call([sys.executable, str(gen), "--repo-root", str(REPO), "--out", str(out)])
- got = json.loads(out.read_text(encoding="utf-8"))
- want = json.loads(committed.read_text(encoding="utf-8"))
- if got != want:
- return "gen_profile.py output differs from host/profiles/prod2u-door-temp/profile.json"
- return None
- def evidence() -> dict[str, str]:
- legacy = HOST / "contracts" / "evidence"
- old_generated = REPO / "src" / "generated"
- contract = old_generated / "host-contract.json"
- golden = old_generated / "golden-vectors.json"
- if not contract.is_file():
- contract = legacy / "host-contract.json"
- if not golden.is_file():
- golden = legacy / "golden-vectors.json"
- paths = {
- "host-contract.json": contract,
- "golden-vectors.json": golden,
- "legacy-RTL_REF.txt": legacy / "RTL_REF.txt",
- "legacy-SHA256SUMS": legacy / "SHA256SUMS",
- "6400-host-contract.json": HOST / "contracts" / "6400" / "host-contract.json",
- "6400-SHA256SUMS": HOST / "contracts" / "6400" / "SHA256SUMS",
- "profile.json": HOST / "profiles" / "prod2u-door-temp" / "profile.json",
- "hth.proto": HOST / "api" / "proto" / "hth" / "api" / "v1" / "hth.proto",
- }
- out: dict[str, str] = {}
- for name, path in paths.items():
- if path.is_file():
- out[name] = sha256(path)
- else:
- out[name] = "MISSING"
- return out
- def maybe_buf() -> str:
- try:
- buf = subprocess.run(["buf", "--version"], capture_output=True, text=True)
- except FileNotFoundError:
- return "buf: NOT RUN (binary missing)"
- if buf.returncode != 0:
- return "buf: NOT RUN (binary missing)"
- lint = subprocess.run(["buf", "lint"], cwd=HOST, capture_output=True, text=True)
- if lint.returncode != 0:
- return f"buf lint FAIL\n{lint.stdout}\n{lint.stderr}"
- desc = HOST / "api" / "proto" / "hth.api.v1.desc.prev"
- if desc.is_file():
- against = f"{desc}#format=binpb"
- brk = subprocess.run(
- ["buf", "breaking", "--against", against],
- cwd=HOST,
- capture_output=True,
- text=True,
- )
- if brk.returncode != 0:
- return f"buf breaking FAIL\n{brk.stdout}\n{brk.stderr}"
- return f"buf lint PASS; buf breaking PASS against {desc.name}"
- return "buf lint PASS; buf breaking NOT RUN (no previous descriptor)"
- def main() -> int:
- _ensure_toolchain_path()
- ap = argparse.ArgumentParser()
- ap.add_argument("--repo-root", type=Path, default=None)
- ap.add_argument("--evidence-root", type=Path, default=None)
- ap.add_argument(
- "--mode",
- choices=("offline", "release"),
- default="offline",
- help="offline: buf missing is PARTIAL; release: buf lint+breaking required",
- )
- args = ap.parse_args()
- global HOST, REPO
- if args.repo_root is not None:
- REPO = args.repo_root.resolve()
- if (REPO / "host" / "go.mod").is_file():
- HOST = REPO / "host"
- elif (REPO / "go.mod").is_file():
- HOST = REPO
- ev_root = args.evidence_root.resolve() if args.evidence_root else None
- ev = evidence()
- if ev_root is not None:
- for name in list(ev):
- alt = ev_root / name
- if alt.is_file():
- ev[name] = sha256(alt)
- print("L0_EVIDENCE_SHA256")
- for k, v in ev.items():
- print(f"{v} {k}")
- if v == "MISSING":
- print("L0_FAIL missing evidence file", k, file=sys.stderr)
- return 1
- dirty = check_gofmt()
- if dirty:
- print("L0_FAIL gofmt", file=sys.stderr)
- print("\n".join(dirty), file=sys.stderr)
- return 1
- print("gofmt: clean")
- drift = check_profile_drift()
- if drift:
- print("L0_FAIL", drift, file=sys.stderr)
- return 1
- print("gen_profile: no drift")
- oracle = HOST / "tools" / "protocol_oracle.py"
- golden = REPO / "src" / "generated" / "golden-vectors.json"
- if ev_root is not None and (ev_root / "golden-vectors.json").is_file():
- golden = ev_root / "golden-vectors.json"
- elif not golden.is_file() and (HOST / "contracts" / "evidence" / "golden-vectors.json").is_file():
- golden = HOST / "contracts" / "evidence" / "golden-vectors.json"
- o = subprocess.run(
- [
- sys.executable,
- str(oracle),
- "--golden",
- str(golden),
- "--min-positive",
- "8",
- "--min-negative",
- "2",
- "--min-frames",
- "6",
- ],
- capture_output=True,
- text=True,
- )
- print(o.stdout.strip())
- if o.returncode != 0:
- print("L0_FAIL oracle", file=sys.stderr)
- print(o.stderr, file=sys.stderr)
- return 1
- buf_line = maybe_buf()
- print(buf_line)
- buf_missing = "NOT RUN" in buf_line
- buf_fail = "FAIL" in buf_line
- if args.mode == "release":
- if buf_missing or buf_fail:
- print("L0_RELEASE_GATE_FAIL buf required", file=sys.stderr)
- print(buf_line, file=sys.stderr)
- return 1
- print("L0_RELEASE_CONTRACT_GATE_PASS")
- print("L0_CONTRACT_CHECK_PASS")
- return 0
- if buf_fail:
- print("L0_FAIL buf", file=sys.stderr)
- return 1
- if buf_missing:
- print("L0_OFFLINE_EVIDENCE_CHECK_PARTIAL")
- print("buf NOT RUN")
- return 0
- print("L0_OFFLINE_EVIDENCE_CHECK_PASS")
- print("L0_CONTRACT_CHECK_PASS")
- return 0
- if __name__ == "__main__":
- raise SystemExit(main())
|