hw-verify-paths / build.py
nickh007's picture
Card: badges, worked example, portfolio block
261324a verified
Raw
History Blame Contribute Delete
5.44 kB
#!/usr/bin/env python3
"""Build hw-verify-paths: dependency graphs and witness paths, not just verdicts.
The first dataset records *what* each fixture is — CONSTANT_TIME or LEAKY. This one
records *why*: the full dependency graph of every module, and for the leaky ones the
concrete chain of signals carrying a secret to the observation.
That is a different artefact for a different audience. A verdict is a label, useful
for measuring a classifier. A witness path is a reasoning trace, which is what you
need to train or evaluate a model that has to *explain* a finding rather than just
emit one — and it is what a human needs to decide whether an over-approximate
analysis has cried wolf.
Everything here is computed from ctbench at build time. `--check` fails if the
committed data differs from a fresh build, so the data cannot drift from the code
that produced it.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
HERE = Path(__file__).resolve().parent
DATA = HERE / "data"
sys.path.insert(0, str(HERE.parent / "ctbench"))
from ctbench.cone import UNKNOWN, parse, verdict_for
from ctbench.explain import all_paths, explain
from ctbench.score import load_manifest
FIXTURES = HERE.parent / "ctbench" / "ctbench" / "fixtures"
ISC_FIXTURES = ("pcpi_div.v", "pcpi_mul.v", "pcpi_div_wiped.v", "pcpi_div_halfwipe.v")
MAX_PATHS = 8
def build_records() -> list[dict]:
man = load_manifest()
out = []
for entry in man["scored"] + man["unscored"]:
name = entry["file"]
src = (FIXTURES / name).read_text()
rec = {
"file": name,
"scored": entry in man["scored"],
"license": "ISC" if name in ISC_FIXTURES else "CC-BY-4.0",
"observation": entry.get("observation"),
"secrets": list(entry.get("secrets", [])),
"expected": entry.get("expected"),
"source": src,
}
try:
mod = parse(src, entry.get("module"))
except Exception as exc: # noqa: BLE001 - any refusal means no graph
# An unreadable fixture has no graph, and inventing an empty one would
# make it look like a design with no dependencies at all.
rec.update(verdict=UNKNOWN, refusal_reason=str(exc), graph=None,
n_signals=0, n_edges=0, paths=None, n_paths=0,
shortest_path_length=None)
out.append(rec)
continue
graph = {k: sorted(v) for k, v in sorted(mod.deps.items())}
rec["graph"] = json.dumps(graph)
rec["n_signals"] = len(set(graph) | {s for v in graph.values() for s in v})
rec["n_edges"] = sum(len(v) for v in graph.values())
obs, secrets = entry.get("observation"), list(entry.get("secrets", []))
if not obs or not secrets:
rec.update(verdict=None, refusal_reason=None, paths=None, n_paths=0,
shortest_path_length=None)
out.append(rec)
continue
try:
v = verdict_for(mod, obs, secrets)
except Exception as exc: # noqa: BLE001 - any refusal means no verdict
rec.update(verdict=UNKNOWN, refusal_reason=str(exc), paths=None,
n_paths=0, shortest_path_length=None)
out.append(rec)
continue
rec["verdict"] = v.status
rec["refusal_reason"] = None
rec["reaching_secrets"] = v.reaching
rec["cone_size"] = v.cone_size
paths = []
for secret in v.reaching:
for p in all_paths(mod, obs, secret, limit=MAX_PATHS):
paths.append(p.to_dict())
rec["paths"] = json.dumps(paths) if paths else None
rec["n_paths"] = len(paths)
rec["shortest_path_length"] = min((p["length"] for p in paths), default=None)
rec["explanation"] = explain(mod, v).render() if v.reaching else None
out.append(rec)
return out
def main() -> int:
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--check", action="store_true",
help="fail if the committed data differs from a fresh build")
args = ap.parse_args()
records = build_records()
# Uniform schema: every record carries every key, so the split loads as one table.
keys = sorted({k for r in records for k in r})
for r in records:
for k in keys:
r.setdefault(k, None)
text = "\n".join(json.dumps({k: r[k] for k in keys}, sort_keys=True) for r in records) + "\n"
target = DATA / "witness_paths.jsonl"
if args.check:
if not target.is_file() or target.read_text() != text:
print("data/witness_paths.jsonl differs from a fresh build — rerun build.py",
file=sys.stderr)
return 1
print(f"committed data matches a fresh build ({len(records)} records)")
return 0
DATA.mkdir(exist_ok=True)
target.write_text(text)
leaky = [r for r in records if r.get("verdict") == "LEAKY"]
print("hw-verify-paths")
print(f" records {len(records)}")
print(f" with a graph {sum(1 for r in records if r.get('graph'))}")
print(f" leaky, with paths {sum(1 for r in leaky if r.get('paths'))}")
print(f" total paths {sum(r.get('n_paths') or 0 for r in records)}")
return 0
if __name__ == "__main__":
raise SystemExit(main())