#!/usr/bin/env python3
"""Independent verifier and mirror for the SOST Protocol Registry.

Checks the registry WITHOUT trusting sostcore.com:
  1. on-chain layer: every manifest entry is compared with what a SOST node returns for its TXID (capsule text, signer,
     block hash at that height). Use your own node (--rpc http://127.0.0.1:18232 --rpc-user U --rpc-pass-file F) or
     any public read-only endpoint (default https://sostcore.com/rpc).
  2. off-chain cards: each signed card must verify (ECDSA secp256k1 over SHA-256 of the signed message, DER), its public
     key must hash to the entry's signer, and the message must contain the SHA-256 of the exact payload string.
  3. documents: every published PDF is downloaded and its SHA-256 must equal the address it is served under; a document
     declared as "the registered document" must also match the on-chain anchor.
With --mirror DIR it writes manifest.json, the PDFs (docs/<sha256>.pdf) and MIRROR-SHA256SUMS, so anyone can host an
independent copy of the archive.

CHAIN-ONLY MODE (no sostcore.com, no manifest, no registry server at all):
  --scan-chain [FROM[:TO]]  walks the blocks of ANY SOST node and rebuilds the list of registry records from the
                            transactions themselves (capsule, signer, block, time, confirmations).
  --file PATH / --sha256 HEX  says whether that document's SHA-256 is anchored on-chain (full 256-bit match for capsule
                            v2, 64-bit prefix match for legacy v1) and in which block. Works if the SOST website and
                            its servers no longer exist; only a node is needed.
  --out FILE                writes the rebuilt record list as JSON (sost-protocol-registry-chainscan/1).

Requires Python 3.8+ and the `cryptography` package. Exit code 0 = everything verified, 1 = at least one failure.
"""
import argparse
import base64
import hashlib
import json
import os
import re
import sys
import time
import urllib.request

UA = {"User-Agent": "sost-registry-verify/1"}


def fetch(url, timeout=60):
    with urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=timeout) as r:
        return r.read()


class Node:
    def __init__(self, url, user=None, password=None):
        self.url, self.auth = url, None
        if user:
            self.auth = "Basic " + base64.b64encode(("%s:%s" % (user, password or "")).encode()).decode()

    def call(self, method, params):
        body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method, "params": params}).encode()
        h = dict(UA, **{"Content-Type": "application/json"})
        if self.auth:
            h["Authorization"] = self.auth
        with urllib.request.urlopen(urllib.request.Request(self.url, data=body, headers=h), timeout=60) as r:
            j = json.loads(r.read())
        if j.get("error"):
            raise RuntimeError(str(j["error"]))
        return j.get("result")


def capsule_text(tx):
    cap = tx.get("capsule")
    if isinstance(cap, dict) and cap.get("type") == "open_note" and isinstance(cap.get("text"), str):
        return cap["text"]
    for o in tx.get("vout") or []:
        h = (o.get("payload_hex") or "").lower()
        if len(h) >= 26 and h[:8] == "53430101":
            n = int(h[24:26], 16)
            try:
                return bytes.fromhex(h[26:26 + 2 * n]).decode()
            except Exception:
                return None
    return None


def anchor_of(capsule):
    m = re.fullmatch(r"sost-protocol ([a-z0-9-]{1,30}) ([0-9a-f]{16})", capsule or "")
    if m:
        return m.group(2)
    m = (re.fullmatch(r"sost-protocol ([a-z0-9-]{1,22}) ([A-Za-z0-9_-]{43})", capsule or "")       # v2
         or re.fullmatch(r"sost ([a-z0-9-]{1,31}) ([A-Za-z0-9_-]{43})", capsule or ""))               # v3
    if m:
        raw = base64.urlsafe_b64decode(m.group(2) + "=")
        if len(raw) == 32 and base64.urlsafe_b64encode(raw).decode().rstrip("=") == m.group(2):
            return raw.hex()
    return None


def address_of(pub_hex):
    return "sost1" + hashlib.new("ripemd160", hashlib.sha256(bytes.fromhex(pub_hex)).digest()).hexdigest()


def sig_ok(pub_hex, message, sig_hex):
    from cryptography.exceptions import InvalidSignature
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import ec, utils
    try:
        pub = ec.EllipticCurvePublicKey.from_encoded_point(ec.SECP256K1(), bytes.fromhex(pub_hex))
        pub.verify(bytes.fromhex(sig_hex), hashlib.sha256(message.encode()).digest(), ec.ECDSA(utils.Prehashed(hashes.SHA256())))
        return True
    except (InvalidSignature, ValueError):
        return False


def scan_chain(node, rng, want_sha=None, out=None):
    tip = int(node.call("getblockcount", []))
    lo, _, hi = (rng or "").partition(":")
    lo = int(lo) if lo else 7000                     # Open Note capsules exist from V12 (#7,350)
    hi = min(int(hi), tip) if hi else tip
    recs = []
    for h in range(lo, hi + 1):
        bh = node.call("getblockhash", [str(h)])
        blk = node.call("getblock", [bh])
        for tid in (blk.get("txids") or [])[1:]:     # the coinbase carries no capsule
            tx = node.call("gettransaction", [tid])
            cap = capsule_text(tx or {})
            anc = anchor_of(cap)
            if not anc:
                continue
            recs.append({"txid": tid, "capsule": cap, "record": cap.split(" ")[1], "anchor_hex": anc,
                         "anchor_bits": 256 if len(anc) == 64 else 64,
                         "capsule_version": 1 if len(anc) == 16 else (3 if cap.startswith("sost ") else 2),
                         "signer": tx.get("source_address") or ((tx.get("vin") or [{}])[0].get("address")),
                         "height": h, "block_hash": bh, "time": blk.get("time"), "confirmations": tip - h + 1})
        if (h - lo) % 2000 == 0 and h != lo:
            print("  scanned to #%d (%d records)" % (h, len(recs)), file=sys.stderr)
    print("chain scan #%d..#%d (tip #%d): %d registry records found" % (lo, hi, tip, len(recs)))
    for r in recs:
        print("  #%-7d %s  %-22s %s-bit  %s" % (r["height"], r["txid"][:16], r["record"], r["anchor_bits"], r["signer"]))
    if out:
        json.dump({"format": "sost-protocol-registry-chainscan/1", "from": lo, "to": hi, "tip": tip, "records": recs},
                  open(out, "w"), indent=1)
        print("record list written to", out)
    if want_sha:
        hits = [r for r in recs if want_sha.startswith(r["anchor_hex"])]
        for r in hits:
            when = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(int(r["time"]))) if r.get("time") else "?"
            print("MATCH %s: '%s' in block #%d (%s), block time %s, %d confirmations\n      tx %s\n      signer %s" % (
                "FULL 256-BIT" if r["anchor_bits"] == 256 else "64-BIT PREFIX", r["record"], r["height"], r["block_hash"],
                when, r["confirmations"], r["txid"], r["signer"]))
        print("RESULT:", "ANCHORED ON-CHAIN" if hits else "NOT FOUND in the scanned range")
        return 0 if hits else 1
    print("RESULT: CHAIN SCAN COMPLETE")
    return 0


def main():
    ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
    ap.add_argument("--manifest", default="https://sostcore.com/registry-api/export/manifest.json", help="URL or file")
    ap.add_argument("--base", default="https://sostcore.com", help="where published PDFs are fetched from")
    ap.add_argument("--rpc", default="https://sostcore.com/rpc", help="SOST node JSON-RPC (prefer your own node)")
    ap.add_argument("--rpc-user"); ap.add_argument("--rpc-pass-file")
    ap.add_argument("--no-chain", action="store_true", help="skip the on-chain comparison")
    ap.add_argument("--no-docs", action="store_true", help="skip downloading PDFs")
    ap.add_argument("--mirror", help="write an independent mirror into this directory")
    ap.add_argument("--scan-chain", nargs="?", const="", metavar="FROM[:TO]", help="chain-only mode: rebuild from a node")
    ap.add_argument("--file", help="chain-only mode: check this document")
    ap.add_argument("--sha256", help="chain-only mode: check this SHA-256 (64 hex)")
    ap.add_argument("--out", help="chain-only mode: write the rebuilt record list (JSON)")
    a = ap.parse_args()
    if a.scan_chain is not None or a.file or a.sha256:
        want = None
        if a.file:
            want = hashlib.sha256(open(a.file, "rb").read()).hexdigest()
            print("SHA-256 of %s: %s" % (a.file, want))
        elif a.sha256:
            want = a.sha256.strip().lower()
            if not re.fullmatch(r"[0-9a-f]{64}", want):
                sys.exit("--sha256 needs 64 hex characters")
        pw = open(a.rpc_pass_file).read().strip() if a.rpc_pass_file else None
        sys.exit(scan_chain(Node(a.rpc, a.rpc_user, pw), a.scan_chain, want, a.out))
    raw = open(a.manifest, "rb").read() if os.path.exists(a.manifest) else fetch(a.manifest)
    m = json.loads(raw)
    if m.get("format") != "sost-protocol-registry-manifest/1":
        sys.exit("unknown manifest format: %r" % m.get("format"))
    fails, n_ok = [], 0

    def bad(what):
        fails.append(what); print("FAIL", what)

    pw = open(a.rpc_pass_file).read().strip() if a.rpc_pass_file else None
    node = None if a.no_chain else Node(a.rpc, a.rpc_user, pw)
    by_tx = {}
    for e in m["entries"]:
        by_tx[e["txid"]] = e
        if anchor_of(e["capsule"]) != e["anchor_hex"]:
            bad("entry %s: capsule does not encode the stated anchor" % e["txid"]); continue
        if node:
            try:
                tx = node.call("gettransaction", [e["txid"]])
                bh = node.call("getblockhash", [str(e["height"])])
            except Exception as ex:
                bad("entry %s: node error %s" % (e["txid"], ex)); continue
            signer = tx.get("source_address") or ((tx.get("vin") or [{}])[0].get("address"))
            if capsule_text(tx) != e["capsule"]:
                bad("entry %s: capsule differs on-chain" % e["txid"]); continue
            if signer != e["signer"]:
                bad("entry %s: signer differs on-chain" % e["txid"]); continue
            if bh != e["block_hash"]:
                bad("entry %s: block #%s hash differs (reorg or wrong chain)" % (e["txid"], e["height"])); continue
        n_ok += 1
    print("on-chain entries verified: %d/%d%s" % (n_ok, len(m["entries"]), " (chain check skipped)" if not node else ""))
    c_ok = 0
    for c in m["cards"]:
        e = by_tx.get(c["txid"])
        if not e:
            bad("card %s: its registry transaction is not in the manifest" % c["submission"]); continue
        if c["published_by"] == "operator-curated":
            print("note card %s: operator-curated, unsigned (marked as such on the site)" % c["submission"]); c_ok += 1; continue
        mm = re.search(r"^txid: ([0-9a-f]{64})\nsigner: (sost1[0-9a-f]{40})\nnonce: [0-9a-f]+\npayload-sha256: ([0-9a-f]{64})$",
                       c["message"], re.M)
        if not mm or mm.group(1) != c["txid"] or mm.group(2) != e["signer"]:
            bad("card %s: signed message does not name this txid and signer" % c["submission"]); continue
        if hashlib.sha256(c["payload"].encode()).hexdigest() != mm.group(3):
            bad("card %s: payload differs from what was signed" % c["submission"]); continue
        if address_of(c["pubkey"]) != e["signer"]:
            bad("card %s: public key is not the signer's" % c["submission"]); continue
        if not sig_ok(c["pubkey"], c["message"], c["signature"]):
            bad("card %s: signature does not verify" % c["submission"]); continue
        if json.loads(c["payload"]).get("txid") != c["txid"]:
            bad("card %s: payload names another txid" % c["submission"]); continue
        c_ok += 1
    print("signed cards verified: %d/%d" % (c_ok, len(m["cards"])))
    d_ok = d_n = 0
    if a.mirror:
        os.makedirs(os.path.join(a.mirror, "docs"), exist_ok=True)
        open(os.path.join(a.mirror, "manifest.json"), "wb").write(raw)
    sums = ["%s  manifest.json" % hashlib.sha256(raw).hexdigest()]
    if not a.no_docs:
        for c in m["cards"]:
            d = c.get("document")
            if not d:
                continue
            d_n += 1
            try:
                data = fetch(a.base.rstrip("/") + d["url"])
            except Exception as ex:
                bad("document %s: not downloadable (%s)" % (d["sha256"], ex)); continue
            h = hashlib.sha256(data).hexdigest()
            if h != d["sha256"] or len(data) != d["size"]:
                bad("document %s: content does not match its hash/size" % d["sha256"]); continue
            e = by_tx.get(c["txid"])
            if d["role"] == "registered_document" and e and not h.startswith(e["anchor_hex"]):
                bad("document %s: declared as the registered document but does not match the on-chain anchor" % h); continue
            if a.mirror:
                open(os.path.join(a.mirror, "docs", h + ".pdf"), "wb").write(data)
                sums.append("%s  docs/%s.pdf" % (h, h))
            d_ok += 1
        print("published documents verified: %d/%d" % (d_ok, d_n))
    if a.mirror:
        open(os.path.join(a.mirror, "MIRROR-SHA256SUMS"), "w").write("\n".join(sums) + "\n")
        print("mirror written to", a.mirror, "(check with: sha256sum -c MIRROR-SHA256SUMS)")
    print("RESULT:", "ALL VERIFIED" if not fails else "%d FAILURE(S)" % len(fails))
    sys.exit(1 if fails else 0)


if __name__ == "__main__":
    main()
