#!/usr/bin/env python3
"""ORBIT Network Chain — standalone independent verifier.

Deliberately independent of ledger.py: canonicalisation, hashing,
Merkle logic and Ed25519 verification are re-implemented here from the
public specifications (RFC 8032 for Ed25519) so a bug — or a lie — in
the writing code cannot rubber-stamp itself. Stdlib only, no network
required. (Optional: if the `ots` tool is installed, anchor proofs are
additionally checked with it; the built-in check always runs.)

Usage:
    python3 orbit-ledger-verify.py <store-dir> [--proof <seq>]

Checks, in order:
  1. Every entry's hash recomputes and every prev_hash links to the
     previous entry (single global hash chain).
  2. Every entry's Ed25519 signature verifies against the public key
     registered for its signer in a ledger.key entry, and that key
     document's SHA-256 matches the entry's artifact hash.
  3. The genesis entry's artifact hash matches the witness document in
     the store, and the witness names the legacy roots it claims.
  4. Every hourly batch's Merkle root recomputes from exactly the
     entry hashes of that hour, in sequence order.
  5. Every daily root recomputes from its batch roots, the daily chain
     (prev_daily_root) is unbroken, and each daily root's root_sig
     verifies against the registered root key.
  6. For every anchored day: daily_root.txt carries that day's root,
     and the SHA-256 of its bytes is embedded in the OpenTimestamps
     proof file (the stamped digest). Full Bitcoin attestation
     validation is delegated to `ots verify` when available and is
     reported separately — a pending attestation is NOT a failure.

A seal in this log proves an artifact existed in this form at this
time and has not changed since. It does not prove the artifact's
contents are correct.

Exit code 0 = PASS, 1 = FAIL (reason printed).
"""
import hashlib
import json
import os
import subprocess
import sys


def H(data: bytes) -> str:
    return hashlib.sha256(data).hexdigest()


def canon(obj) -> bytes:
    return json.dumps(obj, sort_keys=True, separators=(",", ":"),
                      ensure_ascii=False).encode("utf-8")


def mroot(leaves):
    if not leaves:
        return H(b"")
    lvl = [bytes.fromhex(x) for x in leaves]
    while len(lvl) > 1:
        nxt = []
        for i in range(0, len(lvl), 2):
            a = lvl[i]
            b = lvl[i + 1] if i + 1 < len(lvl) else lvl[i]
            nxt.append(hashlib.sha256(a + b).digest())
        lvl = nxt
    return lvl[0].hex()


def mproof(leaves, index):
    proof, lvl, idx = [], [bytes.fromhex(x) for x in leaves], index
    while len(lvl) > 1:
        if idx % 2 == 0:
            sib = lvl[idx + 1] if idx + 1 < len(lvl) else lvl[idx]
            proof.append(("R", sib.hex()))
        else:
            proof.append(("L", lvl[idx - 1].hex()))
        lvl = [hashlib.sha256(lvl[i] + (lvl[i + 1] if i + 1 < len(lvl)
                                        else lvl[i])).digest()
               for i in range(0, len(lvl), 2)]
        idx //= 2
    return proof


def apply_proof(leaf, proof):
    node = bytes.fromhex(leaf)
    for side, sib in proof:
        s = bytes.fromhex(sib)
        node = hashlib.sha256(s + node).digest() if side == "L" \
            else hashlib.sha256(node + s).digest()
    return node.hex()


# ------------------------------------------------- Ed25519 (RFC 8032)
_Q = 2 ** 255 - 19
_L = 2 ** 252 + 27742317777372353535851937790883648493
_D = (-121665 * pow(121666, _Q - 2, _Q)) % _Q
_I = pow(2, (_Q - 1) // 4, _Q)


def _xrecover(y):
    xx = (y * y - 1) * pow(_D * y * y + 1, _Q - 2, _Q) % _Q
    x = pow(xx, (_Q + 3) // 8, _Q)
    if (x * x - xx) % _Q != 0:
        x = (x * _I) % _Q
    if x % 2 != 0:
        x = _Q - x
    return x


_BY = (4 * pow(5, _Q - 2, _Q)) % _Q
_B = (_xrecover(_BY), _BY)


def _edwards(P, Q):
    (x1, y1), (x2, y2) = P, Q
    den = pow(1 + _D * x1 * x2 * y1 * y2, _Q - 2, _Q)
    x3 = (x1 * y2 + x2 * y1) * den % _Q
    den2 = pow(1 - _D * x1 * x2 * y1 * y2, _Q - 2, _Q)
    y3 = (y1 * y2 + x1 * x2) * den2 % _Q
    return x3, y3


def _scalarmult(P, e):
    Q = (0, 1)
    while e > 0:
        if e & 1:
            Q = _edwards(Q, P)
        P = _edwards(P, P)
        e >>= 1
    return Q


def _decode_point(data: bytes):
    if len(data) != 32:
        raise ValueError("bad point length")
    y = int.from_bytes(data, "little") & ((1 << 255) - 1)
    sign = (data[31] >> 7) & 1
    x = _xrecover(y)
    if (x & 1) != sign:
        x = _Q - x
    return x, y


def ed25519_verify(pub: bytes, msg: bytes, sig: bytes) -> bool:
    """Pure-python RFC 8032 verification. Slow, small, independent."""
    import base64  # noqa: F401  (kept stdlib-only; base64 used by caller)
    if len(pub) != 32 or len(sig) != 64:
        return False
    try:
        A = _decode_point(pub)
        R = _decode_point(sig[:32])
    except Exception:
        return False
    S = int.from_bytes(sig[32:], "little")
    if S >= _L:
        return False
    h = int.from_bytes(hashlib.sha512(sig[:32] + pub + msg).digest(),
                       "little") % _L
    # [S]B == R + [H(R,A,M)]A
    return _scalarmult(_B, S) == _edwards(R, _scalarmult(A, h))


class Fail(Exception):
    pass


def load_json(path):
    with open(path, encoding="utf-8") as fh:
        return json.load(fh)


def verify_store(root):
    import base64
    sdir = os.path.join(root, "entries")
    files = [f for f in os.listdir(sdir) if f.endswith(".jsonl")] \
        if os.path.isdir(sdir) else []
    if len(files) != 1:
        raise Fail(f"expected exactly one entry stream, found {files}")
    entries = []
    with open(os.path.join(sdir, files[0]), encoding="utf-8") as fh:
        for ln, line in enumerate(fh):
            line = line.strip()
            if not line:
                continue
            try:
                entries.append(json.loads(line))
            except json.JSONDecodeError:
                raise Fail(f"entries line {ln + 1}: invalid JSON")
    if not entries:
        raise Fail("empty chain")

    # 1. hash chain
    prev = "0" * 64
    for i, e in enumerate(entries):
        if e.get("seq") != i:
            raise Fail(f"seq {i}: out of order or missing")
        if e.get("prev_hash") != prev:
            raise Fail(f"seq {i}: prev_hash link broken")
        body = {k: v for k, v in e.items()
                if k not in ("sig", "entry_hash")}
        if H(canon(body)) != e.get("entry_hash"):
            raise Fail(f"seq {i}: entry_hash mismatch "
                       f"(entry altered after sealing)")
        prev = e["entry_hash"]

    # 2. key registry from ledger.key entries + signature checks
    registry = {}
    for e in entries:
        if e.get("type") != "ledger.key":
            continue
        kid = e["artifact"].get("key_id")
        doc_path = os.path.join(root, "keys", f"{kid}.json")
        if not os.path.exists(doc_path):
            raise Fail(f"seq {e['seq']}: key doc for {kid} missing")
        with open(doc_path, "rb") as fh:
            raw = fh.read()
        if H(raw) != e["artifact"]["sha256"]:
            raise Fail(f"seq {e['seq']}: key doc hash mismatch for {kid}")
        doc = json.loads(raw)
        if doc.get("key_id") != kid:
            raise Fail(f"seq {e['seq']}: key doc id mismatch")
        pub = base64.b64decode(doc["public_key_b64"])
        if H(pub)[:16] != kid:
            raise Fail(f"seq {e['seq']}: key_id does not derive from "
                       f"the public key for {kid}")
        registry[kid] = pub
    if not registry:
        raise Fail("no keys registered")
    for e in entries:
        pub = registry.get(e.get("signer"))
        if pub is None:
            raise Fail(f"seq {e['seq']}: unregistered signer "
                       f"{e.get('signer')}")
        sig = base64.b64decode(e["sig"])
        if not ed25519_verify(pub, e["entry_hash"].encode("ascii"), sig):
            raise Fail(f"seq {e['seq']}: signature does not verify")

    # 3. genesis witness
    g = entries[0]
    if g.get("type") != "ledger.genesis":
        raise Fail("seq 0 is not ledger.genesis")
    wpath = os.path.join(root, "genesis_witness.json")
    if not os.path.exists(wpath):
        raise Fail("genesis_witness.json missing")
    with open(wpath, "rb") as fh:
        wraw = fh.read()
    if H(wraw) != g["artifact"]["sha256"]:
        raise Fail("genesis witness hash mismatch")
    witness = json.loads(wraw)
    legacy = witness.get("legacy_witnesses", {})
    for name in ("orbit_rerun", "deepscan_chain", "ixp_baseline_2026_11_28"):
        if name not in legacy:
            raise Fail(f"genesis witness lacks {name}")

    # 4. hourly batches
    batches = {}
    bdir = os.path.join(root, "batches")
    for stream in sorted(os.listdir(bdir)) if os.path.isdir(bdir) else []:
        sd = os.path.join(bdir, stream)
        for f in sorted(os.listdir(sd)):
            if not f.endswith(".json"):
                continue
            b = load_json(os.path.join(sd, f))
            hour = f[:-5]
            if mroot(b["leaves"]) != b["root"]:
                raise Fail(f"batch {hour}: root mismatch")
            expect = [e["entry_hash"] for e in entries
                      if e["ts"][:13] == hour]
            if expect != b["leaves"]:
                raise Fail(f"batch {hour}: leaves do not match the "
                           f"sealed entries for that hour")
            batches[(hour[:10], b["root"])] = b

    # 5. daily roots + root signatures
    ddir = os.path.join(root, "daily")
    days = sorted(f[:-5] for f in os.listdir(ddir)
                  if f.endswith(".json")) if os.path.isdir(ddir) else []
    prev_daily = None
    daily_records = {}
    root_kid = witness.get("root_key", {}).get("key_id")
    for day in days:
        rec = load_json(os.path.join(ddir, day + ".json"))
        daily_records[day] = rec
        if rec["prev_daily_root"] != prev_daily:
            raise Fail(f"day {day}: daily chain broken")
        if mroot(rec["batch_roots"]) != rec["merkle_root"]:
            raise Fail(f"day {day}: merkle_root does not recompute")
        body = {k: rec[k] for k in
                ("v", "day", "merkle_root", "prev_daily_root")}
        if H(canon(body)) != rec["daily_root"]:
            raise Fail(f"day {day}: daily_root mismatch")
        for b in rec["batches"]:
            if (day, b["root"]) not in batches:
                raise Fail(f"day {day}: references missing batch "
                           f"{b['hour']}")
        if rec.get("root_signer") != root_kid:
            raise Fail(f"day {day}: unexpected root signer")
        pub = registry.get(root_kid)
        if pub is None or not ed25519_verify(
                pub, rec["daily_root"].encode("ascii"),
                base64.b64decode(rec["root_sig"])):
            raise Fail(f"day {day}: daily root signature invalid")
        prev_daily = rec["daily_root"]

    # 6. anchors: stamped-digest presence in OTS proofs
    anchor_notes = []
    adir = os.path.join(root, "anchors")
    if os.path.isdir(adir):
        for day in sorted(os.listdir(adir)):
            txt = os.path.join(adir, day, "daily_root.txt")
            ots = txt + ".ots"
            if not os.path.exists(txt):
                continue
            with open(txt, "rb") as fh:
                raw = fh.read()
            rec = daily_records.get(day)
            if rec and raw.decode().strip() != rec["daily_root"]:
                raise Fail(f"anchor {day}: daily_root.txt disagrees "
                           f"with the daily record")
            if os.path.exists(ots):
                with open(ots, "rb") as fh:
                    proof = fh.read()
                digest = hashlib.sha256(raw).digest()
                if digest in proof:
                    anchor_notes.append(
                        f"{day}: OTS proof present, stamped digest "
                        f"embedded")
                else:
                    raise Fail(f"anchor {day}: OTS proof does not "
                               f"embed the stamped digest")
                status_path = os.path.join(adir, day, "ots_status.json")
                if os.path.exists(status_path):
                    st = load_json(status_path)
                    anchor_notes.append(
                        f"{day}: ots state = {st.get('state')}")
            else:
                anchor_notes.append(f"{day}: no OTS proof yet")
    return entries, batches, daily_records, anchor_notes


def do_proof(root, entries, batches, daily_records, seq):
    if seq >= len(entries):
        raise Fail(f"no entry seq {seq}")
    e = entries[seq]
    hour = e["ts"][:13]
    day = hour[:10]
    batch = None
    for (d, _r), b in batches.items():
        if d == day and b["hour"] == hour:
            batch = b
    if batch is None:
        raise Fail(f"no batch for hour {hour} (not yet closed?)")
    idx = batch["leaves"].index(e["entry_hash"])
    p1 = mproof(batch["leaves"], idx)
    if apply_proof(e["entry_hash"], p1) != batch["root"]:
        raise Fail("entry->batch proof does not verify")
    rec = daily_records[day]
    bidx = rec["batch_roots"].index(batch["root"])
    p2 = mproof(rec["batch_roots"], bidx)
    if apply_proof(batch["root"], p2) != rec["merkle_root"]:
        raise Fail("batch->day proof does not verify")
    print(f"PROOF seq {seq} ({e['type']})")
    print(f"  entry_hash : {e['entry_hash']}")
    print(f"  batch      : {hour} root {batch['root']} "
          f"(step {idx}, {len(p1)} hashes)")
    print(f"  merkle_root: {rec['merkle_root']} "
          f"(batch step {bidx}, {len(p2)} hashes)")
    print(f"  daily_root : {rec['daily_root']} (signed by root key "
          f"{rec['root_signer']}; chains to prev "
          f"{rec['prev_daily_root']})")


def main(argv):
    if len(argv) < 2:
        print(__doc__)
        return 2
    root = argv[1]
    try:
        entries, batches, daily, notes = verify_store(root)
        if "--proof" in argv:
            i = argv.index("--proof")
            do_proof(root, entries, batches, daily, int(argv[i + 1]))
        for n in notes:
            print(f"  anchor: {n}")
        print(f"PASS: {len(entries)} entries, {len(batches)} batches, "
              f"{len(daily)} daily roots — ORBIT Network Chain intact")
        return 0
    except Fail as exc:
        print(f"FAIL: {exc}")
        return 1


if __name__ == "__main__":
    sys.exit(main(sys.argv))
