"""Check a POAW receipt offline with our published check script: Python standard library + stock OpenSSL 3.5 or later.

    python verify_receipt.py sample-receipt.json            # prints the two OpenSSL commands
    python verify_receipt.py sample-receipt.json --openssl  # and runs them (openssl must be on PATH)

poaw-receipt/2 (COSE_Sign1 per RFC 9942/9943, POAW profile):
  1. decodes the CBOR, checks typ / alg / vds / kid / iss, recomputes the RFC 9162 Merkle root over JCS(trace)
  2. writes sigstructure.bin (RFC 9052 §4.4 Sig_structure with the root as detached payload), sig.bin, token.der
  3. OpenSSL checks the ML-DSA-65 signature and the RFC 3161 token, whose imprint is
     SHA-256(CBOR-encoded signature field incl. byte-string header) per RFC 9921 §3.1.1.
poaw-receipt/1 bundles (the pre-October-2026 format) are still accepted: raw-root signature, LEDGER:LEAF tree.
"""
import base64, hashlib, json, subprocess, sys

sha = lambda b: hashlib.sha256(b).digest()
TYP, CTY, ALG, VDS = "application/poaw-run-receipt+cose", "application/poaw-trace+json", -49, 1

# ── minimal CBOR (RFC 8949): decode anything definite-length, encode what Sig_structure needs ──
def cbor_decode(b, pos=0):
    ib = b[pos]; major, ai = ib >> 5, ib & 31; pos += 1
    if ai < 24: n = ai
    elif ai == 24: n = b[pos]; pos += 1
    elif ai == 25: n = int.from_bytes(b[pos:pos + 2], "big"); pos += 2
    elif ai == 26: n = int.from_bytes(b[pos:pos + 4], "big"); pos += 4
    elif ai == 27: n = int.from_bytes(b[pos:pos + 8], "big"); pos += 8
    else: raise ValueError("indefinite length not allowed")
    if major == 0: return n, pos
    if major == 1: return -1 - n, pos
    if major == 2: return b[pos:pos + n], pos + n
    if major == 3: return b[pos:pos + n].decode("utf-8"), pos + n
    if major == 4:
        out = []
        for _ in range(n): v, pos = cbor_decode(b, pos); out.append(v)
        return out, pos
    if major == 5:
        out = {}
        for _ in range(n):
            k, pos = cbor_decode(b, pos); v, pos = cbor_decode(b, pos); out[k] = v
        return out, pos
    if major == 6:
        v, pos = cbor_decode(b, pos); return ("tag", n, v), pos
    if major == 7 and n in (20, 21): return n == 21, pos
    if major == 7 and n in (22, 23): return None, pos
    raise ValueError("unsupported CBOR item")

def head(major, n):
    if n < 24: return bytes([(major << 5) | n])
    if n < 256: return bytes([(major << 5) | 24, n])
    if n < 65536: return bytes([(major << 5) | 25]) + n.to_bytes(2, "big")
    return bytes([(major << 5) | 26]) + n.to_bytes(4, "big")
def cbor_bstr(b): return head(2, len(b)) + b
def cbor_tstr(s): e = s.encode(); return head(3, len(e)) + e

# ── RFC 9162 §2.1.1 ──
def mth(leaves):
    if len(leaves) == 0: return sha(b"")
    if len(leaves) == 1: return leaves[0]
    k = 1
    while k * 2 < len(leaves): k *= 2
    return sha(b"\x01" + mth(leaves[:k]) + mth(leaves[k:]))

def jcs(v):  # RFC 8785 for the value types used here (ASCII keys, ints, short floats, strings, bools)
    return json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()

def leaf_hash(el):
    if set(el) == {"seq", "leaf_hash"}: return bytes.fromhex(el["leaf_hash"].replace("sha256:", ""))
    return sha(b"\x00" + jcs(el))

def message_data_hex(text):
    """The imprint from `openssl ts -reply -text`: hexdump lines '0000 - 14 a1 ...-3c 08 ...   ascii' under 'Message data:'."""
    import re
    block = text.split("Message data:", 1)[1].split("Serial number:", 1)[0] if "Message data:" in text else ""
    return "".join(re.sub(r"[ -]", "", m) for m in re.findall(r"^\s*[0-9a-f]{4} - ((?:[0-9a-f]{2}[ -])*[0-9a-f]{2})", block, re.M)).lower()

def verify_v2(bundle, run):
    cose = base64.b64decode(bundle["receipt"])
    top, end = cbor_decode(cose)
    assert end == len(cose) and top[0] == "tag" and top[1] == 18, "not a tagged COSE_Sign1"
    prot_b, unprot, payload, sig = top[2]
    prot, _ = cbor_decode(prot_b)
    cwt = prot.get(15, {})
    kid = prot.get(4, b"").decode()
    hdr_ok = prot.get(16) == TYP and prot.get(1) == ALG and prot.get(395) == VDS and kid and cwt.get(1) == kid.split("#")[0] and cwt.get(2) and isinstance(cwt.get(6), int)
    print(f"   header:  typ={prot.get(16)!r} alg={prot.get(1)} vds={prot.get(395)} kid={kid} iss={cwt.get(1)} sub={cwt.get(2)} iat={cwt.get(6)}")
    print("   header: ", "OK" if hdr_ok else "MISMATCH - profile headers wrong")
    trace = bundle["trace"]
    contiguous = all(el["seq"] == i + 1 for i, el in enumerate(trace))
    root = mth([leaf_hash(el) for el in trace])
    root_ok = contiguous and (payload is None or payload == root)
    for proof_b in (unprot.get(396, {}) or {}).get(-1, []):        # RFC 9942 §4.3 inclusion proofs
        n, i, _path = cbor_decode(proof_b)[0]
        if n != len(trace) or i >= n: root_ok = False
    print("1. steps:    ", "OK - RFC 9162 root recomputed from the trace: " + root.hex() if root_ok else "MISMATCH - steps were changed after signing or proofs inconsistent")
    sigstructure = head(4, 4) + cbor_tstr("Signature1") + cbor_bstr(prot_b) + cbor_bstr(b"") + cbor_bstr(root)   # RFC 9052 §4.4
    open("sigstructure.bin", "wb").write(sigstructure); open("sig.bin", "wb").write(sig)
    token = unprot.get(270)
    if token: open("token.der", "wb").write(token)
    imprint = sha(cbor_bstr(sig)).hex()                              # RFC 9921 §3.1.1: CBOR-encoded signature incl. header
    cmd_sig = ["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", "destill-key-1.pem", "-rawin", "-in", "sigstructure.bin", "-sigfile", "sig.bin"]
    cmd_ts = ["openssl", "ts", "-reply", "-token_in", "-in", "token.der", "-text"]
    print("2. signature: ", " ".join(cmd_sig))
    print("3. timestamp: ", " ".join(cmd_ts), "   # the printed Message data must equal", imprint)
    print("   full check: openssl ts -verify -token_in -in token.der -digest", imprint, "-CAfile <your CA bundle>")
    ok = hdr_ok and root_ok
    if run:
        r = subprocess.run(cmd_sig, capture_output=True, text=True); sig_ok = "Verified Successfully" in r.stdout + r.stderr
        print("   signature:", "OK" if sig_ok else "FAIL " + (r.stdout + r.stderr).strip())
        ts_ok = False
        if token:
            r = subprocess.run(cmd_ts, capture_output=True, text=True)
            ts_ok = message_data_hex(r.stdout + r.stderr) == imprint
            print("   timestamp:", "OK - token references this signature" if ts_ok else "FAIL - token does not reference this signature")
        ok = ok and sig_ok and ts_ok
    return ok

def verify_v1(bundle, run):
    r = bundle["receipt"]
    level = [sha(("LEDGER:LEAF:" + json.dumps({k: a[k] for k in ("seq", "type", "payload", "ts")}, separators=(",", ":"), ensure_ascii=False)).encode()) for a in r["actions"]]
    while len(level) > 1: level = [sha(level[i] + level[min(i + 1, len(level) - 1)]) for i in range(0, len(level), 2)]
    ok = level[0].hex() == r["merkleRoot"]
    print("1. steps:     ", "OK - recomputed root matches the signed root" if ok else "MISMATCH - steps were changed after signing")
    sig = bytes.fromhex(r["signatureHex"])
    open("root.bin", "wb").write(bytes.fromhex(r["merkleRoot"])); open("sig.bin", "wb").write(sig)
    open("token.der", "wb").write(base64.b64decode(bundle["timestamp"]["tokenB64"]))
    print("2. signature:  openssl pkeyutl -verify -pubin -inkey destill-key-1.pem -rawin -in root.bin -sigfile sig.bin")
    print("3. timestamp:  openssl ts -verify -token_in -in token.der -digest", sha(sig).hex(), "-CAfile <your CA bundle>")
    if run:
        out = subprocess.run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", "destill-key-1.pem", "-rawin", "-in", "root.bin", "-sigfile", "sig.bin"], capture_output=True, text=True)
        s = "Verified Successfully" in out.stdout + out.stderr; print("   signature:", "OK" if s else "FAIL"); ok = ok and s
    return ok

if __name__ == "__main__":
    bundle = json.load(open(sys.argv[1], encoding="utf-8"))
    run = "--openssl" in sys.argv
    fmt = bundle.get("format")
    print("format:", fmt)
    ok = verify_v2(bundle, run) if fmt == "poaw-receipt/2" else verify_v1(bundle, run) if fmt == "poaw-receipt/1" else sys.exit("unknown format")
    sys.exit(0 if ok else 1)
