hw-verify / build.py
nickh007's picture
hw-verify v1.0.0: 49 records across 3 splits, byte-reproducible from the open tools
6d72c48 verified
Raw
History Blame Contribute Delete
8.31 kB
#!/usr/bin/env python3
"""Build the hw-verify dataset from the packages' real artifacts.
Every record here is *computed*, not transcribed: the RTL split reads the actual
fixture sources, the masking split runs the actual prover over every probe of every
gadget, and the patch split runs the actual solver and emits the certificates it
produces. Re-running this script must reproduce the committed files byte for byte,
and a test asserts exactly that — so the data cannot drift from the code that made
it.
python build.py # regenerate data/ in place
python build.py --check # fail if the committed data is stale
Three splits, because they answer three different questions and have three
different schemas. Flattening them into one table would force null columns
everywhere and make the licence field meaningless.
"""
from __future__ import annotations
import argparse
import json
import sys
from pathlib import Path
from typing import Any
from ctbench.cli import FIXTURES, run_reference
from ctbench.score import load_manifest
from ctbench.score import score as ct_score
from ctmask.analysis import analyse as mask_analyse
from ctmask.gadgets import GADGETS
from ctmask.gadgets import build as mask_build
from patchproof.linear import replay as pp_replay
from patchproof.model import CLASSES, OUT_OF_MODEL, REAL_CLASSES
from patchproof.prover import prove as pp_prove
HERE = Path(__file__).resolve().parent
DATA = HERE / "data"
#: Four fixtures derive from picorv32 and stay under the upstream ISC licence.
ISC_FIXTURES = frozenset({
"pcpi_div.v", "pcpi_mul.v", "pcpi_div_wiped.v", "pcpi_div_halfwipe.v",
})
# ---------------------------------------------------------------------------
# Split 1 — RTL constant-time fixtures
# ---------------------------------------------------------------------------
def build_rtl() -> list[dict[str, Any]]:
"""One record per Verilog fixture, with the full source inlined."""
man = load_manifest()
rows: list[dict[str, Any]] = []
def row(e: dict, scored: bool) -> dict[str, Any]:
return {
"file": e["file"],
"module": e["module"],
"source": (FIXTURES / e["file"]).read_text(),
"scored": scored,
"label": e["expected"] if scored else None,
"observation": e["observation"] if scored else None,
"secrets": e["secrets"] if scored else [],
"pair": e.get("pair") if scored else None,
"role": e.get("role") if scored else None,
"note": e.get("note", "") if scored else "",
"reason": None if scored else e["reason"],
"license": "ISC" if e["file"] in ISC_FIXTURES else "CC-BY-4.0",
}
rows += [row(e, True) for e in man["scored"]]
rows += [row(e, False) for e in man["unscored"]]
return rows
# ---------------------------------------------------------------------------
# Split 2 — masking probe verdicts
# ---------------------------------------------------------------------------
def build_masking() -> list[dict[str, Any]]:
"""One record per *probe* of every bundled gadget, with its certificate.
Probe-level rather than gadget-level, because the interesting datum is which
certificate discharged which wire — that is what separates this analysis from
a dependence-only one.
"""
rows: list[dict[str, Any]] = []
for name in sorted(GADGETS):
expected = GADGETS[name][1]
rep = mask_analyse(mask_build(name))
rows.extend(
{
"gadget": name,
"gadget_expected": expected,
"gadget_verdict": "SECURE" if rep.secure else "LEAKY",
"probe": p.probe,
"secure": p.secure,
"certificate": p.certificate,
"refreshed_by": p.masking_wire,
"touches_shares": json.dumps(p.touches, sort_keys=True),
"secret_classes": rep.secret_classes,
"mean_invariant": rep.mean_invariant,
"distribution_invariant": rep.distribution_invariant,
"model": rep.model,
"license": "Apache-2.0",
}
for p in rep.probes
)
return rows
# ---------------------------------------------------------------------------
# Split 3 — patch-completeness certificates
# ---------------------------------------------------------------------------
def build_patches() -> list[dict[str, Any]]:
"""One record per modelled defect class, with witnesses and the certificate."""
rows: list[dict[str, Any]] = []
for key in list(REAL_CLASSES) + [k for k in sorted(CLASSES) if k not in REAL_CLASSES]:
r = pp_prove(key)
cert = r.certificate.to_dict() if r.certificate else None
replayed = pp_replay(cert)[0] if cert else None
rows.append({
"defect_class": key,
"title": r.title,
"is_demo": key not in REAL_CLASSES,
"verdict": r.verdict,
"widths": json.dumps(r.widths, sort_keys=True),
"total_width": r.total_width,
"exploit_witness": json.dumps(r.exploit.values, sort_keys=True) if r.exploit else None,
"incompleteness_witness": (
json.dumps(r.incompleteness_witness.values, sort_keys=True)
if r.incompleteness_witness else None
),
"violating_region_measure": r.violating_measure,
"bit_precise_leg": r.complete,
"elimination_certificate": json.dumps(cert, sort_keys=True) if cert else None,
"certificate_replays_without_solver": replayed,
"legs_agree": r.legs_agree,
"strictly_stronger_than_unsound_guard": r.strictly_stronger,
"out_of_model": json.dumps(OUT_OF_MODEL),
"license": "Apache-2.0",
})
return rows
# ---------------------------------------------------------------------------
# Baseline, so the dataset ships a reference result rather than only inputs.
# ---------------------------------------------------------------------------
def build_baseline() -> dict[str, Any]:
man = load_manifest()
verdicts = run_reference(man)
s = ct_score(verdicts, man)
return {
"tool": "ctbench reference checker (syntactic cone-of-influence)",
"split": "rtl_constant_time",
"method": (
"Fan-in cone of the observation signal, including every enclosing if/case "
"guard, intersected with the declared secret inputs. Over-approximate, so "
"CONSTANT_TIME is conservative."
),
"verdicts": verdicts,
"score": s.to_dict(),
}
SPLITS = {
"rtl_constant_time": build_rtl,
"masking_probes": build_masking,
"patch_certificates": build_patches,
}
def write(check_only: bool = False) -> int:
DATA.mkdir(parents=True, exist_ok=True)
stale: list[str] = []
for name, builder in SPLITS.items():
rows = builder()
text = "".join(json.dumps(r, sort_keys=True) + "\n" for r in rows)
path = DATA / f"{name}.jsonl"
if check_only:
if not path.is_file() or path.read_text() != text:
stale.append(path.name)
else:
path.write_text(text)
print(f" {name:<22} {len(rows):>4} records")
baseline = json.dumps(build_baseline(), indent=2, sort_keys=True) + "\n"
bpath = DATA / "baseline.json"
if check_only:
if not bpath.is_file() or bpath.read_text() != baseline:
stale.append(bpath.name)
else:
bpath.write_text(baseline)
print(f" {'baseline':<22} {'1':>4} record")
if check_only:
if stale:
print(f"\nSTALE: {', '.join(stale)} — run `python build.py`")
return 1
print("\nCommitted data matches a fresh build.")
return 0
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()
print("hw-verify dataset" + (" (check)" if args.check else ""))
return write(check_only=args.check)
if __name__ == "__main__":
sys.exit(main())