#!/usr/bin/env python3
"""Verify a PROOFLOOP record with the Python STANDARD LIBRARY ONLY. No `cryptography`, no pip, no Rust, no build.

Works on Termux/Android, minimal containers, anywhere Python 3 runs:

    curl -fsSLO https://cainstudio.online/verify_proofloop_pure.py
    curl -fsSLO https://cainstudio.online/evidence/proofloop-fresh-eval/record.json
    python3 verify_proofloop_pure.py record.json

It implements Ed25519 signature verification (RFC 8032) in pure Python, then checks: the pinned key's fingerprint,
the signature over the exact signed bytes, and that record_sha256 matches. Exit 0 only when all pass.
"""
from __future__ import annotations
import argparse, base64, hashlib, json, sys

PUBLIC_KEY_B64 = "b6hfA2rpAdV29FOdhNXGkk4t91mCV0AnfFYwq0HO0R8="
FINGERPRINT = "SHA256:2232b4add9b35d4016e5be270df4ed56e0dc9b39a0530ac69891073253aae90d"

# ---- Ed25519 (RFC 8032 reference implementation, public domain) in pure Python --------------------------------
_p = 2**255 - 19
_q = 2**252 + 27742317777372353535851937790883648493
def _inv(x): return pow(x, _p - 2, _p)
_d = (-121665 * _inv(121666)) % _p
_sqrtm1 = pow(2, (_p - 1) // 4, _p)
def _sha512_modq(s): return int.from_bytes(hashlib.sha512(s).digest(), "little") % _q
def _pt_add(P, Q):
    A = (P[1]-P[0]) * (Q[1]-Q[0]) % _p
    B = (P[1]+P[0]) * (Q[1]+Q[0]) % _p
    C = 2 * P[3] * Q[3] * _d % _p
    D = 2 * P[2] * Q[2] % _p
    E, F, G, H = B-A, D-C, D+C, B+A
    return (E*F % _p, G*H % _p, F*G % _p, E*H % _p)
def _pt_mul(s, P):
    Q = (0, 1, 1, 0)
    while s > 0:
        if s & 1: Q = _pt_add(Q, P)
        P = _pt_add(P, P); s >>= 1
    return Q
def _pt_eq(P, Q):
    if (P[0]*Q[2] - Q[0]*P[2]) % _p != 0: return False
    if (P[1]*Q[2] - Q[1]*P[2]) % _p != 0: return False
    return True
def _recover_x(y, sign):
    if y >= _p: return None
    x2 = (y*y - 1) * _inv(_d*y*y + 1) % _p
    if x2 == 0:
        return None if sign else 0
    x = pow(x2, (_p + 3) // 8, _p)
    if (x*x - x2) % _p != 0: x = x * _sqrtm1 % _p
    if (x*x - x2) % _p != 0: return None
    if (x & 1) != sign: x = _p - x
    return x
_gy = 4 * _inv(5) % _p
_gx = _recover_x(_gy, 0)
_G = (_gx, _gy, 1, _gx * _gy % _p)
def _decompress(b):
    if len(b) != 32: return None
    y = int.from_bytes(b, "little"); sign = y >> 255; y &= (1 << 255) - 1
    x = _recover_x(y, sign)
    return None if x is None else (x, y, 1, x * y % _p)
def ed25519_verify(pub: bytes, sig: bytes, msg: bytes) -> bool:
    if len(sig) != 64 or len(pub) != 32: return False
    A = _decompress(pub)
    if A is None: return False
    R = _decompress(sig[:32])
    if R is None: return False
    s = int.from_bytes(sig[32:], "little")
    if s >= _q: return False
    h = _sha512_modq(sig[:32] + pub + msg)
    return _pt_eq(_pt_mul(s, _G), _pt_add(R, _pt_mul(h, A)))

def main(argv=None) -> int:
    ap = argparse.ArgumentParser(description=__doc__.splitlines()[0])
    ap.add_argument("record"); ap.add_argument("--public-key", default=PUBLIC_KEY_B64)
    ap.add_argument("--fingerprint", default=FINGERPRINT); ap.add_argument("--json", action="store_true")
    a = ap.parse_args(argv)
    checks = []
    def add(n, ok, d=""): checks.append({"check": n, "ok": bool(ok), "detail": d}); return ok
    rec = json.load(open(a.record))
    raw = base64.b64decode(a.public_key)
    fp = "SHA256:" + hashlib.sha256(raw).hexdigest()
    add("KEY", fp.lower() == a.fingerprint.strip().lower(), fp)
    sig = rec.get("signature", {})
    body = {k: rec[k] for k in rec if k not in ("record_sha256", "signature", "signed_payload_b64")}
    payload = json.dumps(body, sort_keys=True, separators=(",", ":")).encode()
    add("SIG", ed25519_verify(raw, base64.b64decode(sig.get("sig_b64", "")), payload), sig.get("key_fingerprint", ""))
    add("HASH", rec.get("record_sha256") == hashlib.sha256(payload).hexdigest(), (rec.get("record_sha256") or "")[:16])
    ok = all(c["ok"] for c in checks)
    if a.json:
        print(json.dumps({"ok": ok, "checks": checks, "summary": rec.get("summary")}, indent=2))
    else:
        for c in checks: print(f"  {'PASS' if c['ok'] else 'FAIL'}  {c['check']:5s} {c['detail']}")
        print("VERIFIED (pure-Python, no dependencies)" if ok else "NOT VERIFIED")
    return 0 if ok else 1

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