#!/usr/bin/env python3
"""botsrated_verify.py: check one BotsRated day against its public anchor, offline.

Python 3.8+ standard library only. Nothing is installed and nothing is sent anywhere except
the GET requests that `fetch` makes to botsrated.com and github.com.

  python3 botsrated_verify.py fetch 2026-11-23 -o day-2026-11-23     # download a day (online, once)
  python3 botsrated_verify.py check day-2026-11-23                   # verify it (offline)
  python3 botsrated_verify.py prove day-2026-11-23 <record id>       # Merkle inclusion path for one record
  python3 botsrated_verify.py record my-receipt.json day-2026-11-23  # is a record you hold in that day?
  python3 botsrated_verify.py late 2026-11-25 -o late-2026-11-25     # check a late-cover batch (online fetch, then offline check)

What `check` proves, step by step:
  1. head.json is exactly {v, day, leaf_count, merkle_root, prev_anchor} of the day document, and
     sha256(head.json) equals the day's anchor.
  2. The RFC 6962 Merkle root recomputed from the published leaf hashes equals merkle_root, the
     leaves are in (s, id, h) order, and leaf_count matches.
  3. prev_anchor equals the previous day's anchor (the chain), when the previous day doc was fetched.
  4. The botsrated.com copy and the github.com/botsrated/anchors copy of the day doc agree.
  5. The OpenTimestamps proof commits to sha256(head.json), and lists the Bitcoin block heights
     it claims. To check those blocks against Bitcoin itself, run `ots verify` (see /verify-day).
  6. Each archive manifest (x402, MCP) hashes to its leaf and carries a valid ed25519 signature
     from a key published at /.well-known/botsrated-key.
  7. Each fetched record (paid test-buy receipts, BotsRated self-status receipts) hashes to its
     leaf, and its ed25519 signature verifies with a key valid at its signing time.

What it does not prove: that a measurement was right, or anything about records we do not
publish (raw probe parts carry payee addresses and stay private; their sha256 values are in the
signed manifest). An anchor shows a record existed no later than the anchor's Bitcoin timestamp.
"""
import argparse, base64, datetime as dt, hashlib, json, os, sys, urllib.request

SITE = os.environ.get("BOTSRATED_SITE", "https://botsrated.com")
GH = "https://raw.githubusercontent.com/botsrated/anchors/main"
UA = {"user-agent": "botsrated-verify/1 (+https://botsrated.com/verify-day)", "accept": "application/json"}
VERSION = "botsrated-verify-1"

# ---------- canonical JSON (same rule as the anchor worker: keys sorted, no whitespace) ----------
def _num(v):
    if isinstance(v, bool): return "true" if v else "false"
    if isinstance(v, int): return str(v)
    if v != v or v in (float("inf"), float("-inf")): raise ValueError("non-finite number")
    if v == int(v) and abs(v) < 1e21: return str(int(v))
    r = repr(v)                      # shortest round-trip repr, like JavaScript
    if "e" in r:
        m, e = r.split("e"); e = int(e)
        if -7 < e < 21:
            from decimal import Decimal
            t = format(Decimal(r), "f")
            return t.rstrip("0").rstrip(".") if "." in t else t
        return m + "e" + ("+" if e > 0 else "-") + str(abs(e))
    return r

def canon(v):
    if v is None: return "null"
    if isinstance(v, (bool, int, float)): return _num(v)
    if isinstance(v, str): return json.dumps(v, ensure_ascii=False)
    if isinstance(v, list): return "[" + ",".join(canon(x) for x in v) + "]"
    if isinstance(v, dict):
        return "{" + ",".join(json.dumps(k, ensure_ascii=False) + ":" + canon(v[k]) for k in sorted(v)) + "}"
    raise TypeError(type(v))

def sha(b): return hashlib.sha256(b if isinstance(b, bytes) else b.encode()).hexdigest()

# ---------- RFC 6962 Merkle tree ----------
def _H(b): return hashlib.sha256(b).digest()
def mth(leaves):
    if not leaves: return _H(b"")
    if len(leaves) == 1: return _H(b"\x00" + leaves[0])
    k = 1
    while k * 2 < len(leaves): k *= 2
    return _H(b"\x01" + mth(leaves[:k]) + mth(leaves[k:]))

def audit_path(leaves, m):
    """RFC 6962 section 2.1.1 PATH(m, D[n])."""
    n = len(leaves)
    if n <= 1: return []
    k = 1
    while k * 2 < n: k *= 2
    if m < k: return audit_path(leaves[:k], m) + [("R", mth(leaves[k:]))]
    return audit_path(leaves[k:], m - k) + [("L", mth(leaves[:k]))]

def root_from_path(leaf, path):
    h = _H(b"\x00" + leaf)
    for side, sib in path:
        h = _H(b"\x01" + sib + h) if side == "L" else _H(b"\x01" + h + sib)
    return h

# ---------- Ed25519 verify (RFC 8032, pure Python; slow but dependency-free) ----------
_p = 2**255 - 19
_L = 2**252 + 27742317777372353535851937790883648493
_d = -121665 * pow(121666, _p - 2, _p) % _p
_I = pow(2, (_p - 1) // 4, _p)
def _xr(y, sign):
    xx = (y * y - 1) * pow(_d * y * y + 1, _p - 2, _p)
    x = pow(xx, (_p + 3) // 8, _p)
    if (x * x - xx) % _p: x = x * _I % _p
    if (x * x - xx) % _p: return None
    if x & 1 != sign: x = _p - x
    return x
_By = 4 * pow(5, _p - 2, _p) % _p
_B = (_xr(_By, 0), _By, 1, _xr(_By, 0) * _By % _p)
def _add(P, Q):
    A = (P[1] - P[0]) * (Q[1] - Q[0]) % _p; B = (P[1] + P[0]) * (Q[1] + Q[0]) % _p
    C = 2 * P[3] * Q[3] * _d % _p; D = 2 * P[2] * Q[2] % _p
    E, F, G, H = B - A, D - C, D + C, B + A
    return (E * F % _p, G * H % _p, F * G % _p, E * H % _p)
def _mul(s, P):
    Q = (0, 1, 1, 0)
    while s:
        if s & 1: Q = _add(Q, P)
        P = _add(P, P); s >>= 1
    return Q
def _eq(P, Q): return (P[0] * Q[2] - Q[0] * P[2]) % _p == 0 and (P[1] * Q[2] - Q[1] * P[2]) % _p == 0
def _dec(b):
    if len(b) != 32: return None
    y = int.from_bytes(b, "little"); sign = y >> 255; y &= (1 << 255) - 1
    if y >= _p: return None
    x = _xr(y, sign)
    return None if x is None else (x, y, 1, x * y % _p)
def ed25519_verify(pub, msg, sig):
    try:
        if len(sig) != 64: return False
        A = _dec(pub); R = _dec(sig[:32])
        if A is None or R is None: 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
        return _eq(_mul(s, _B), _add(R, _mul(h, A)))
    except Exception:
        return False

# ---------- helpers ----------
def get(url, raw=False, tries=4):
    import time, urllib.error
    for n in range(tries):
        try:
            req = urllib.request.Request(url, headers=UA)
            with urllib.request.urlopen(req, timeout=60) as r:
                b = r.read()
            time.sleep(0.15)          # be gentle with a public site
            return b if raw else json.loads(b)
        except urllib.error.HTTPError as e:
            if e.code not in (429, 500, 502, 503, 504) or n == tries - 1: raise
            time.sleep(2 * (n + 1) ** 2)

def ts_parse(s):
    return dt.datetime.fromisoformat(s.replace("Z", "+00:00")) if s else None

def key_ok(keys, kid, when):
    k = keys.get(kid)
    if not k: return False, "key %s not published" % kid
    t = ts_parse(when)
    lo, hi = ts_parse(k.get("valid_from")), ts_parse(k.get("valid_until"))
    if t and lo and t < lo: return False, "%s signed at %s, before key valid_from %s" % (kid, when, k.get("valid_from"))
    if t and hi and t >= hi: return False, "%s signed at %s, after key valid_until %s" % (kid, when, k.get("valid_until"))
    return True, "%s valid at %s" % (kid, when)

def strip_served(rec):
    """Undo the API presentation hints the site adds when serving a stored record."""
    r = dict(rec)
    for k in ("receipt_url", "signature"): r.pop(k, None)
    if not isinstance(r.get("payment"), dict) and r.get("kind") not in ("mcp_probe", "mpp_probe", "mpp_catalog"):
        r.pop("payment", None)
    return r

def signing_time(r):
    if r.get("signed_late") and r.get("signed_late_at"): return r["signed_late_at"]
    return r.get("signed_at") or r.get("ts") or r.get("generated_at")

def verify_record_sig(r, keys):
    sig = r.get("sig")
    if not isinstance(sig, dict) or not sig.get("sig_b64"): return None, "no per-record signature object"
    k = keys.get(sig.get("key_id"))
    if not k: return False, "unknown key %s" % sig.get("key_id")
    pub = base64.b64decode(k["public_key_b64"]); s = base64.b64decode(sig["sig_b64"])
    body = {x: y for x, y in r.items() if x != "sig"}
    tries = [body, {x: y for x, y in body.items() if x != "tx_url"}]
    if not any(ed25519_verify(pub, canon(t).encode(), s) for t in tries):
        return False, "ed25519 signature does not verify (key %s)" % sig["key_id"]
    ok, why = key_ok(keys, sig["key_id"], signing_time(r))
    return ok, "ed25519 OK, " + why

def verify_manifest_sig(m, keys):
    sig = m.get("sig")
    if isinstance(sig, dict):
        kid, s = sig.get("key_id"), sig.get("sig_b64")
        body = {x: y for x, y in m.items() if x != "sig"}
    else:
        kid, s = m.get("key_id"), sig
        body = {x: y for x, y in m.items() if x != "sig"}
    if not (kid and s): return None, "manifest carries no signature"
    k = keys.get(kid)
    if not k: return False, "unknown key %s" % kid
    pub = base64.b64decode(k["public_key_b64"]); sb = base64.b64decode(s)
    tries = [body, {x: y for x, y in body.items() if x != "key_id"}]
    if not any(ed25519_verify(pub, canon(t).encode(), sb) for t in tries):
        return False, "ed25519 manifest signature does not verify (key %s)" % kid
    return True, "ed25519 OK (key %s)" % kid

# ---------- OpenTimestamps: minimal reader ----------
OTS_MAGIC = b"\x00OpenTimestamps\x00\x00Proof\x00\xbf\x89\xe2\xe8\x84\xe8\x92\x94"
TAG_BTC = bytes.fromhex("0588960d73d71901"); TAG_PENDING = bytes.fromhex("83dfe30d2ef90c8e")
def _varuint(b, i):
    v = 0; sh = 0
    while True:
        c = b[i]; i += 1; v |= (c & 0x7f) << sh; sh += 7
        if not c & 0x80: return v, i
def ots_read(b):
    if not b.startswith(OTS_MAGIC): return None, "not an OpenTimestamps proof file"
    i = len(OTS_MAGIC); _ver, i = _varuint(b, i)
    op = b[i]; i += 1
    if op != 0x08: return None, "proof is not over a sha256 file digest"
    digest = b[i:i + 32].hex()
    heights, pending, j = [], 0, i + 32
    while True:
        j = b.find(TAG_BTC, j)
        if j < 0: break
        try:
            ln, k = _varuint(b, j + 8); h, _ = _varuint(b, k); heights.append(h)
        except Exception: pass
        j += 8
    pending = b.count(TAG_PENDING)
    return {"digest": digest, "bitcoin_heights": sorted(set(heights)), "pending": pending}, None

# ---------- fetch ----------
def fetch(day, out, records, limit):
    os.makedirs(out, exist_ok=True)
    w = lambda name, data: open(os.path.join(out, name), "wb").write(data if isinstance(data, bytes) else json.dumps(data, indent=1, ensure_ascii=False).encode())
    print("fetching", day, "into", out)
    doc = get(f"{SITE}/v1/anchor/{day}"); w("day.json", doc)
    w("leaves.json", get(f"{SITE}/v1/anchor/{day}/leaves"))
    w("head.json", get(f"{SITE}/v1/anchor/{day}/head.json", raw=True))
    try: w("anchor.ots", get(f"{GH}/proofs/{day}.head.json.ots", raw=True)); print("  OTS proof from github (upgraded copy)")
    except Exception:
        try: w("anchor.ots", get(f"{SITE}/v1/anchor/{day}/anchor.ots", raw=True)); print("  OTS proof from botsrated.com")
        except Exception as e: print("  no OTS proof:", e)
    try: w("day.github.json", get(f"{GH}/days/{day}.json"))
    except Exception as e: print("  github copy not available yet:", e)
    if doc.get("prev_day"):
        w("prev_day.json", get(f"{SITE}/v1/anchor/{doc['prev_day']}"))
    elif doc.get("prev_anchor"):
        g = get(f"{SITE}/v1/anchor/genesis"); g.pop("chunk_roots", None); w("prev_day.json", g)
    w("keys.json", get(f"{SITE}/.well-known/botsrated-key"))
    os.makedirs(os.path.join(out, "records"), exist_ok=True)
    lv = json.load(open(os.path.join(out, "leaves.json")))["leaves"]
    for l in lv:
        if l["s"] in ("x402_manifest", "mcp_manifest"):
            w(os.path.join("records", l["s"] + ".json"), get(f"{SITE}/archive/{l['id']}"))
        if l["s"] == "late_cover":
            w(os.path.join("records", "late_cover.bytes"), get(f"{SITE}/archive/{l['id']}", raw=True))
    if records == "none": return
    want = {"receipt": "{}/receipt/{}?format=json", "self_status": "{}/status/receipt/{}"}
    for s, tpl in want.items():
        ids = [l["id"] for l in lv if l["s"] == s and l["id"]]
        if records == "sample": ids = ids[:limit]
        for n, i in enumerate(ids, 1):
            try:
                d = get(tpl.format(SITE, i))
                w(os.path.join("records", f"{s}.{i}.json"), d.get("receipt", d))
            except Exception as e:
                print(f"  {s} {i}: fetch failed ({e})")
        print(f"  {s}: fetched {len(ids)} of {sum(1 for l in lv if l['s'] == s)}")

# ---------- check ----------
class R:
    def __init__(s): s.fail = 0; s.warn = 0
    def ok(s, m): print("PASS ", m)
    def bad(s, m): s.fail += 1; print("FAIL ", m)
    def note(s, m): s.warn += 1; print("WARN ", m)
    def info(s, m): print("INFO ", m)

def check(d):
    r = R(); L = lambda n: json.load(open(os.path.join(d, n)))
    doc, lv = L("day.json"), L("leaves.json")
    day = doc["day"]; leaves = lv["leaves"]
    r.info(f"{VERSION}: day {day}, status {doc.get('status')}, {len(leaves)} leaves")
    if doc.get("status") != "final": r.note("this day is not final yet: its root can still change")
    head = {k: doc[k] for k in ("v", "day", "leaf_count", "merkle_root", "prev_anchor")}
    hb = open(os.path.join(d, "head.json"), "rb").read()
    (r.ok if json.loads(hb) == head else r.bad)("head.json matches the day document's {v, day, leaf_count, merkle_root, prev_anchor}")
    (r.ok if sha(hb) == doc["anchor"] else r.bad)(f"sha256(head.json) = anchor {doc['anchor'][:16]}...")
    (r.ok if sha(canon(head)) == doc["anchor"] else r.bad)("anchor = sha256(canonical head)")
    order = sorted(leaves, key=lambda l: (l["s"], l["id"] or "", l["h"]))
    (r.ok if order == leaves else r.bad)("leaves are in (s, id, h) order")
    (r.ok if len(leaves) == doc["leaf_count"] else r.bad)(f"leaf_count {doc['leaf_count']}")
    root = mth([bytes.fromhex(l["h"]) for l in leaves]).hex()
    (r.ok if root == doc["merkle_root"] else r.bad)(f"recomputed RFC 6962 root {root[:16]}... = merkle_root")
    if os.path.exists(os.path.join(d, "prev_day.json")):
        p = L("prev_day.json")
        (r.ok if p.get("anchor") == doc["prev_anchor"] else r.bad)(f"chain: prev_anchor = anchor of {p.get('day')}")
    else: r.note("previous day not fetched; chain not checked")
    if os.path.exists(os.path.join(d, "day.github.json")):
        g = L("day.github.json")
        same = all(g.get(k) == doc.get(k) for k in ("merkle_root", "anchor", "prev_anchor", "leaf_count"))
        (r.ok if same else r.bad)("github.com/botsrated/anchors copy agrees (root, anchor, prev_anchor, leaf_count)")
    else: r.note("no github copy of this day (it is mirrored after the day is final)")
    op = os.path.join(d, "anchor.ots")
    if os.path.exists(op):
        o, err = ots_read(open(op, "rb").read())
        if err: r.bad("OpenTimestamps: " + err)
        else:
            (r.ok if o["digest"] == sha(hb) else r.bad)("OpenTimestamps proof commits to sha256(head.json)")
            if o["bitcoin_heights"]: r.ok(f"OpenTimestamps proof claims Bitcoin block(s) {o['bitcoin_heights']} (confirm with: ots verify anchor.ots -f head.json)")
            else: r.note("OpenTimestamps proof is still pending Bitcoin confirmation")
    else: r.note("no OpenTimestamps proof file")
    keys = {k["key_id"]: k for k in L("keys.json").get("keys", [])}
    by = {}
    for l in leaves: by.setdefault((l["s"], l["id"]), set()).add(l["h"])
    rd = os.path.join(d, "records"); counts = {}
    for f in sorted(os.listdir(rd)) if os.path.isdir(rd) else []:
        if f == "late_cover.bytes":
            lid = [l for l in leaves if l["s"] == "late_cover"][0]
            (r.ok if sha(open(os.path.join(rd, f), "rb").read()) == lid["h"] else r.bad)(f"late_cover {lid['id']} bytes hash to their leaf (check the batch itself with: late <day>)")
            continue
        rec = json.load(open(os.path.join(rd, f)))
        if f in ("x402_manifest.json", "mcp_manifest.json"):
            s = f[:-5]; lid = [l for l in leaves if l["s"] == s][0]
            (r.ok if sha(canon(rec)) == lid["h"] else r.bad)(f"{s} {lid['id']} hashes to its leaf")
            ok, why = verify_manifest_sig(rec, keys)
            (r.ok if ok else (r.note if ok is None else r.bad))(f"{s} signature: {why}")
            parts = rec.get("parts") or []
            r.info(f"{s}: {rec.get('receipts')} receipts in {len(parts)} parts, each part's sha256 listed (raw parts are private)")
            continue
        s, rid = f.split(".")[0], f.split(".")[1]
        body = strip_served(rec)
        hit = sha(canon(body)) in by.get((s, rid), set())
        if not hit:
            b2 = dict(body); b2.pop("tx_url", None)
            hit = sha(canon(b2)) in by.get((s, rid), set())
        c = counts.setdefault(s, [0, 0, 0])
        if hit: c[0] += 1
        else: r.bad(f"{s} {rid}: record does not hash to a leaf of this day")
        ok, why = verify_record_sig(body, keys)
        if ok: c[1] += 1
        elif ok is None: c[2] += 1
        else: r.bad(f"{s} {rid}: {why}")
    for s, (h, sg, ns) in counts.items():
        total = sum(1 for l in leaves if l["s"] == s)
        r.ok(f"{s}: {h} fetched records hash to their leaves; {sg} signatures verify ({total} leaves of this kind in the day)")
        if ns: r.note(f"{s}: {ns} records carry no per-record signature object")
    print(f"\nRESULT {day}: {'OK' if not r.fail else 'FAILED'} ({r.fail} failures, {r.warn} warnings)")
    return r.fail == 0

def prove(d, rid):
    lv = json.load(open(os.path.join(d, "leaves.json")))["leaves"]; doc = json.load(open(os.path.join(d, "day.json")))
    idx = [i for i, l in enumerate(lv) if l["id"] == rid]
    if not idx: print("id not in this day's leaves"); return False
    hs = [bytes.fromhex(l["h"]) for l in lv]; m = idx[0]; path = audit_path(hs, m)
    ok = root_from_path(hs[m], path).hex() == doc["merkle_root"]
    print(json.dumps({"day": doc["day"], "leaf": lv[m], "index": m, "tree_size": len(hs),
                      "path": [{"side": s, "hash": h.hex()} for s, h in path], "merkle_root": doc["merkle_root"],
                      "anchor": doc["anchor"], "path_checks": ok}, indent=1))
    return ok

def record(fn, d):
    rec = json.load(open(fn)); rec = rec.get("receipt", rec) if isinstance(rec, dict) else rec
    body = strip_served(rec)
    lv = json.load(open(os.path.join(d, "leaves.json")))["leaves"]
    hs = {l["h"]: l for l in lv}
    for b in (body, {k: v for k, v in body.items() if k != "tx_url"}):
        h = sha(canon(b))
        if h in hs: print("PASS record hash", h, "is leaf", hs[h]); return prove(d, hs[h]["id"]) if hs[h]["id"] else True
    print("FAIL record hash not found in this day's leaves (wrong day, or the record was changed)"); return False

def late(batch, out):
    import gzip
    os.makedirs(out, exist_ok=True); r = R()
    base = f"{SITE}/archive/late-cover/{batch}/"
    ib = get(base + "index.json", raw=True); open(os.path.join(out, "index.json"), "wb").write(ib)
    idx = json.loads(ib)
    r.info(f"late cover {batch}: created_at {idx.get('created_at')}, {len(idx['items'])} items. {idx.get('honesty', '')}")
    try:
        ob = get(base + "index.json.ots", raw=True); open(os.path.join(out, "index.json.ots"), "wb").write(ob)
        o, err = ots_read(ob)
        if err: r.bad("OpenTimestamps: " + err)
        else:
            (r.ok if o["digest"] == sha(ib) else r.bad)("OpenTimestamps proof commits to sha256(index.json)")
            if o["bitcoin_heights"]: r.ok(f"OpenTimestamps proof claims Bitcoin block(s) {o['bitcoin_heights']} (confirm with: ots verify index.json.ots -f index.json)")
            else: r.note("OpenTimestamps proof is pending Bitcoin confirmation (run ots upgrade later)")
    except Exception as e: r.bad(f"no OpenTimestamps proof ({e})")
    roots = []
    for it in idx["items"]:
        gz = get(it["file"], raw=True); t = gzip.decompress(gz)
        open(os.path.join(out, os.path.basename(it["file"])), "wb").write(gz)
        d = json.loads(t); hs = [bytes.fromhex(l["h"]) for l in d["leaves"]]
        good = sha(t) == it["file_sha256"] and len(hs) == it["leaf_count"] and mth(hs).hex() == it["merkle_root"] == d["merkle_root"]
        (r.ok if good else r.bad)(f"{it['stream']} {it['day']}: {it['leaf_count']} leaves rebuild to {it['merkle_root'][:16]}...")
        roots.append(bytes.fromhex(it["merkle_root"]))
    (r.ok if mth(roots).hex() == idx["items_root"] else r.bad)("items_root rebuilds from the item roots")
    print(f"\nRESULT late cover {batch}: {'OK' if not r.fail else 'FAILED'} ({r.fail} failures, {r.warn} warnings)")
    return r.fail == 0

if __name__ == "__main__":
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    sp = ap.add_subparsers(dest="cmd", required=True)
    f = sp.add_parser("fetch"); f.add_argument("day"); f.add_argument("-o", "--out")
    f.add_argument("--records", choices=["all", "sample", "none"], default="sample"); f.add_argument("--limit", type=int, default=25)
    c = sp.add_parser("check"); c.add_argument("dir")
    p = sp.add_parser("prove"); p.add_argument("dir"); p.add_argument("id")
    rc = sp.add_parser("record"); rc.add_argument("file"); rc.add_argument("dir")
    lc = sp.add_parser("late"); lc.add_argument("batch"); lc.add_argument("-o", "--out")
    a = ap.parse_args()
    if a.cmd == "fetch": fetch(a.day, a.out or f"day-{a.day}", a.records, a.limit); sys.exit(0)
    if a.cmd == "check": sys.exit(0 if check(a.dir) else 1)
    if a.cmd == "prove": sys.exit(0 if prove(a.dir, a.id) else 1)
    if a.cmd == "record": sys.exit(0 if record(a.file, a.dir) else 1)
    if a.cmd == "late": sys.exit(0 if late(a.batch, a.out or f"late-{a.batch}") else 1)
