# -*- coding: utf-8 -*-
"""verify_stamp.py — B-45 P4 offline verifier for Aicent Compute Floor
receipt bundles (single file, stdlib only, no floor package needed).

Usage:
    python verify_stamp.py bundle.json [--answer answer.txt]

Fetch a bundle from a stamped receipt:
    curl -o bundle.json https://<floor>/receipt/<addr>/bundle.json

What it checks (fail-closed, one FAIL = exit 1):
  1. bundle format tag
  2. transport integrity: request_sha256 == sha256(stamp_request bytes)
  3. key self-consistency: fingerprint(pubkey) == organ_key.fingerprint
  4. signed key pin: the stamp message names the same key fingerprint
  5. envelope binding: stamp msg envelope_sha256 == sha256(envelope bytes)
  6. epoch consistency: stamp msg epoch == organ_key.epoch
  7. money facts recompute: buyer_total / supplier_share from the pinned
     prices in the signed bytes
  8. Ed25519 signature verifies over the exact canonical bytes (RFC 8032)
  9. optional --answer: sha256(answer file) == the signed output_sha256
 10. when present: signed card_aid matches the bundle supply identity

Exit 0 = VERIFIED, 1 = FAILED. The Ed25519 implementation below is the
same pure-stdlib RFC 8032 verifier the floor itself uses.
"""
import argparse
import hashlib
import json
import sys

# --- RFC 8032 Ed25519 (pure stdlib) -------------------------------------
_P = 2**255 - 19
_L = 2**252 + 27742317777372353535851937790883648493
_D = (-121665 * pow(121666, _P - 2, _P)) % _P
_I = pow(2, (_P - 1) // 4, _P)


def _recover_x(y, sign):
    if y >= _P:
        return None
    x2 = (y * y - 1) * pow(_D * y * y + 1, _P - 2, _P) % _P
    if x2 == 0:
        return None
    x = pow(x2, (_P + 3) // 8, _P)
    if (x * x - x2) % _P != 0:
        x = x * _I % _P
    if (x * x - x2) % _P != 0:
        return None
    if (x & 1) != sign:
        x = _P - x
    return x


def _point_add(p1, p2):
    x1, y1, z1 = p1
    x2, y2, z2 = p2
    a = z1 * z2 % _P
    b = a * a % _P
    c = x1 * x2 % _P
    d = y1 * y2 % _P
    e = _D * c * d % _P
    f = (b - e) % _P
    g = (b + e) % _P
    x3 = a * f * ((x1 + y1) * (x2 + y2) - c - d) % _P
    y3 = a * g * (d + c) % _P
    z3 = f * g % _P
    return (x3, y3, z3)


def _point_mul(s, p):
    q = (0, 1, 1)
    while s > 0:
        if s & 1:
            q = _point_add(q, p)
        p = _point_add(p, p)
        s >>= 1
    return q


def _point_equal(p1, p2):
    x1, y1, z1 = p1
    x2, y2, z2 = p2
    return (x1 * z2 - x2 * z1) % _P == 0 and (y1 * z2 - y2 * z1) % _P == 0


def _basepoint():
    y = (4 * pow(5, _P - 2, _P)) % _P
    return (_recover_x(y, 0), y, 1)


def _expand(b):
    y = int.from_bytes(b, "little") & ((1 << 255) - 1)
    sign = (b[31] >> 7) & 1
    x = _recover_x(y, sign)
    return None if x is None else (x, y, 1)


def ed25519_verify(public32, msg, sig64):
    if len(public32) != 32 or len(sig64) != 64:
        return False
    a = _expand(public32)
    if a is None:
        return False
    rs = sig64[:32]
    r = _expand(rs)
    if r is None:
        return False
    s = int.from_bytes(sig64[32:], "little")
    if s >= _L:
        return False
    k = int.from_bytes(hashlib.sha512(rs + public32 + msg).digest(),
                       "little") % _L
    left = _point_mul(s, _basepoint())
    right = _point_add(r, _point_mul(k, a))
    return _point_equal(left, right)


def ed25519_fingerprint(public32):
    return hashlib.sha256(public32).hexdigest()[:16]


# --- checks --------------------------------------------------------------
_RESULTS = []


def check(name, cond, detail=""):
    _RESULTS.append(bool(cond))
    print(f"  [{'PASS' if cond else 'FAIL'}] {name}"
          + (f" — {detail}" if detail and not cond else ""))


def main():
    ap = argparse.ArgumentParser(description="verify an Aicent Floor "
                                 "receipt bundle offline (stdlib only)")
    ap.add_argument("bundle", help="bundle.json from /receipt/<addr>/bundle.json")
    ap.add_argument("--answer", help="the answer text file the receipt vouches for")
    args = ap.parse_args()

    print(f"== verify {args.bundle} ==")
    with open(args.bundle, "r", encoding="utf-8") as f:
        b = json.load(f)

    check("bundle format tag", b.get("format") == "aicent-floor/receipt-bundle-v1",
          f"got {b.get('format')!r}")

    req = b["stamp_request"]
    sig = bytes.fromhex(b["stamp_signature"])
    env = bytes.fromhex(b["envelope_hex"])
    pub = bytes.fromhex(b["organ_key"]["public_key_hex"])

    check("transport integrity (request_sha256)",
          b.get("request_sha256") == hashlib.sha256(req.encode("utf-8")).hexdigest())
    check("organ key algorithm is Ed25519",
          b["organ_key"].get("algorithm") == "Ed25519")
    check("key self-consistency (fingerprint of published key)",
          ed25519_fingerprint(pub) == b["organ_key"]["fingerprint"],
          f"{ed25519_fingerprint(pub)} vs {b['organ_key']['fingerprint']}")

    msg = json.loads(req)
    check("stamp message pins the same key fingerprint",
          msg.get("fingerprint") == b["organ_key"]["fingerprint"])
    check("envelope binding (signed envelope_sha256)",
          msg.get("envelope_sha256") == hashlib.sha256(env).hexdigest())
    check("epoch consistency",
          msg.get("epoch") == b["organ_key"]["epoch"],
          f"{msg.get('epoch')!r} vs {b['organ_key']['epoch']!r}")
    if "card_aid" in msg:
        aid = msg.get("card_aid")
        check("signed card AID is well-formed",
              isinstance(aid, str) and aid.startswith("iqa://") and len(aid) >= 32,
              f"{aid!r}")
        check("signed card AID matches bundle supply identity",
              b.get("supply_identity", {}).get("aid") == aid,
              f"bundle {b.get('supply_identity', {}).get('aid')!r} vs signed {aid!r}")
    else:
        print("      legacy signing domain: no card_aid; supply identity is "
              "display-layer only")
    # B-59 dual shape: a 20-field message bills the unpacked thinking
    # alongside the answer under the out price; a legacy 18-field message
    # (frozen pending receipts) keeps the old formula — both verify.
    think = msg.get("think_tokens") or 0
    tot = round(msg["tokens_in"] * msg["price_in"] / 1e6
                + (msg["tokens_out"] + think) * msg["price_out"] / 1e6, 6)
    check("money facts recompute (buyer_total from pinned prices)",
          msg.get("buyer_total") == tot, f"{msg.get('buyer_total')} vs {tot}")
    check("supplier share recomputes",
          msg.get("supplier_share_amt")
          == round(tot * msg["supplier_share"], 6))
    # B-50: kind discriminator rides in the signed bytes. A failure receipt
    # has no answer to bind — the empty output_sha256 IS the fact (and the
    # reason is right there in the signed bytes); a run receipt must carry a
    # full sha binding.
    if msg.get("kind") == "failure":
        check("failure receipt: no answer sha in the signed bytes (nothing to bind)",
              msg.get("output_sha256") == ""
              and bool(msg.get("fail_reason")))
    else:
        check("answer sha bound in the signed bytes (B-44)",
              len(msg.get("output_sha256") or "") == 64)

    ok = ed25519_verify(pub, req.encode("utf-8"), sig)
    check("Ed25519 signature verifies over the canonical bytes", ok)
    kind = msg.get("kind") or "run"
    aid_note = (f" · card_aid {msg['card_aid']}" if msg.get("card_aid") else "")
    if kind == "failure":
        print(f"      signed facts: task {msg.get('taskid')} · FAILURE "
              f"({msg.get('fail_reason')}) · tok 0-0 (metering stopped where "
              f"the proof stopped) · buyer_total ${msg.get('buyer_total')}{aid_note}")
    else:
        think_note = (f" + {think} think" if think else "")
        print(f"      signed facts: task {msg.get('taskid')} · engine "
              f"{msg.get('engine')} · tok {msg.get('tokens_in')}-"
              f"{msg.get('tokens_out')}{think_note}"
              f" · runtime {msg.get('runtime_ms')}ms · buyer_total ${msg.get('buyer_total')}"
              f"{aid_note}")

    if args.answer:
        import io
        with io.open(args.answer, "rb") as f:
            ans = f.read()
        check("--answer sha256 matches the signed output_sha256",
              hashlib.sha256(ans).hexdigest() == msg.get("output_sha256"),
              f"{hashlib.sha256(ans).hexdigest()} vs {msg.get('output_sha256')}")

    if all(_RESULTS):
        print("VERIFIED — the organ stamp holds offline "
              f"(receipt {b['receipt_address']})")
        sys.exit(0)
    print("FAILED — do not trust this bundle")
    sys.exit(1)


if __name__ == "__main__":
    main()
