#!/usr/bin/env python3
"""Customer verifier — standard library only, no CAIN code.

Run: python3 -S -I CUSTOMER_VERIFY.py payload.json
"""
import base64
import hashlib
import json
import sys

"""Pure-Python Ed25519 verification (RFC 8032), standard library only.

No `cryptography`, no `nacl`, no site-packages. A customer can run this on any
Python 3 with nothing installed. Verification only (no signing).

Correctness is not assumed: the study differential-tests it against the reference
implementation on valid, mutated and malformed signatures.
"""
import hashlib

P = 2 ** 255 - 19
L = 2 ** 252 + 27742317777372353535851937790883648493
D = (-121665 * pow(121666, P - 2, P)) % P
I = pow(2, (P - 1) // 4, P)


def _sha512_int(b: bytes) -> int:
    return int.from_bytes(hashlib.sha512(b).digest(), "little")


def _inv(x: int) -> int:
    return pow(x, P - 2, P)


def _add(a, b):
    x1, y1, z1, t1 = a
    x2, y2, z2, t2 = b
    A = ((y1 - x1) * (y2 - x2)) % P
    B = ((y1 + x1) * (y2 + x2)) % P
    C = (2 * t1 * t2 * D) % P
    Dd = (2 * z1 * z2) % P
    E, F, G, H = B - A, Dd - C, Dd + C, B + A
    return ((E * F) % P, (G * H) % P, (F * G) % P, (E * H) % P)


def _mul(s: int, pt):
    q = (0, 1, 1, 0)
    while s > 0:
        if s & 1:
            q = _add(q, pt)
        pt = _add(pt, pt)
        s >>= 1
    return q


def _equal(a, b) -> bool:
    x1, y1, z1, _ = a
    x2, y2, z2, _ = b
    return (x1 * z2 - x2 * z1) % P == 0 and (y1 * z2 - y2 * z1) % P == 0


def _recover_x(y: int, sign: int):
    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:
        x = (x * I) % P
    if (x * x - x2) % P:
        return None
    if (x & 1) != sign:
        x = P - x
    return x


def decode_point(b: bytes):
    if len(b) != 32:
        return None
    y = int.from_bytes(b, "little")
    sign = (y >> 255) & 1
    y &= (1 << 255) - 1
    x = _recover_x(y, sign)
    if x is None:
        return None
    return (x, y, 1, (x * y) % P)


BY = (4 * _inv(5)) % P
B = (_recover_x(BY, 0), BY, 1, (_recover_x(BY, 0) * BY) % P)


def verify(public_key: bytes, message: bytes, signature: bytes) -> bool:
    if len(public_key) != 32 or len(signature) != 64:
        return False
    A = decode_point(public_key)
    if A is None:
        return False
    R = decode_point(signature[:32])
    if R is None:
        return False
    S = int.from_bytes(signature[32:], "little")
    if S >= L:
        return False
    k = _sha512_int(signature[:32] + public_key + message) % L
    return _equal(_mul(S, B), _add(R, _mul(k, A)))


# --------------------------------------------------------------------------- #
# Customer verification: ledger + acknowledgements, no CAIN code, no packages.  #
# --------------------------------------------------------------------------- #
SCHEMA = "cain42.mvc.verify.v1"


def canon(o):
    return json.dumps(o, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()


def sha(b):
    return hashlib.sha256(b if isinstance(b, (bytes, bytearray)) else str(b).encode()).hexdigest()


def merkle(items):
    level = sorted(items) if items else ["0" * 64]
    while len(level) > 1:
        if len(level) % 2:
            level.append(level[-1])
        level = [sha(level[i] + level[i + 1]) for i in range(0, len(level), 2)]
    return level[0]


def vsig(pk_hex, sig_hex, body):
    try:
        return verify(bytes.fromhex(pk_hex), body, bytes.fromhex(sig_hex))
    except (ValueError, TypeError):
        return False


def receipt_fails(rec):
    h, steps, close = rec["header"], rec["steps"], rec["close"]
    fails = []
    if not vsig(h.get("pubkey", ""), h.get("signature", ""),
                canon({k: v for k, v in h.items() if k != "signature"})):
        fails.append("HDR")
    if h.get("plan_hash") != sha(canon(h.get("plan_kinds"))):
        fails.append("PLAN_HASH")
    if len(steps) != h.get("plan_steps"):
        fails.append("COUNT")
    if [s.get("kind") for s in steps] != h.get("plan_kinds"):
        fails.append("SEQ")
    prev = h.get("start_head")
    for i, s in enumerate(steps):
        body = canon({"mission_id": s["mission_id"], "index": s["index"], "kind": s["kind"],
                      "detail": s["detail"], "prev_hash": s["prev_hash"]})
        if s.get("index") != i or s.get("prev_hash") != prev:
            fails.append("CHAIN@%d" % i)
        if sha(body) != s.get("step_hash") or not vsig(h["pubkey"], s["signature"], body):
            fails.append("STEP@%d" % i)
        prev = s.get("step_hash")
    if steps and close.get("head") != steps[-1]["step_hash"]:
        fails.append("HEAD")
    if close.get("merkle_root") != merkle([s["step_hash"] for s in steps]):
        fails.append("MERKLE")
    if not vsig(h["pubkey"], close.get("signature", ""),
                canon({k: v for k, v in close.items() if k != "signature"})):
        fails.append("CLOSE")
    return fails


def entry_hash(e):
    return sha(canon({k: v for k, v in e.items() if k != "entry_hash"}))


def verify_payload(payload):
    """payload: {"ledgers": {tenant: ledger}, "acks": [...]}"""
    checks, fails, heads = 0, [], {}
    for tenant, lg in payload["ledgers"].items():
        checks += 1
        if not vsig(lg.get("operator_pubkey", ""), lg.get("signature", ""),
                    canon({k: v for k, v in lg.items() if k != "signature"})):
            fails.append("%s:OP_SIG" % tenant)
        if len(lg["entries"]) != lg.get("declared_missions"):
            fails.append("%s:DECLARED" % tenant)
        prev = "0" * 64
        for i, e in enumerate(lg["entries"]):
            if e.get("seq") != i or e.get("prev") != prev or entry_hash(e) != e.get("entry_hash"):
                fails.append("%s:ENTRY@%d" % (tenant, i))
            f = receipt_fails(e["receipt"])
            if f:
                fails.append("%s:RECEIPT@%d" % (tenant, i))
            prev = e.get("entry_hash")
        if lg["entries"] and lg.get("head") != lg["entries"][-1]["entry_hash"]:
            fails.append("%s:HEAD" % tenant)
        if lg.get("merkle_root") != merkle([e["entry_hash"] for e in lg["entries"]]):
            fails.append("%s:MERKLE" % tenant)
        acks = [a for a in payload["acks"] if a.get("tenant") == tenant]
        by_mission = {a["mission_id"]: a for a in acks}
        if len(acks) != len(by_mission):
            fails.append("%s:ACK_DUP" % tenant)
        if lg.get("declared_missions") != len(acks):
            fails.append("%s:DECLARED_VS_ACK" % tenant)
        seen = set()
        for i, e in enumerate(lg["entries"]):
            a = e.get("ack")
            body = {k: v for k, v in (a or {}).items() if k not in ("signature", "customer_pubkey")}
            if not a or not vsig(a.get("customer_pubkey", ""), a.get("signature", ""), canon(body)) \
                    or a.get("tenant") != tenant:
                fails.append("%s:ACK_INVALID@%d" % (tenant, i))
                continue
            if a["mission_id"] != e["mission_id"] or a["seq"] != e["seq"] \
                    or a["receipt_root"] != e["receipt_root"]:
                fails.append("%s:ACK_BIND@%d" % (tenant, i))
            seen.add(a["mission_id"])
            if a["mission_id"] not in by_mission:
                fails.append("%s:ACK_NOT_CUSTOMER@%d" % (tenant, i))
        if [m for m in by_mission if m not in seen]:
            fails.append("%s:OMITTED" % tenant)
        if any(a["mission_id"] not in {e["mission_id"] for e in lg["entries"]} for a in acks):
            fails.append("%s:CUSTOMER_MISSING" % tenant)
        heads[tenant] = lg.get("head")
    return {"schema": SCHEMA, "ok": not fails, "checks": checks, "heads": heads,
            "failures": fails[:12]}


def main(argv):
    if len(argv) != 2:
        print(json.dumps({"ok": False, "error": "usage: CUSTOMER_VERIFY.py payload.json"}))
        return 2
    payload = json.loads(open(argv[1], "r", encoding="utf-8").read())
    out = verify_payload(payload)
    print(json.dumps(out))
    return 0 if out["ok"] else 1


if __name__ == "__main__":
    raise SystemExit(main(sys.argv))
