#!/usr/bin/env python3
"""Qrypto Trust Release 1 - open certificate verifier, built to Bill's specification.

Owner, 2026-10-08: "if we can implement, do it... don't tell me something is missing when you
know the next command is build it if you can safely."

A conformance pass found 31% of Release 1 built. The largest gap was not a weak verifier but a
MISSING one: zap_verify.py validates the ZAP tunnel bundle (kem_ct || n1 || n2 || sig || ct2)
and does that well, while Bill's verifier validates a CERTIFICATE - identity digest, issuer
binding, policy digest, validity window, revocation, and rejection-sampling bounds. Different
artifacts. This is the certificate verifier.

WHY THIS IS SAFE TO BUILD NOW. It is pure Python over pqcrypto's ML-DSA-44 and touches nothing
in the shipped Rust NIF, so the G1 hedged-signing and G4 verify-after-sign gates on the tunnel
path are not at risk. The generator half exists only to produce artifacts to verify, and the
negative-test battery to produce BAD ones.

WHAT IS GENUINELY CHECKED, not merely asserted. "Rejection-sampling validation" is only
meaningful if the signature is actually decoded, so sigDecode is implemented per FIPS 204
Algorithm 27 for ML-DSA-44 (sigma = c_tilde(32) || z(2304) || h(84) = 2420 bytes):
  - ||z||inf < gamma1 - beta  (131072 - 78 = 130994), from the 18-bit packed coefficients
  - hint weight <= omega (80), cutoffs non-decreasing, indices strictly increasing per poly
These are public acceptance rules computable from the signature alone - exactly the public
bridge Bill describes, and the part that makes the verifier more than a wrapper around verify().

FAIL vs INCONCLUSIVE is held apart, per S7.5. Contradictory evidence fails closed with the most
specific reason code; MISSING evidence returns inconclusive. Collapsing the two is how a
verifier fails open.

  python release1_verify.py self-test
  python release1_verify.py verify-cert <cert.json>
  python release1_verify.py explain-rejection <cert.json>
"""
import argparse
import datetime
import hashlib
import json
import os
import sys

try:
    sys.stdout.reconfigure(encoding="utf-8", errors="replace")
except Exception:
    pass

from pqcrypto.sign import ml_dsa_44 as MLDSA

TOOL = {"name": "release1-verifier", "version": "1.0.0", "profile": "open-reference"}
PARAM_SET = "ML-DSA-44"

# ---- FIPS 204 ML-DSA-44 parameters -------------------------------------------------
N = 256
K, L = 4, 4
GAMMA1 = 1 << 17
TAU, ETA = 39, 2
BETA = TAU * ETA                 # 78
OMEGA = 80
CTILDE_BYTES = 32
Z_BITS = 18                      # bitlen(2*gamma1 - 1)
Z_BYTES = L * N * Z_BITS // 8    # 2304
H_BYTES = OMEGA + K              # 84
SIG_BYTES = CTILDE_BYTES + Z_BYTES + H_BYTES   # 2420

# ---- reason codes, Bill S6.1 / S7.5 ------------------------------------------------
R = {
    "MALFORMED": "malformed_input",
    "PARAM": "parameter_mismatch",
    "PROFILE": "profile_mismatch",
    "IDENTITY": "identity_mismatch",
    "ISSUER": "issuer_key_mismatch",
    "POLICY": "policy_digest_mismatch",
    "SIG": "invalid_signature",
    "NORM": "norm_bound_failure",
    "HINT": "hint_density_failure",
    "REJ": "rejection_sampling_failure",
    "BINDING": "report_binding_mismatch",
    "SIGREP": "signature_report_mismatch",
    "REPLAY": "stale_report_replay",
    "ENT_HEALTH": "entropy_health_test_failure",
    "ENT_PROV": "entropy_provenance_failure",
}


def sha256(b):
    return hashlib.sha256(b).hexdigest()


def canon(obj):
    """Canonical bytes for hashing. Sorted keys, no whitespace - so two parties agree."""
    return json.dumps(obj, sort_keys=True, separators=(",", ":")).encode()


# ---- S5 / S6.1: canonical identity --------------------------------------------------
def identity_digest(cert):
    """ID = H(subject || pk_subject || issuer || validity || policy), per S5.

    Field ORDER is part of the definition: a verifier that hashes a different order computes
    a different ID and rejects every certificate. Pinned here and shared with the generator.
    """
    payload = {
        "subject": cert.get("subject"),
        "subject_pk": cert.get("subject_pk"),
        "issuer": cert.get("issuer"),
        "valid_from": cert.get("valid_from"),
        "valid_to": cert.get("valid_to"),
        "policy": cert.get("policy"),
    }
    return sha256(canon(payload))


# ---- S6.1: rejection-sampling validation (real decode, not a stub) ------------------
def _bitunpack_z(buf):
    """l*256 coefficients, 18 bits each, little-endian bit order (FIPS 204 BitUnpack).

    Stored value s maps to the signed coefficient as z = gamma1 - s.
    """
    coeffs = []
    acc = 0
    nbits = 0
    idx = 0
    total = L * N
    for byte in buf:
        acc |= byte << nbits
        nbits += 8
        while nbits >= Z_BITS and idx < total:
            coeffs.append(GAMMA1 - (acc & ((1 << Z_BITS) - 1)))
            acc >>= Z_BITS
            nbits -= Z_BITS
            idx += 1
    return coeffs


def sig_decode(sig):
    """sigma -> (c_tilde, z coefficients, hint bytes). Raises ValueError if malformed."""
    if not isinstance(sig, (bytes, bytearray)):
        raise ValueError("signature is not bytes")
    if len(sig) != SIG_BYTES:
        raise ValueError("signature length %d != %d" % (len(sig), SIG_BYTES))
    c = bytes(sig[:CTILDE_BYTES])
    z = _bitunpack_z(sig[CTILDE_BYTES:CTILDE_BYTES + Z_BYTES])
    h = bytes(sig[CTILDE_BYTES + Z_BYTES:])
    if len(z) != L * N:
        raise ValueError("z unpacked to %d coefficients, expected %d" % (len(z), L * N))
    return c, z, h


def check_norm(z):
    """||z||inf < gamma1 - beta. The public half of the signer's rejection condition."""
    bound = GAMMA1 - BETA
    worst = max(abs(c) for c in z)
    return worst < bound, worst, bound


def check_hint(h):
    """Hint weight <= omega, cutoffs non-decreasing, indices strictly increasing per poly."""
    idxs, cuts = h[:OMEGA], h[OMEGA:]
    if len(cuts) != K:
        return False, 0, "cutoff section is %d bytes, expected %d" % (len(cuts), K)
    prev = 0
    for i, c in enumerate(cuts):
        if c < prev or c > OMEGA:
            return False, cuts[-1], "cutoff %d at poly %d is out of order or > omega" % (c, i)
        seg = idxs[prev:c]
        for a, b in zip(seg, seg[1:]):
            if b <= a:
                return False, cuts[-1], "hint indices not strictly increasing in poly %d" % i
        prev = c
    weight = cuts[-1] if cuts else 0
    for b in idxs[weight:]:
        if b != 0:
            return False, weight, "non-zero padding beyond the declared hint weight"
    return True, weight, None


# ---- verification -------------------------------------------------------------------
def verify_cert(cert, now=None, trusted_issuers=None, known_report_hashes=None):
    """Return Bill's S6.5 report. overall_result in {pass, fail, inconclusive}."""
    now = now or datetime.datetime.now(datetime.timezone.utc)
    checks = []
    fails = []
    inconclusive = []

    def note(name, ok, code=None, detail=""):
        checks.append({"check": name, "result": "pass" if ok else "fail",
                       "reason_code": None if ok else code, "detail": detail})
        if not ok:
            fails.append(code)

    def missing(name, code, detail):
        checks.append({"check": name, "result": "inconclusive",
                       "reason_code": code, "detail": detail})
        inconclusive.append(code)

    # --- input parsing ---------------------------------------------------------------
    required = ("subject", "subject_pk", "issuer", "issuer_pk", "valid_from", "valid_to",
                "policy", "identity", "signature", "parameter_set")
    absent = [f for f in required if cert.get(f) in (None, "")]
    if absent:
        missing("input_parse", R["MALFORMED"], "missing field(s): %s" % ", ".join(absent))
        return _report(cert, checks, fails, inconclusive)
    note("input_parse", True, detail="all required fields present")

    if cert.get("parameter_set") != PARAM_SET:
        note("parameter_set", False, R["PARAM"],
             "declared %r, this verifier validates %r" % (cert.get("parameter_set"), PARAM_SET))
    else:
        note("parameter_set", True, detail=PARAM_SET)

    prof = cert.get("profile", "software-only")
    if prof not in ("software-only", "enhanced-platform"):
        note("profile", False, R["PROFILE"], "unrecognised profile %r" % prof)
    elif prof == "enhanced-platform" and not cert.get("platform_attestation"):
        # S6.1: the enhanced profile REQUIRES attestations. Absent evidence is inconclusive,
        # not a failure - we cannot say the platform is bad, only that it is unproven.
        missing("profile_evidence", R["PROFILE"],
                "enhanced-platform declared without platform_attestation")
    else:
        note("profile", True, detail=prof)

    # --- canonical identity ----------------------------------------------------------
    recomputed = identity_digest(cert)
    note("identity_recompute", recomputed == cert.get("identity"), R["IDENTITY"],
         "recomputed %s..., certificate carries %s..."
         % (recomputed[:16], str(cert.get("identity"))[:16]))

    # --- issuer trust ----------------------------------------------------------------
    try:
        issuer_pk = bytes.fromhex(cert["issuer_pk"])
    except Exception:
        note("issuer_key", False, R["MALFORMED"], "issuer_pk is not hex")
        return _report(cert, checks, fails, inconclusive)
    if trusted_issuers is None:
        missing("issuer_trust", R["ISSUER"], "no trust anchor supplied to the verifier")
    elif sha256(issuer_pk) not in trusted_issuers:
        note("issuer_trust", False, R["ISSUER"], "issuer key is not a trusted anchor")
    else:
        note("issuer_trust", True, detail="issuer key hash %s..." % sha256(issuer_pk)[:16])

    # --- lifecycle -------------------------------------------------------------------
    try:
        vf = datetime.datetime.fromisoformat(cert["valid_from"].replace("Z", "+00:00"))
        vt = datetime.datetime.fromisoformat(cert["valid_to"].replace("Z", "+00:00"))
        if now < vf:
            note("validity_window", False, R["REPLAY"], "certificate is not yet valid")
        elif now > vt:
            note("validity_window", False, R["REPLAY"], "certificate expired %s" % cert["valid_to"])
        else:
            note("validity_window", True, detail="%s .. %s" % (cert["valid_from"], cert["valid_to"]))
    except Exception as e:
        note("validity_window", False, R["MALFORMED"], "unparseable validity: %s" % e)

    if cert.get("revoked"):
        note("revocation", False, R["REPLAY"], "certificate is marked revoked")
    elif "revoked" not in cert:
        missing("revocation", R["REPLAY"], "no revocation evidence supplied")
    else:
        note("revocation", True, detail="not revoked")

    # --- policy digest ---------------------------------------------------------------
    pd = cert.get("policy_digest")
    if pd is None:
        missing("policy_digest", R["POLICY"], "no policy digest supplied")
    else:
        note("policy_digest", pd == sha256(canon(cert.get("policy"))), R["POLICY"],
             "recomputed %s..." % sha256(canon(cert.get("policy")))[:16])

    # --- report binding --------------------------------------------------------------
    if known_report_hashes is not None:
        rb = cert.get("report_binding")
        if rb is None:
            missing("report_binding", R["BINDING"], "no report binding supplied")
        elif rb not in known_report_hashes:
            note("report_binding", False, R["BINDING"], "binding does not match a known report")
        else:
            note("report_binding", True)

    # --- entropy provenance ----------------------------------------------------------
    ent = cert.get("entropy") or {}
    if not ent:
        missing("entropy_provenance", R["ENT_PROV"], "no entropy provenance supplied")
    else:
        if not ent.get("source_class"):
            note("entropy_provenance", False, R["ENT_PROV"], "entropy source class absent")
        elif ent.get("health_tests") != "pass":
            note("entropy_health", False, R["ENT_HEALTH"],
                 "declared health-test status %r" % ent.get("health_tests"))
        else:
            note("entropy_provenance", True, detail=ent.get("source_class"))

    # --- signature + rejection sampling ----------------------------------------------
    try:
        sig = bytes.fromhex(cert["signature"])
    except Exception:
        note("signature_decode", False, R["MALFORMED"], "signature is not hex")
        return _report(cert, checks, fails, inconclusive)

    try:
        _c, z, h = sig_decode(sig)
        note("signature_encoding", True, detail="%d bytes, c_tilde|z|h decoded" % len(sig))
    except ValueError as e:
        note("signature_encoding", False, R["MALFORMED"], str(e))
        return _report(cert, checks, fails, inconclusive)

    ok_n, worst, bound = check_norm(z)
    note("norm_bound", ok_n, R["NORM"],
         "||z||inf = %d, bound gamma1-beta = %d" % (worst, bound))

    ok_h, weight, why = check_hint(h)
    note("hint_density", ok_h, R["HINT"],
         "hint weight %d of omega %d%s" % (weight, OMEGA, ("; " + why) if why else ""))

    msg = recomputed.encode()
    # pqcrypto's verify RETURNS A BOOL - it does not raise on a bad signature. Wrapping it in
    # try/except makes a gate that can never fail: every forgery "verifies". This file had
    # exactly that bug, and the zeroed-signature vector in self_test() caught it. The except
    # clause stays only for a genuinely broken call (wrong key length, non-bytes), and the
    # VALUE is what decides. See feedback_verify_returns_bool_not_raises.
    try:
        sig_ok = bool(MLDSA.verify(issuer_pk, msg, sig))
    except Exception:
        sig_ok = False
    note("ml_dsa_verify", sig_ok, R["SIG"], "ML-DSA-44 over the recomputed identity digest")

    # S7: the report must be bound to the artifact it describes, or a valid report can be
    # presented alongside a different signature.
    srh = cert.get("report_signature_hash")
    if srh is not None:
        note("signature_report_binding", srh == sha256(sig), R["SIGREP"],
             "report cites %s..., artifact hashes to %s..." % (str(srh)[:16], sha256(sig)[:16]))

    if (not ok_n or not ok_h) and sig_ok:
        # Bill S6.1: the rejection-sampling validator evaluates each rule INDEPENDENTLY.
        #
        # DEFENCE IN DEPTH, and deliberately hard to reach. Tampering with z or h breaks the
        # signature, so an ATTACKER cannot normally land here - this fires when a signature
        # verifies yet violates a public acceptance rule, which means the SIGNER emitted
        # something it should have rejected. That is a generator bug, not a forgery, and it is
        # exactly the case an independent verifier exists to catch. The self-test reports this
        # code as unexercised rather than manufacturing a fake vector for it.
        note("rejection_sampling", False, R["REJ"],
             "public acceptance rules failed although the signature verified - "
             "this indicates a SIGNER fault, not a forgery")

    return _report(cert, checks, fails, inconclusive)


def _report(cert, checks, fails, inconclusive):
    if fails:
        overall = "fail"
    elif inconclusive:
        overall = "inconclusive"
    else:
        overall = "pass"
    sigh = sha256(bytes.fromhex(cert["signature"])) if _hexable(cert.get("signature")) else None
    return {
        "schema_version": "1.0",
        "tool": dict(TOOL, build_hash="sha256:" + sha256(canon(TOOL))[:32]),
        "parameter_set": cert.get("parameter_set"),
        "certificate": {
            "certificate_id": cert.get("certificate_id"),
            "payload_hash": sha256(canon({k: v for k, v in cert.items()
                                          if k != "signature"})),
            "subject_pk_hash": sha256(bytes.fromhex(cert["subject_pk"]))
            if _hexable(cert.get("subject_pk")) else None,
            "issuer_pk_hash": sha256(bytes.fromhex(cert["issuer_pk"]))
            if _hexable(cert.get("issuer_pk")) else None,
            "valid_from": cert.get("valid_from"),
            "valid_to": cert.get("valid_to"),
            "policy_digest": cert.get("policy_digest"),
        },
        "identity": {
            "canonical_id_hash": identity_digest(cert),
            "identity_match": identity_digest(cert) == cert.get("identity"),
        },
        "signature_verification": {
            "status": "accept" if not any(c["check"] == "ml_dsa_verify"
                                          and c["result"] == "fail" for c in checks) else "reject",
            "signature_hash": sigh,
            "reason_code": R["SIG"] if R["SIG"] in fails else None,
        },
        "rejection_sampling": {
            "checks": [c for c in checks if c["check"] in
                       ("signature_encoding", "norm_bound", "hint_density", "rejection_sampling")],
            "thresholds": {"gamma1_minus_beta": GAMMA1 - BETA, "omega": OMEGA},
        },
        "checks": checks,
        "reason_codes": sorted(set([c for c in fails if c] +
                                   [c for c in inconclusive if c])),
        "overall_result": overall,
        "safe_disclosure": {
            "secret_seeds": False, "raw_entropy": False,
            "rejected_private_candidates": False, "timing_traces": False,
            "generator_internals": False,
            "statement": "This report contains only public validation evidence.",
        },
    }


def _hexable(s):
    try:
        bytes.fromhex(s)
        return True
    except Exception:
        return False


# ---- generator (self-test fixtures only) --------------------------------------------
def make_cert(subject="device-0001", issuer="Qrypto Trust Issuing CA",
              policy=None, days=365, sk=None, pk=None):
    policy = policy or {"profile": "software-only", "usage": ["device-identity"]}
    if pk is None or sk is None:
        pk, sk = MLDSA.generate_keypair()
    spk, _ssk = MLDSA.generate_keypair()
    now = datetime.datetime.now(datetime.timezone.utc)
    cert = {
        "certificate_id": "cert-%s" % now.strftime("%Y%m%d%H%M%S"),
        "parameter_set": PARAM_SET,
        "profile": "software-only",
        "subject": subject,
        "subject_pk": spk.hex(),
        "issuer": issuer,
        "issuer_pk": pk.hex(),
        "valid_from": now.replace(microsecond=0).isoformat().replace("+00:00", "Z"),
        "valid_to": (now + datetime.timedelta(days=days)).replace(microsecond=0)
                    .isoformat().replace("+00:00", "Z"),
        "policy": policy,
        "revoked": False,
        "entropy": {"source_class": "TRNG+SHAKE256-conditioned", "health_tests": "pass"},
    }
    cert["policy_digest"] = sha256(canon(policy))
    cert["identity"] = identity_digest(cert)
    cert["signature"] = MLDSA.sign(sk, cert["identity"].encode()).hex()
    return cert, pk, sk


# ---- S6.1 self-test: a NEGATIVE test for each rejection reason ----------------------
def self_test():
    """Deterministic, boundary, malformed and negative vectors - one per reason code.

    A verifier that cannot FAIL is decoration. Every refusal path below is driven with bad
    input and must produce its SPECIFIC reason code, not merely some failure: a verifier that
    returns malformed_input for everything is as useless as one that returns pass.
    """
    import copy
    ok_cert, pk, sk = make_cert()
    anchors = {sha256(pk)}
    results = []

    def run(name, cert, expect_code=None, expect_overall="fail"):
        rep = verify_cert(cert, trusted_issuers=anchors)
        got = rep["overall_result"]
        codes = rep["reason_codes"]
        passed = (got == expect_overall) and (expect_code is None or expect_code in codes)
        results.append((name, passed, got, expect_code, codes))
        return rep

    # 1. the happy path must PASS
    run("valid certificate", copy.deepcopy(ok_cert), None, "pass")

    # 2. one negative per reason code
    c = copy.deepcopy(ok_cert); del c["subject"]
    run("missing field -> malformed_input", c, R["MALFORMED"], "inconclusive")

    c = copy.deepcopy(ok_cert); c["parameter_set"] = "ML-DSA-87"
    run("wrong parameter set", c, R["PARAM"])

    c = copy.deepcopy(ok_cert); c["profile"] = "quantum-magic"
    run("unknown profile", c, R["PROFILE"])

    c = copy.deepcopy(ok_cert); c["subject"] = "device-9999"
    run("tampered subject -> identity_mismatch", c, R["IDENTITY"])

    c = copy.deepcopy(ok_cert); c["identity"] = sha256(b"not the real identity")
    run("forged identity digest", c, R["IDENTITY"])

    c = copy.deepcopy(ok_cert)
    other_pk, _ = MLDSA.generate_keypair()
    c["issuer_pk"] = other_pk.hex(); c["identity"] = identity_digest(c)
    run("untrusted issuer key", c, R["ISSUER"])

    c = copy.deepcopy(ok_cert); c["policy_digest"] = sha256(b"stale policy")
    run("policy digest mismatch", c, R["POLICY"])

    c = copy.deepcopy(ok_cert)
    c["valid_to"] = "2020-01-01T00:00:00Z"; c["identity"] = identity_digest(c)
    c["signature"] = MLDSA.sign(sk, c["identity"].encode()).hex()
    run("expired -> stale_report_replay", c, R["REPLAY"])

    c = copy.deepcopy(ok_cert); c["revoked"] = True
    run("revoked certificate", c, R["REPLAY"])

    c = copy.deepcopy(ok_cert); c["entropy"] = {"source_class": "TRNG", "health_tests": "fail"}
    run("entropy health test failed", c, R["ENT_HEALTH"])

    c = copy.deepcopy(ok_cert); c["entropy"] = {"health_tests": "pass"}
    run("entropy provenance absent", c, R["ENT_PROV"])

    c = copy.deepcopy(ok_cert); c["signature"] = (b"\x00" * SIG_BYTES).hex()
    run("zeroed signature -> invalid_signature", c, R["SIG"])

    c = copy.deepcopy(ok_cert); c["signature"] = c["signature"][:-8]
    run("truncated signature -> malformed_input", c, R["MALFORMED"])

    # norm-bound violation: force a z coefficient past gamma1 - beta by packing 0 (-> z=gamma1)
    c = copy.deepcopy(ok_cert)
    sig = bytearray(bytes.fromhex(c["signature"]))
    sig[CTILDE_BYTES:CTILDE_BYTES + 3] = b"\x00\x00\x00"      # first coeff stored 0 -> z=gamma1
    c["signature"] = bytes(sig).hex()
    run("norm bound violated", c, R["NORM"])

    # hint-density violation: declare a cutoff above omega
    c = copy.deepcopy(ok_cert)
    sig = bytearray(bytes.fromhex(c["signature"]))
    sig[-1] = OMEGA + 5
    c["signature"] = bytes(sig).hex()
    run("hint density violated", c, R["HINT"])

    c = copy.deepcopy(ok_cert); c["report_signature_hash"] = sha256(b"a different artifact")
    run("report cites a different signature", c, R["SIGREP"])

    c = copy.deepcopy(ok_cert); c["report_binding"] = "sha256:not-a-known-report"
    rep = verify_cert(c, trusted_issuers=anchors, known_report_hashes={"sha256:known"})
    results.append(("report binding mismatch",
                    rep["overall_result"] == "fail" and R["BINDING"] in rep["reason_codes"],
                    rep["overall_result"], R["BINDING"], rep["reason_codes"]))

    # 3. inconclusive is NOT fail: no trust anchor supplied
    rep = verify_cert(copy.deepcopy(ok_cert), trusted_issuers=None)
    results.append(("no trust anchor -> inconclusive, not fail",
                    rep["overall_result"] == "inconclusive", rep["overall_result"],
                    "inconclusive", rep["reason_codes"]))

    # 4. safe disclosure must hold on every report
    rep = verify_cert(copy.deepcopy(ok_cert), trusted_issuers=anchors)
    # Scan the VALUES, not the whole blob: safe_disclosure's own key names contain the very
    # words being searched for ("rejected_private_candidates", "secret_seeds"), so a naive
    # substring test over the serialised report flags itself. A leak detector that fires on
    # its own vocabulary is noise, and noise gets switched off.
    def _values(o):
        if isinstance(o, dict):
            for v in o.values():
                yield from _values(v)
        elif isinstance(o, (list, tuple)):
            for v in o:
                yield from _values(v)
        elif isinstance(o, str):
            yield o
    blob = " ".join(_values(rep)).lower()
    leaked = any(x in blob for x in ("seed", "private key", "secret key", "sk_hex", "-----begin"))
    results.append(("safe disclosure - no secret material in report",
                    not leaked and all(v is False for k, v in rep["safe_disclosure"].items()
                                       if isinstance(v, bool)),
                    "clean" if not leaked else "LEAK", None, []))

    print("RELEASE 1 VERIFIER - self-test (negative test per rejection reason)")
    print("=" * 84)
    npass = 0
    for name, ok, got, exp, codes in results:
        npass += ok
        print("  %-4s %-46s -> %-13s %s"
              % ("PASS" if ok else "FAIL", name[:46], got,
                 ("expect " + exp) if exp and not ok else ""))
    print("=" * 84)
    covered = set()
    for _n, _o, _g, _e, codes in results:
        covered |= set(codes)
    missing_codes = [c for c in R.values() if c not in covered]
    print("  %d/%d vectors pass" % (npass, len(results)))
    print("  reason codes exercised: %d of %d" % (len(R) - len(missing_codes), len(R)))
    if missing_codes:
        print("  NOT exercised: %s" % ", ".join(missing_codes))
    return 0 if npass == len(results) else 1


def main():
    ap = argparse.ArgumentParser(prog="release1_verify")
    ap.add_argument("cmd", choices=["verify-cert", "explain-rejection", "self-test", "make-cert"])
    ap.add_argument("path", nargs="?")
    ap.add_argument("--anchors", help="file of trusted issuer public-key sha256 hashes")
    a = ap.parse_args()

    if a.cmd == "self-test":
        return self_test()

    if a.cmd == "make-cert":
        cert, pk, _sk = make_cert()
        out = a.path or "certificate.json"
        json.dump(cert, open(out, "w", encoding="utf-8"), indent=2)
        print("wrote %s (issuer pk sha256 %s)" % (out, sha256(pk)))
        return 0

    if not a.path:
        print("a certificate path is required")
        return 2
    cert = json.load(open(a.path, encoding="utf-8"))
    anchors = None
    if a.anchors and os.path.isfile(a.anchors):
        anchors = {l.strip() for l in open(a.anchors, encoding="utf-8") if l.strip()}
    rep = verify_cert(cert, trusted_issuers=anchors)

    if a.cmd == "verify-cert":
        print(json.dumps(rep, indent=2))
    else:
        print("REJECTION REPORT - %s" % rep["overall_result"].upper())
        for c in rep["checks"]:
            mark = {"pass": "ok  ", "fail": "FAIL", "inconclusive": "????"}[c["result"]]
            print("  %s %-22s %-28s %s"
                  % (mark, c["check"], c["reason_code"] or "", c["detail"][:60]))
    return 0 if rep["overall_result"] == "pass" else 1


if __name__ == "__main__":
    sys.exit(main())
