# Gauss independent RFC 9162 (sec 2.1) implementation + C5 naive json.dumps count. Stdlib only.
import hashlib, json, sys
D = sys.argv[1] + "/data/"
H = lambda b: hashlib.sha256(b).digest()
def mth(L):
    n = len(L)
    if n == 0: return H(b"")
    if n == 1: return H(b"\x00" + L[0])
    k = 1
    while k * 2 < n: k *= 2
    return H(b"\x01" + mth(L[:k]) + mth(L[k:]))
def path(m, L):
    n = len(L)
    if n == 1: return []
    k = 1
    while k * 2 < n: k *= 2
    return path(m, L[:k]) + [mth(L[k:])] if m < k else path(m - k, L[k:]) + [mth(L[:k])]
def subproof(m, L, b):
    n = len(L)
    if m == n: return [] if b else [mth(L)]
    k = 1
    while k * 2 < n: k *= 2
    return subproof(m, L[:k], b) + [mth(L[k:])] if m <= k else subproof(m - k, L[k:], False) + [mth(L[:k])]
def verify_incl(idx, size, leaf_hash, proof, root):  # RFC 9162 2.1.3.2
    if idx >= size: return False
    fn, sn, r = idx, size - 1, leaf_hash
    for p in proof:
        if sn == 0: return False
        if fn & 1 or fn == sn:
            r = H(b"\x01" + p + r)
            if not fn & 1:
                while fn and not fn & 1: fn >>= 1; sn >>= 1
        else: r = H(b"\x01" + r + p)
        fn >>= 1; sn >>= 1
    return sn == 0 and r == root
def verify_cons(first, second, r1, r2, proof):  # RFC 9162 2.1.4.2
    if first > second: return False
    if first == second: return proof == [] and r1 == r2
    if first == 0: return False  # RFC: consistency from empty tree has no proof defined
    if not proof: return False
    p = list(proof)
    if first & (first - 1) == 0: p = [r1] + p
    fn, sn = first - 1, second - 1
    while fn & 1: fn >>= 1; sn >>= 1
    fr = sr = p[0]
    for c in p[1:]:
        if sn == 0: return False
        if fn & 1 or fn == sn:
            fr = H(b"\x01" + c + fr); sr = H(b"\x01" + c + sr)
            if not fn & 1:
                while fn and not fn & 1: fn >>= 1; sn >>= 1
        else: sr = H(b"\x01" + sr + c)
        fn >>= 1; sn >>= 1
    return fr == r1 and sr == r2 and sn == 0
lv = json.load(open(D + "log-vectors.json"))
L = [bytes.fromhex(x) for x in lv["leaves"]]
mm = 0; bad = []
if mth([]).hex() != lv["empty_root"]: mm += 1; bad.append("empty")
roots = {}
for t in lv["trees"]:
    r = mth(L[:t["size"]]); roots[t["size"]] = r
    if r.hex() != t["root"]: mm += 1; bad.append(f"root{t['size']}")
for c in lv["inclusion"]:
    gen = [x.hex() for x in path(c["index"], L[:c["size"]])]
    ok = gen == c["proof"] and verify_incl(c["index"], c["size"], H(b"\x00" + L[c["index"]]), [bytes.fromhex(x) for x in c["proof"]], roots[c["size"]])
    if not ok: mm += 1; bad.append(f"incl{c['index']}/{c['size']}")
for c in lv["consistency"]:
    gen = [x.hex() for x in subproof(c["first"], L[:c["second"]], True)] if 0 < c["first"] < c["second"] else []
    r1 = roots.get(c["first"], mth([])); ok = gen == c["proof"]
    if 0 < c["first"]: ok = ok and verify_cons(c["first"], c["second"], r1, roots[c["second"]], [bytes.fromhex(x) for x in c["proof"]])
    if not ok: mm += 1; bad.append(f"cons{c['first']}/{c['second']}")
canon = lambda v: json.dumps(v, sort_keys=True, separators=(",", ":"), ensure_ascii=False)  # only used on string-only leaf objects below
lex = 0
for ex in lv["leaf_examples"]:
    lf = {k: ("sha256:" + hashlib.sha256(json.dumps(v).encode()).hexdigest() if k in ("sig", "key_sig") else v) for k, v in ex["signed_entry"].items()}
    if lf != ex["leaf"]["entry"]: mm += 1; bad.append("leafobj")
    if ex["signed_entry"]["type"] == "key" and ex["leaf"]["operator"] != "op:" + hashlib.sha256(ex["signed_entry"]["key"].encode()).hexdigest(): mm += 1; bad.append("leafop")
    h = H(b"\x00" + canon(ex["leaf"]).encode()).hex()
    if h != ex["leaf_hash"]: mm += 1; bad.append("leafhash")
    lex += 1
ia = [c["name"] for c in lv["invalid_inclusion"] if verify_incl(c["index"], c["size"], bytes.fromhex(c["leaf_hash"]), [bytes.fromhex(x) for x in c["proof"]], bytes.fromhex(c["root"]))]
def vc(c):
    try: return verify_cons(c["first"], c["second"], bytes.fromhex(c["first_root"]), bytes.fromhex(c["second_root"]), [bytes.fromhex(x) for x in c["proof"]])
    except Exception: return False
ca = [c["name"] for c in lv["invalid_consistency"] if vc(c)]
# C5 naive
cv = json.load(open(D + "claim-id-vectors.json"))
naive = 0; total = 0; which = set()
for case in cv["cases"]:
    claims = json.loads(case["claims_json"]); by = {c["local_id"]: c for c in claims}; memo = {}
    def cid(l):
        if l in memo: return memo[l]
        c = dict(by[l]); c.pop("local_id")
        c["depends_on"] = sorted(set(cid(d) if d in by else d for d in c.get("depends_on", [])))
        if c.get("evidence"):
            c["verification_inputs"] = case["verification_inputs"]
            names = [e["result"] for e in c["evidence"] if "result" in e]
            if names: c["results"] = {n: case["results"][n] for n in names}
        memo[l] = "claim:" + hashlib.sha256(canon(c).encode()).hexdigest(); return memo[l]
    for l, exp in case["expected"].items():
        total += 1
        if cid(l) != exp: naive += 1; which.add(case["name"])
print(json.dumps({"C3": {"tree_sizes": len(lv["trees"]), "inclusion": len(lv["inclusion"]), "consistency": len(lv["consistency"]), "leaf_examples": lex,
      "mismatches": mm, "bad": bad[:10], "invalid_inclusion": len(lv["invalid_inclusion"]), "invalid_inclusion_accepted": ia,
      "invalid_consistency": len(lv["invalid_consistency"]), "invalid_consistency_accepted": ca},
      "C5": {"claims": total, "naive_mismatches": naive, "cases": sorted(which)}}, indent=1))
