#!/usr/bin/env python3
"""Offline check of an LA4KB V3 receipt (result hash, result signature, binding signature).

Usage:  python3 verify_receipt.py receipt.json PUBLIC_KEY_HEX
Get PUBLIC_KEY_HEX from GET /api/v3/pubkey (field public_key_hex).
Requires: pip install cryptography
Message formats follow blackbox/crypto.py and blackbox/binding.py (LA4KB commit 036df36).
Note: this basic verifier trusts the receipt's payload_hash. For the build-specific
V3 check against the original request, use verify_v3_receipt.py and the published
V3 canonicalization and signed vectors.
"""
import hashlib, json, sys
from cryptography.hazmat.primitives.asymmetric import ed25519

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

r = json.load(open(sys.argv[1]))
pub = ed25519.Ed25519PublicKey.from_public_bytes(bytes.fromhex(sys.argv[2]))
job, build, verdict = r["job_id"], r["engine_build"], r.get("verdict")

result_hash = hashlib.sha256(canon({
    "client_reference": r.get("client_reference") or "",
    "engine_build": build, "job_id": job, "verdict": verdict or "NONE"})).hexdigest()
print("result_hash matches:", result_hash == r["result_hash"])

def check(sig, msg):
    try:
        pub.verify(bytes.fromhex(sig.split(":", 1)[1]), msg); return True
    except Exception:
        return False

print("result signature valid:",
      check(r["signature"], f"{build}:{job}:{r['result_hash']}".encode()))
binding = b"LA4KB-PAYLOAD-RESULT-BINDING-V1\x1f" + canon({
    "version": "la4kb-payload-result-binding-v1", "payload_hash": r["payload_hash"],
    "result_hash": r["result_hash"], "engine_build": build, "job_id": job})
print("binding signature valid:", check(r["binding_signature"], binding))
