"""Independent check of sample-receipt.json with a SECOND CBOR implementation (cbor2) and OpenSSL 3.5 — not our code.
    pip install cbor2 ; python test_independent.py sample-receipt.json destill-key-1.pem
Proves (T3/T5 of the profile): the object is a real tagged COSE_Sign1, the ML-DSA-65 signature verifies over
RFC 9052 Sig_structure with the RFC 9162 root as detached payload, and the RFC 3161 token's imprint is
SHA-256 of the CBOR-encoded signature field (RFC 9921 §3.1.1)."""
import base64, hashlib, json, subprocess, sys, tempfile, os
import cbor2

bundle = json.load(open(sys.argv[1], encoding="utf-8")); pem = sys.argv[2]
assert bundle["format"] == "poaw-receipt/2"
cose = base64.b64decode(bundle["receipt"])
obj = cbor2.loads(cose)
assert isinstance(obj, cbor2.CBORTag) and obj.tag == 18, "not #6.18"
prot_b, unprot, payload, sig = obj.value
prot = cbor2.loads(prot_b)
assert prot[16] == "application/poaw-run-receipt+cose" and prot[1] == -49 and prot[395] == 1
sha = lambda b: hashlib.sha256(b).digest()

def mth(leaves):  # RFC 9162 §2.1.1, written independently of poaw-cose.mjs
    if not leaves: 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:]))
leaves = [sha(b"\x00" + json.dumps(e, sort_keys=True, separators=(",", ":"), ensure_ascii=False).encode()) for e in bundle["trace"]]
root = mth(leaves)
assert root.hex() == bundle["root"], "root in bundle metadata differs from recomputation"
sigstructure = cbor2.dumps(["Signature1", prot_b, b"", root], canonical=True)
d = tempfile.mkdtemp()
open(os.path.join(d, "ss.bin"), "wb").write(sigstructure); open(os.path.join(d, "sig.bin"), "wb").write(sig)
r = subprocess.run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", pem, "-rawin", "-in", os.path.join(d, "ss.bin"), "-sigfile", os.path.join(d, "sig.bin")], capture_output=True, text=True)
sig_ok = "Verified Successfully" in r.stdout + r.stderr
# negative control: the same signature over the raw root must NOT verify (that was poaw-receipt/1 behaviour)
open(os.path.join(d, "root.bin"), "wb").write(root)
r2 = subprocess.run(["openssl", "pkeyutl", "-verify", "-pubin", "-inkey", pem, "-rawin", "-in", os.path.join(d, "root.bin"), "-sigfile", os.path.join(d, "sig.bin")], capture_output=True, text=True)
raw_ok = "Verified Successfully" in r2.stdout + r2.stderr
token = unprot[270]
open(os.path.join(d, "token.der"), "wb").write(token)
imprint = sha(cbor2.dumps(sig)).hex()   # cbor2 encodes the bstr with its header, as RFC 9921 §3.1.1 requires
r3 = subprocess.run(["openssl", "ts", "-reply", "-token_in", "-in", os.path.join(d, "token.der"), "-text"], capture_output=True, text=True)
import re
block = (r3.stdout + r3.stderr).split("Message data:", 1)[1].split("Serial number:", 1)[0]
stamped = "".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()
ts_ok = stamped == imprint
wrong = stamped == sha(sig).hex()   # the /1 imprint (raw signature bytes) must NOT be what the TSA stamped
print("COSE_Sign1 tag 18:        OK")
print("profile headers:          OK")
print("RFC 9162 root:            OK", root.hex()[:16] + "…")
print("ML-DSA-65 over Sig_structure (OpenSSL):", "OK" if sig_ok else "FAIL")
print("negative: raw-root signature verifies?  ", "no (good)" if not raw_ok else "YES (BAD)")
print("RFC 3161 imprint = SHA-256(CBOR sig):   ", "OK" if ts_ok else "FAIL")
print("negative: imprint = SHA-256(raw sig)?   ", "no (good)" if not wrong else "YES (BAD)")
sys.exit(0 if (sig_ok and ts_ok and not raw_ok and not wrong) else 1)
