#!/usr/bin/env python3
"""aic-verify — AIC 원장의 공개 비트코인 앵커를 «운영자를 믿지 않고» 검증한다 (제3자용, 읽기 전용).

무엇을 확인하나 (서버가 알려 준 status 는 신뢰하지 않고 직접 다시 계산한다)
  1. 앵커 목록의 각 날짜에 대해 <date>.head 와 <date>.head.ots 를 받아, 목록의 journal_id·chain_hash 가 .head 파일과 같은지.
  2. .ots 증명이 «그 .head 파일» 의 것인지(SHA-256), 증명 안의 비트코인 attestation 이 공개 탐색기 2곳의 «원시 블록 헤더»
     (double-SHA256 으로 블록 해시와 대조, merkle root 는 헤더에서 직접 추출)와 맞는지, 확인 깊이 6 이상인지.
  3. 체인 머리가 되돌려지지 않았는지: 날짜가 늘면 journal_id 는 줄지 않고, 같은 journal_id 는 항상 같은 chain_hash 여야 한다.
  4. 서버가 말한 status 와 내 계산이 어긋나면 그 사실을 드러낸다(서버가 verified 라 했는데 내가 확인 못 함 등).

무엇을 증명하지 않나
  · 앵커는 «그 시각에 이 체인 머리가 존재했다» 는 것만 증명한다. 거래 내용이 옳은지·원장 전체가 일관한지는 이 도구의 범위가 아니다.
  · 이 도구가 받아 오는 것은 이미 공개된 /v0/anchors 와 그 파일뿐이다. 거래 내역·개인정보는 받지 않는다.

사용:  python3 aic-verify.py [--base https://aic.star365.site] [--days 30] [--json]
의존:  pip install opentimestamps   (증명 파일 해석에만 쓴다. 비트코인 노드는 필요 없다)
종료코드: 0 이상 없음(오래된 앵커는 모두 verified) · 3 미확정 앵커가 48시간 넘게 남음 · 4 무결성 실패 · 2 사용/네트워크 오류
"""
import hashlib
import json
import sys
import time
import urllib.request
from datetime import datetime, timezone

EXPLORERS = {
    "blockstream": "https://blockstream.info/api",
    "mempool": "https://mempool.space/api",
}
MIN_CONFIRMATIONS = 6
MAX_RESPONSE = 4096


def http_get(url):
    req = urllib.request.Request(url, headers={"user-agent": "aic-ots-verify/1"})
    with urllib.request.urlopen(req, timeout=10) as r:
        data = r.read(MAX_RESPONSE + 1)
    if len(data) > MAX_RESPONSE:
        raise ValueError("explorer response too large")
    return data.decode().strip()


def is_hex(s, n):
    return len(s) == n and all(c in "0123456789abcdef" for c in s.lower())


def explorer_view(get, base, height):
    """(merkle_root_display_hex, tip_height) — 헤더 해시가 블록 해시와 맞지 않으면 ValueError."""
    block_hash = get(f"{base}/block-height/{height}").lower()
    if not is_hex(block_hash, 64):
        raise ValueError("bad block hash")
    header_hex = get(f"{base}/block/{block_hash}/header").lower()
    if not is_hex(header_hex, 160):
        raise ValueError("bad header")
    header = bytes.fromhex(header_hex)
    if hashlib.sha256(hashlib.sha256(header).digest()).digest()[::-1].hex() != block_hash:
        raise ValueError("header does not hash to the block hash")
    tip = get(f"{base}/blocks/tip/height")
    if not tip.isdigit():
        raise ValueError("bad tip height")
    return header[36:68][::-1].hex(), int(tip)


def judge(attestations, get=http_get, explorers=EXPLORERS):
    """attestations: [(height, claimed_merkle_root_display_hex)] → (status line, exit code, notes)"""
    verified, mismatched, undecided, notes = [], [], [], []
    dead = set()   # 이번 실행에서 한 번 실패한 탐색기는 다시 부르지 않는다(attestation 이 많아도 실행 시간이 묶인다)
    for height, claim in sorted(set(attestations)):
        views = {}
        for name, base in explorers.items():
            if name in dead:
                continue
            try:
                views[name] = explorer_view(get, base, height)
            except Exception as e:  # 응답 없음·이상 응답 → 이 탐색기는 판정 보류
                dead.add(name)
                notes.append(f"{name}@{height}: {e}")
        disagree = [k for k, (root, _) in views.items() if root != claim]
        if disagree:
            mismatched.append((height, "+".join(disagree)))
        elif len(views) == len(explorers) and all(tip - height + 1 >= MIN_CONFIRMATIONS for _, tip in views.values()):
            verified.append(height)
        else:
            undecided.append(height)
    if verified:
        for h, who in mismatched:
            notes.append(f"ignored contradicted attestation at {h} ({who}) — another attestation verified")
        return f"verified:{min(verified)}", 0, notes
    if mismatched and not undecided:
        h, who = mismatched[0]
        return f"mismatch:{h}:{who}", 4, notes
    if mismatched:
        notes.append(f"contradicted attestation at {mismatched[0][0]} — waiting on the others")
    return f"attested:{min(undecided or [h for h, _ in mismatched])}", 3, notes

# ↑ http_get·is_hex·explorer_view·judge 는 서버 쪽 deploy/aic-ots-verify.py 와 «글자 그대로 같다»
#   (deploy/test_aic_verify.py 가 소스 일치를 시험한다 — 두 판정기가 몰래 갈라지지 않게).

DEFAULT_BASE = "https://aic.star365.site"
FILE_CAP = 256 * 1024
STALE_HOURS = 48


def fetch(url, cap=FILE_CAP):
    req = urllib.request.Request(url, headers={"user-agent": "aic-verify/1"})
    with urllib.request.urlopen(req, timeout=15) as r:
        data = r.read(cap + 1)
    if len(data) > cap:
        raise ValueError("response too large")
    return data


def check_proof(head_bytes, ots_bytes, get=http_get):
    """(status line, exit code, notes) — aic-ots-verify.main 과 같은 규칙, 파일 대신 바이트."""
    import io
    from opentimestamps.core.notary import BitcoinBlockHeaderAttestation
    from opentimestamps.core.serialize import StreamDeserializationContext
    from opentimestamps.core.timestamp import DetachedTimestampFile

    dtf = DetachedTimestampFile.deserialize(StreamDeserializationContext(io.BytesIO(ots_bytes)))
    if dtf.file_digest != hashlib.sha256(head_bytes).digest():
        return "mismatch:0:proof-is-for-a-different-file", 4, []
    atts = [(a.height, msg[::-1].hex()) for msg, a in dtf.timestamp.all_attestations()
            if isinstance(a, BitcoinBlockHeaderAttestation)]
    if not atts:
        return "pending", 3, []
    return judge(atts, get=get)


def age_hours(stamped_at, now):
    try:
        return (now - datetime.fromisoformat(stamped_at.replace("Z", "+00:00")).timestamp()) / 3600
    except Exception:
        return None


def audit(index, download, prove, now=None, days=30):
    """index: /v0/anchors 의 JSON. download(path)->bytes. prove(head, ots)->(line, code, notes).
    → {"anchors": [...], "findings": [...], "exit": n}. 네트워크를 직접 쓰지 않는다(주입) — 그래서 시험할 수 있다."""
    now = time.time() if now is None else now
    rows, findings = [], []
    listed = sorted(index.get("anchors", []), key=lambda a: a["date"])[-days:]
    if not listed:
        findings.append({"level": "error", "date": None, "what": "the anchor list is empty — there is nothing to verify"})
    for a in listed:
        d = a["date"]
        row = {"date": d, "journal_id": a.get("journal_id"), "server_status": a.get("status"), "mine": None}
        rows.append(row)
        try:
            head = download(a["head"])
        except Exception as e:
            findings.append({"level": "error", "date": d, "what": f"cannot download the head file: {e}"})
            continue
        try:
            h = json.loads(head)
        except Exception:
            findings.append({"level": "fail", "date": d, "what": "the head file is not valid JSON"})
            continue
        if str(h.get("journal_id")) != str(a.get("journal_id")) or h.get("chain_hash") != a.get("chain_hash"):
            findings.append({"level": "fail", "date": d, "what": "the list and the head file disagree about journal_id/chain_hash"})
        if not a.get("proof"):
            row["mine"] = "no-proof"
            if (age_hours(a.get("stamped_at") or "", now) or 0) > STALE_HOURS:
                findings.append({"level": "stale", "date": d, "what": "no timestamp proof is published for this head"})
            continue
        try:
            line, code, notes = prove(head, download(a["proof"]))
        except Exception as e:
            findings.append({"level": "error", "date": d, "what": f"cannot check the proof: {e}"})
            continue
        row["mine"] = line
        for n in notes:
            findings.append({"level": "note", "date": d, "what": n})
        if code == 4:
            findings.append({"level": "fail", "date": d, "what": f"the proof does not hold: {line}"})
        elif line.startswith("verified"):
            pass
        elif (age_hours(a.get("stamped_at") or "", now) or 0) > STALE_HOURS:
            findings.append({"level": "stale", "date": d, "what": f"still {line.split(':')[0]} after {STALE_HOURS} h"})
        claimed = (a.get("status") or "").split(":")[0]
        if claimed == "verified" and not line.startswith("verified"):
            findings.append({"level": "fail" if code == 4 else "warn", "date": d, "what": f"the server says verified but I computed {line}"})
    # 체인 머리는 되돌려지지 않는다
    seen = {}
    prev = None
    for a in listed:
        jid, ch = a.get("journal_id"), a.get("chain_hash")
        if jid is None or ch is None:
            continue
        jid = int(jid)
        if jid in seen and seen[jid][1] != ch:
            findings.append({"level": "fail", "date": a["date"], "what": f"journal {jid} has two different chain hashes ({seen[jid][0]} vs {a['date']}) — the history forked"})
        seen.setdefault(jid, (a["date"], ch))
        if prev is not None and jid < prev[0]:
            findings.append({"level": "fail", "date": a["date"], "what": f"journal_id went backwards: {prev[0]} ({prev[1]}) → {jid}"})
        prev = (jid, a["date"])
    exit_code = 4 if any(f["level"] == "fail" for f in findings) else 2 if any(f["level"] == "error" for f in findings) else 3 if any(f["level"] == "stale" for f in findings) else 0
    return {"anchors": rows, "findings": findings, "exit": exit_code}


def main(argv):
    base, days, as_json = DEFAULT_BASE, 30, False
    it = iter(argv)
    for x in it:
        if x == "--base": base = next(it, "").rstrip("/")
        elif x == "--days": days = int(next(it, "30"))
        elif x == "--json": as_json = True
        else:
            print(__doc__, file=sys.stderr)
            return 2
    try:
        index = json.loads(fetch(f"{base}/v0/anchors"))
    except Exception as e:
        print(f"cannot read {base}/v0/anchors: {e}", file=sys.stderr)
        return 2
    report = audit(index, lambda p: fetch(base + p), check_proof, days=days)
    if as_json:
        print(json.dumps(report, indent=2, ensure_ascii=False))
    else:
        for r in report["anchors"]:
            print(f"{r['date']}  journal {r['journal_id']!s:>6}  server={r['server_status']!s:<9} mine={r['mine']}")
        for f in report["findings"]:
            print(f"[{f['level']}] {f['date'] or '-'}: {f['what']}", file=sys.stderr)
        print({0: "OK — every checked anchor holds", 3: "INCOMPLETE — some anchors are older than 48 h and not verified yet",
               4: "FAIL — an integrity check failed", 2: "ERROR — could not complete"}[report["exit"]])
    return report["exit"]


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