#!/usr/bin/env python3
"""MapleChange anonymous ledger verifier — Python 3.8+ standard library only (no install).
메이플체인지 익명 원장 검증 — 파이썬 표준 라이브러리만(설치 없음). 서버가 /game/ledger/verify.py로 이 파일을 그대로 준다.

  python verify_dump.py <epoch file (.jsonl / .jsonl.gz) or URL> [--manifest <day .txt or URL>] [--rpc <Polygon JSON-RPC URL> --tx <0x…>]

What it checks / 무엇을 보나 (rule = RFC 6962 Merkle tree, same as the game and server — merkle.py · tools/crypto/merkle.cjs):
  1. rows   : every row's ledger position; when all rows of a ledger are in the file, the ledger root is recomputed from the leaves.
              rows marked "full" (no user, no meta removed) → the leaf itself is recomputed from the row content.
  2. batch  : batch root = MTH(leaf("ledger:<l>:<n>:<root>") × 6) must equal the root recorded in the epoch.
  3. channel: channel(instance) subroot = MTH(leaf("batch:<no>:<root>")) must equal the instance line.
  4. world  : world root = MTH(leaf("instance:<id>:<subroot>")) must equal the header — this is the value written on Polygon
              (the epoch anchor transaction's input data). --rpc/--tx compares it with the chain directly.
  5. day    : --manifest = sha256 of this file (uncompressed) must be the "epoch <id> <root> <rows> <sha256>" line of the day list;
              the day list's own sha256 (printed) is the value anchored for that day.
Exit code 0 = everything checked matched · 1 = mismatch · 2 = bad input.
A file downloaded with ?kind= keeps the content of those rows only; every other row is cut down to its leaf ("cut"), so all ledgers are
still recomputed. A ledger that is not complete in a file (a row was removed or added) is reported as a mismatch.
"""

from __future__ import annotations

import argparse
import gzip
import hashlib
import json
import sys
import urllib.request
from decimal import ROUND_HALF_UP, Decimal

LEDGERS = ("meso", "item", "scroll", "cash_rng", "boss_kill", "other")
EMPTY = hashlib.sha256(b"").digest()
_SIX = Decimal("0.000001")


def leaf_hash(data: str) -> bytes:
    return hashlib.sha256(b"\x00" + data.encode("utf-8")).digest()


def node_hash(left: bytes, right: bytes) -> bytes:
    return hashlib.sha256(b"\x01" + left + right).digest()


def mth(leaves):
    if not leaves:
        return EMPTY
    if len(leaves) == 1:
        return leaves[0]
    k = 1
    while k * 2 < len(leaves):
        k *= 2
    return node_hash(mth(leaves[:k]), mth(leaves[k:]))


def _num(v) -> str:
    if isinstance(v, int):
        return "i%d;" % v
    if v == int(v):
        return "i%d;" % int(v)
    return "f" + str(Decimal(v).quantize(_SIX, rounding=ROUND_HALF_UP)) + ";"


def canon(v) -> str:
    if isinstance(v, str):
        return "s%d:%s" % (len(v.encode("utf-8")), v)
    if isinstance(v, bool):
        return "b1" if v else "b0"
    if isinstance(v, (int, float)):
        return _num(v)
    if isinstance(v, (list, tuple)):
        return canon({str(i + 1): x for i, x in enumerate(v)})
    if isinstance(v, dict):
        by = {str(k): x for k, x in v.items()}
        return "{" + "".join(canon(k) + canon(by[k]) for k in sorted(by, key=lambda s: s.encode("utf-8"))) + "}"
    raise ValueError("unsupported value %r" % (v,))


def row_leaf(row: dict, t_shift: int) -> bytes:
    r = {"t": row["t"] + t_shift, "k": row["k"], "r": row["r"], "u": row.get("u", ""), "d": row.get("d", 0)}
    if "m" in row:
        r["m"] = row["m"]
    return leaf_hash(canon(r))


def _fetch(src: str) -> bytes:
    if src.startswith("http://") or src.startswith("https://"):
        req = urllib.request.Request(src, headers={"User-Agent": "maplechange-verify/1"})
        with urllib.request.urlopen(req, timeout=60) as resp:
            return resp.read()
    with open(src, "rb") as f:
        return f.read()


def _text(raw: bytes) -> bytes:
    return gzip.decompress(raw) if raw[:2] == b"\x1f\x8b" else raw


def verify(data: bytes, out=print) -> dict:
    """data = uncompressed JSONL. → {"ok", "worldRoot", "epoch", "rows", "given", "full", "errors"}."""
    lines = [json.loads(x) for x in data.decode("utf-8").splitlines() if x.strip()]
    if not lines or lines[0].get("type") != "epoch":
        raise ValueError("first line must be the epoch header")
    head = lines[0]
    errors = []
    insts = []  # [(i, s, [batch …])]
    cur_inst = cur_batch = None
    for x in lines[1:]:
        t = x.get("type")
        if t == "instance":
            cur_inst = {"i": x["i"], "s": x["s"], "batches": []}
            insts.append(cur_inst)
        elif t == "batch":
            if cur_inst is None or x["i"] != cur_inst["i"]:
                raise ValueError("batch line outside its instance")
            cur_batch = dict(x, rows=[])
            cur_inst["batches"].append(cur_batch)
        elif t == "row":
            if cur_batch is None:
                raise ValueError("row line before any batch line")
            cur_batch["rows"].append(x)  # 줄 = 바로 위 묶음 줄의 것(채널·묶음 번호는 그 줄에)
    stats = {"rows": 0, "given": 0, "recomputed": 0, "full": 0}
    inst_leaves = []
    for inst in insts:
        batch_leaves = []
        for b in inst["batches"]:
            shift = int(b.get("tShift") or 0)
            by = {l: [] for l in LEDGERS}
            for r in b["rows"]:
                stats["rows"] += 1
                leaf = bytes.fromhex(r["leaf"])
                if r.get("full"):
                    stats["full"] += 1
                    if row_leaf(r, shift) != leaf:
                        errors.append("row %s: content does not match its leaf" % r.get("id"))
                by[r["l"]].append((r["x"], leaf))
            top = []
            for led in b["ledgers"]:
                got = sorted(by[led["l"]])
                root = led["root"]
                if len(got) == led["n"] and [x for x, _ in got] == list(range(led["n"])):
                    mine = mth([h for _, h in got]).hex()
                    stats["recomputed"] += 1
                    if mine != root:
                        errors.append("batch %s/%s ledger %s: root from rows %s != %s" % (b["i"][:8], b["no"], led["l"], mine[:16], root[:16]))
                        root = mine
                else:
                    # 서버 파일(전부·거른 것)엔 늘 원장 줄이 다 있음 → 빠지거나 남는 줄 = 숨긴·더한 줄
                    stats["given"] += 1
                    errors.append("batch %s/%s ledger %s: %d rows in file, batch line says %d" % (
                        b["i"][:8], b["no"], led["l"], len(got), led["n"]))
                top.append(leaf_hash("ledger:%s:%d:%s" % (led["l"], led["n"], root)))
            broot = mth(top).hex()
            if broot != b["root"]:
                errors.append("batch %s/%s: batch root %s != recorded %s" % (b["i"][:8], b["no"], broot[:16], b["root"][:16]))
            batch_leaves.append((int(b["no"]), leaf_hash("batch:%d:%s" % (int(b["no"]), b["root"]))))
        sub = mth([h for _, h in sorted(batch_leaves)]).hex()
        if sub != inst["s"]:
            errors.append("instance %s: subroot %s != %s" % (inst["i"][:8], sub[:16], inst["s"][:16]))
        inst_leaves.append((inst["i"].encode("utf-8"), leaf_hash("instance:%s:%s" % (inst["i"], inst["s"]))))
    world = mth([h for _, h in sorted(inst_leaves)]).hex()
    if world != head["worldRoot"]:
        errors.append("world root %s != header %s" % (world, head["worldRoot"]))
    res = {"ok": not errors, "epoch": head.get("epoch"), "world": head.get("world"), "worldRoot": world, "errors": errors, **stats}
    # 출력 = ASCII만(윈도 콘솔 코드페이지에서도 안 깨지게)
    out("epoch %s (%s): rows %d, ledgers recomputed %d, given %d, full rows %d" % (
        head.get("epoch"), head.get("world"), stats["rows"], stats["recomputed"], stats["given"], stats["full"]))
    out("world root %s %s" % (world, "OK" if world == head["worldRoot"] else "MISMATCH"))
    for e in errors[:20]:
        out("  x " + e)
    return res


def check_manifest(manifest: str, epoch_id, data: bytes, world_root: str, out=print) -> bool:
    sha = hashlib.sha256(data).hexdigest()
    out("day list sha256 %s  (= value anchored for that day)" % hashlib.sha256(manifest.encode("utf-8")).hexdigest())
    for line in manifest.splitlines():
        p = line.split()
        if len(p) == 5 and p[0] == "epoch" and p[1] == str(epoch_id):
            ok = p[2] == world_root and p[4] == sha
            out("day list line for epoch %s %s (file sha256 %s)" % (epoch_id, "OK" if ok else "MISMATCH", sha[:16]))
            return ok
    out("day list has no line for epoch %s" % epoch_id)
    return False


def check_tx(rpc: str, tx: str, root: str, out=print) -> bool:
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": "eth_getTransactionByHash", "params": [tx]}).encode()
    req = urllib.request.Request(rpc, data=body, headers={"Content-Type": "application/json", "User-Agent": "maplechange-verify/1"})
    with urllib.request.urlopen(req, timeout=60) as resp:
        got = json.loads(resp.read()).get("result") or {}
    data = str(got.get("input") or got.get("data") or "").lower()
    ok = data == "0x" + root.lower()
    out("tx %s input %s %s" % (tx[:18], data[:18], "OK" if ok else "MISMATCH"))
    return ok


def main(argv=None) -> int:
    p = argparse.ArgumentParser(description="MapleChange anonymous ledger verifier")
    p.add_argument("file", help="epoch file (.jsonl / .jsonl.gz) or URL")
    p.add_argument("--manifest", help="day list (.txt) or URL")
    p.add_argument("--rpc", help="Polygon JSON-RPC URL (to read the anchor transaction)")
    p.add_argument("--tx", help="anchor transaction hash (epoch tx for the world root · day tx with --manifest-root)")
    p.add_argument("--manifest-root", action="store_true", help="compare --tx with the day list sha256 instead of the world root")
    a = p.parse_args(argv)
    try:
        data = _text(_fetch(a.file))
        res = verify(data)
    except (OSError, ValueError, KeyError) as e:
        print("bad input: %s" % e)
        return 2
    ok = res["ok"]
    manifest = None
    if a.manifest:
        manifest = _text(_fetch(a.manifest)).decode("utf-8")
        ok = check_manifest(manifest, res["epoch"], data, res["worldRoot"]) and ok
    if a.rpc and a.tx:
        want = hashlib.sha256(manifest.encode("utf-8")).hexdigest() if (a.manifest_root and manifest) else res["worldRoot"]
        ok = check_tx(a.rpc, a.tx, want) and ok
    print("RESULT %s" % ("OK" if ok else "MISMATCH"))
    return 0 if ok else 1


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