#!/usr/bin/env python3
"""
Check the Attention Scanner trade ledger against the Solana blockchain.

Python 3.8 or newer, standard library only. Run:

    python3 proof_verify.py
    python3 proof_verify.py https://attention.volametric.com

What it checks:

  1. Every published entry hashes to the value shown:
     sha256(prev_hash + "\\n" + record + "\\n" + salt).
  2. Every entry points at the hash of the entry before it, so no entry can be
     removed, inserted or reordered without breaking the chain.
  3. Every Solana transaction listed carries the hash of the entry it covers
     in its memo, and is signed by the ledger's address. The script reads the
     transactions from a public Solana node, not from our site.

Entries of positions that are still open show only their hash. Their text
appears when the position closes, and the script checks it then.
"""

import hashlib
import json
import sys
import time
import urllib.request

SITE = (sys.argv[1] if len(sys.argv) > 1 else "https://attention.volametric.com").rstrip("/")
RPC = {"devnet": "https://api.devnet.solana.com",
       "mainnet-beta": "https://api.mainnet-beta.solana.com"}


def get_json(url):
    req = urllib.request.Request(url, headers={"User-Agent": "proof-verify/1"})
    with urllib.request.urlopen(req, timeout=30) as r:
        return json.load(r)


def rpc(url, method, params):
    body = json.dumps({"jsonrpc": "2.0", "id": 1, "method": method,
                       "params": params}).encode()
    req = urllib.request.Request(url, data=body,
                                 headers={"Content-Type": "application/json"})
    for attempt in range(5):
        try:
            with urllib.request.urlopen(req, timeout=30) as r:
                out = json.load(r)
            if "error" in out:
                raise RuntimeError(out["error"])
            return out["result"]
        except Exception:
            if attempt == 4:
                raise
            time.sleep(2 * (attempt + 1))


def main():
    chain = get_json(SITE + "/api/proof")
    events = chain["events"]
    problems = []

    prev = "0" * 64
    checked = 0
    for e in events:
        if e["prev_hash"] != prev:
            problems.append(f"entry #{e['seq']}: does not point at entry before it")
        if e["record"] is not None:
            h = hashlib.sha256((e["prev_hash"] + "\n" + e["record"] + "\n"
                                + e["salt"]).encode("utf-8")).hexdigest()
            if h != e["hash"]:
                problems.append(f"entry #{e['seq']}: text does not match its hash")
            checked += 1
        prev = e["hash"]

    by_seq = {e["seq"]: e for e in events}
    node = RPC.get(chain["cluster"])
    print(f"Solana network: {chain['cluster']}, signer {chain['signer']}")
    for a in chain["anchors"]:
        head = by_seq.get(a["head_seq"])
        if not head or head["hash"] != a["head_hash"]:
            problems.append(f"tx {a['signature']}: hash is not entry #{a['head_seq']}")
            continue
        tx = rpc(node, "getTransaction", [a["signature"], {
            "encoding": "json", "commitment": "confirmed",
            "maxSupportedTransactionVersion": 0}])
        if not tx:
            problems.append(f"tx {a['signature']}: not found on Solana")
            continue
        logs = " ".join(tx["meta"].get("logMessages") or [])
        keys = tx["transaction"]["message"]["accountKeys"]
        if a["head_hash"] not in logs:
            problems.append(f"tx {a['signature']}: memo does not carry the hash")
        if keys[0] != chain["signer"]:
            problems.append(f"tx {a['signature']}: signed by another address")
        when = time.strftime("%Y-%m-%d %H:%M:%S UTC", time.gmtime(tx["blockTime"]))
        print(f"  entries up to #{a['head_seq']}: on Solana since {when}")
        time.sleep(0.2)

    unanchored = [e for e in events if not e.get("anchor")]
    print(f"Entries: {len(events)}, text checked: {checked}, "
          f"hidden until close: {len(events) - checked}, "
          f"transactions checked: {len(chain['anchors'])}, "
          f"waiting for a transaction: {len(unanchored)}")
    if problems:
        print("PROBLEMS:")
        for p in problems:
            print("  " + p)
        sys.exit(1)
    if unanchored:
        print(f"OK so far: every entry matches its hash, but {len(unanchored)}"
              " entries are not on Solana yet.")
    else:
        print("OK: every entry matches its hash and its Solana transaction.")


if __name__ == "__main__":
    main()
