#!/usr/bin/env python3
"""Verify the OMEGA Proof-of-Edge chain yourself (no trust in us needed).
Usage: python3 verify.py chain.jsonl batches/      (download both from the whitepaper site /proof/)
Checks every record's leaf hash, every batch Merkle root, and every chain link. Then, for Bitcoin timestamps:
  pip install opentimestamps-client && ots verify batches/0000001.hash.ots   (one per batch)
A batch whose .ots verifies against Bitcoin existed no later than that block -- with every decision inside it."""
import hashlib, json, sys
from pathlib import Path


def H(b): return hashlib.sha256(b).hexdigest()


def canon(o): return json.dumps(o, sort_keys=True, separators=(",", ":"))


def merkle(leaves):
    lvl = list(leaves) or [H(b"")]
    while len(lvl) > 1:
        if len(lvl) % 2:
            lvl.append(lvl[-1])
        lvl = [H((lvl[i] + lvl[i + 1]).encode()) for i in range(0, len(lvl), 2)]
    return lvl[0]


chain = [json.loads(l) for l in open(sys.argv[1])]
bdir = Path(sys.argv[2]); prev = "PROOF-OF-EDGE-GENESIS"; n = 0
for c in chain:
    b = json.loads((bdir / f"{c['seq']:07d}.json").read_text())
    leaves = [H(canon(r).encode()) for r in b["records"]]
    assert leaves == b["leaves"], f"batch {c['seq']}: a record was altered"
    assert merkle(leaves) == b["root"] == c["root"], f"batch {c['seq']}: root mismatch"
    assert b["prev"] == c["prev"] == prev, f"batch {c['seq']}: chain broken"
    assert H((prev + b["root"]).encode()) == b["batch_hash"] == c["batch_hash"], f"batch {c['seq']}: batch hash mismatch"
    prev = c["batch_hash"]; n += len(b["records"])
print(f"OK: {len(chain)} batches, {n} records, chain head {prev}")
