#!/usr/bin/env python3
"""Quorscan open verifier (MIT, Python 3.8+, standard library only).

Checks that the Quorscan ledger ("every scan, sealed") was not edited:
  1. downloads every ledger entry (GET /api/ledger) and recomputes each hash:
       hash_i = keccak256( b"qs1" + prev_i (32 raw bytes) + utf8(c_i) ),  prev_1 = 32 zero bytes, prev_i = hash_{i-1}
     and checks that c_i is in canonical form (keys sorted, no spaces, JS number formatting);
  2. downloads every hourly seal (GET /api/seals) and checks that its head hash and count match the ledger and that its calldata is
       "qs1" (3 bytes) + hour (uint64 big-endian) + head hash (32 bytes) + count (uint64 big-endian);
  3. for every anchored seal, reads the transaction from a Robinhood Chain RPC (chain id 4663) and checks that it succeeded, that it
     was sent by the anchor wallet to itself with value 0, and that its input is exactly that calldata. A head commits to every earlier
     report, so one anchored head proves every report before it existed, unchanged, by that block time.

usage:  python3 verify.py [--base https://quorscan.pages.dev] [--rpc URL] [--no-chain] [--quiet]
exit code 0 = PASS, 1 = FAIL, 2 = could not download."""
import json, sys, time, urllib.request, urllib.error

BASE = 'https://quorscan-engine.pages.dev'
RPCS = ['https://robinhood-rpc.publicnode.com', 'https://robinhood.drpc.org', 'https://rpc.mainnet.chain.robinhood.com']
UA = 'quorscan-verifier/1 (python)'

# ---------------- keccak-256 (Ethereum variant) ----------------
RC = [0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, 0x000000000000808B, 0x0000000080000001,
      0x8000000080008081, 0x8000000000008009, 0x000000000000008A, 0x0000000000000088, 0x0000000080008009, 0x000000008000000A,
      0x000000008000808B, 0x800000000000008B, 0x8000000000008089, 0x8000000000008003, 0x8000000000008002, 0x8000000000000080,
      0x000000000000800A, 0x800000008000000A, 0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008]
ROT = [0, 1, 62, 28, 27, 36, 44, 6, 55, 20, 3, 10, 43, 25, 39, 41, 45, 15, 21, 8, 18, 2, 61, 56, 14]
M64 = (1 << 64) - 1
def _rol(v, n): return ((v << n) | (v >> (64 - n))) & M64 if n else v
def _f(A):
    for rc in RC:
        C = [A[x] ^ A[x + 5] ^ A[x + 10] ^ A[x + 15] ^ A[x + 20] for x in range(5)]
        D = [C[(x - 1) % 5] ^ _rol(C[(x + 1) % 5], 1) for x in range(5)]
        A = [A[i] ^ D[i % 5] for i in range(25)]
        B = [0] * 25
        for x in range(5):
            for y in range(5): B[y + 5 * ((2 * x + 3 * y) % 5)] = _rol(A[x + 5 * y], ROT[x + 5 * y])
        A = [B[i] ^ (~B[(i % 5 + 1) % 5 + 5 * (i // 5)] & B[(i % 5 + 2) % 5 + 5 * (i // 5)]) for i in range(25)]
        A[0] ^= rc
    return A
def keccak256(data):
    p = bytearray(data) + b'\x01'
    while len(p) % 136: p.append(0)
    p[-1] |= 0x80
    A = [0] * 25
    for off in range(0, len(p), 136):
        for i in range(17): A[i] ^= int.from_bytes(p[off + 8 * i: off + 8 * i + 8], 'little')
        A = _f(A)
    return b''.join(A[i].to_bytes(8, 'little') for i in range(4))
assert keccak256(b'').hex() == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'

# ---------------- canonical JSON (identical to the engine's JS) ----------------
def js_num(x):
    """A number exactly as JavaScript's JSON.stringify writes it."""
    if isinstance(x, bool): raise ValueError('bool')
    if isinstance(x, int): return str(x)
    if x != x or x in (float('inf'), float('-inf')): raise ValueError('non-finite number')
    if x == 0: return '0'
    if x.is_integer() and abs(x) < 1e21: return str(int(x))
    r, sign = repr(x), ''
    if r[0] == '-': sign, r = '-', r[1:]
    mant, exp = (r.split('e') + ['0'])[:2]
    exp = int(exp)
    ip, fp = (mant.split('.') + [''])[:2]
    digits = (ip + fp).lstrip('0')
    n = len(ip.lstrip('0')) + exp if ip.strip('0') else exp - (len(fp) - len(fp.lstrip('0')))
    digits = digits.rstrip('0') or '0'
    k = len(digits)
    if k <= n <= 21: s = digits + '0' * (n - k)
    elif 0 < n <= 21: s = digits[:n] + '.' + digits[n:]
    elif -6 < n <= 0: s = '0.' + '0' * (-n) + digits
    else:
        e = n - 1
        s = digits[0] + ('.' + digits[1:] if k > 1 else '') + 'e' + ('+' if e >= 0 else '-') + str(abs(e))
    return sign + s
for v, want in ((1.0, '1'), (0.25, '0.25'), (1e21, '1e+21'), (1e-7, '1e-7'), (0.000001, '0.000001'), (123.456, '123.456'), (-0.5, '-0.5'), (5e-324, '5e-324')):
    assert js_num(v) == want, (v, js_num(v), want)
def canonical(v):
    if v is None: return 'null'
    if v is True: return 'true'
    if v is False: return 'false'
    if isinstance(v, (int, float)): return js_num(v)
    if isinstance(v, str): return json.dumps(v, ensure_ascii=False)
    if isinstance(v, list): return '[' + ','.join(canonical(x) for x in v) + ']'
    if isinstance(v, dict): return '{' + ','.join(json.dumps(k, ensure_ascii=False) + ':' + canonical(v[k]) for k in sorted(v)) + '}'
    raise ValueError('unsupported type %r' % type(v))

def entry_hash(prev, c):
    return '0x' + keccak256(b'qs1' + bytes.fromhex(prev[2:]) + c.encode('utf-8')).hex()
def seal_calldata(hour, head, count):
    return '0x' + (b'qs1' + hour.to_bytes(8, 'big') + bytes.fromhex(head[2:]) + count.to_bytes(8, 'big')).hex()

# ---------------- I/O ----------------
def get(url, tries=3):
    last = None
    for i in range(tries):
        try:
            req = urllib.request.Request(url, headers={'accept': 'application/json', 'user-agent': UA})
            return json.loads(urllib.request.urlopen(req, timeout=60).read())
        except Exception as e:
            last = e; time.sleep(1 + 2 * i)
    raise SystemExit('could not download %s (%s)' % (url, last))
def rpc(rpcs, method, params):
    last = None
    for u in rpcs:
        try:
            req = urllib.request.Request(u, data=json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}).encode(),
                                         headers={'content-type': 'application/json', 'user-agent': UA})
            j = json.loads(urllib.request.urlopen(req, timeout=25).read())
            if 'result' in j: return j['result']
            last = j.get('error')
        except Exception as e:
            last = e
    raise RuntimeError('no RPC answered %s (%s)' % (method, last))

def main(argv):
    base, rpcs, chain, quiet = BASE, RPCS, True, False
    i = 0
    while i < len(argv):
        a = argv[i]
        if a == '--base': base = argv[i + 1].rstrip('/'); i += 1
        elif a == '--rpc': rpcs = [argv[i + 1]]; i += 1
        elif a == '--no-chain': chain = False
        elif a == '--quiet': quiet = True
        elif a in ('-h', '--help'): print(__doc__); return 0
        i += 1
    say = (lambda *x: None) if quiet else print
    fails = []
    # 1. the ledger
    entries, frm = [], 1
    while True:
        page = get('%s/api/ledger?from=%d&limit=200' % (base, frm))
        entries += page.get('entries') or []
        if not page.get('next'): head = page.get('head') or {}; break
        frm = page['next']
    prev, hashes = '0x' + '00' * 32, {}
    for n, e in enumerate(entries, 1):
        if e['seq'] != n: fails.append('entry %d is missing (found %d)' % (n, e['seq'])); break
        if e['prev'].lower() != prev: fails.append('entry %d does not point to the hash of entry %d' % (n, n - 1)); break
        try:
            if canonical(json.loads(e['c'])) != e['c']: fails.append('entry %d is not in canonical form' % n)
        except ValueError as x: fails.append('entry %d: %s' % (n, x))
        h = entry_hash(prev, e['c'])
        if h != e['hash'].lower(): fails.append('entry %d was changed: its content gives %s, the ledger says %s' % (n, h, e['hash'])); break
        hashes[n] = h; prev = h
    say('ledger   %d entries, every hash recomputed%s; head %s' % (len(entries), '' if not fails else ' (FAILED)', prev))
    if head and head.get('seq') and head['seq'] > len(entries): say('         (the ledger grew to %d while downloading; the new entries are checked next run)' % head['seq'])
    # 2. seals
    seals, before = [], None
    while True:
        page = get('%s/api/seals?limit=100%s' % (base, '&before=%d' % before if before else ''))
        if before is None: anchor = page.get('anchor') or {}
        seals += page.get('seals') or []
        if not page.get('nextBefore'): break
        before = page['nextBefore']
    wallet = (anchor.get('wallet') or '').lower()
    checked = 0
    for s in seals:
        hs = s['headSeq']
        if hs in hashes and hashes[hs] != s['headHash'].lower(): fails.append('seal %d: head %s is not ledger entry %d (%s)' % (s['hour'], s['headHash'], hs, hashes[hs]))
        if s['calldata'].lower() != seal_calldata(s['hour'], s['headHash'].lower(), s['count']): fails.append('seal %d: calldata does not encode hour, head and count' % s['hour'])
        checked += 1
    confirmed = [s for s in seals if s['status'] == 'confirmed' and s.get('tx')]
    say('seals    %d seals checked against the ledger; %d anchored on-chain; anchor wallet %s (%s)' % (checked, len(confirmed), wallet or 'none', anchor.get('status')))
    # 3. anchors on Robinhood Chain
    if chain and confirmed:
        for s in confirmed:
            try:
                tx = rpc(rpcs, 'eth_getTransactionByHash', [s['tx']])
                rc = rpc(rpcs, 'eth_getTransactionReceipt', [s['tx']])
                if not tx or not rc: fails.append('seal %d: tx %s not found on-chain' % (s['hour'], s['tx'])); continue
                if (tx.get('input') or '').lower() != s['calldata'].lower(): fails.append('seal %d: on-chain input differs from the calldata' % s['hour'])
                if tx['from'].lower() != wallet or (tx.get('to') or '').lower() != wallet: fails.append('seal %d: tx not sent by the anchor wallet to itself' % s['hour'])
                if int(tx.get('value') or '0x0', 16) != 0: fails.append('seal %d: tx has a value' % s['hour'])
                if int(tx.get('chainId') or '0x1237', 16) != 4663: fails.append('seal %d: wrong chain id' % s['hour'])
                if rc.get('status') != '0x1': fails.append('seal %d: tx reverted' % s['hour'])
                blk = rpc(rpcs, 'eth_getBlockByNumber', [rc['blockNumber'], False])
                ts = int(blk['timestamp'], 16)
                say('  anchor %s  hour %s  block %d  %s  head #%d  ok' % (s['tx'][:12] + '…', time.strftime('%Y-%m-%d %H:00 UTC', time.gmtime(s['hour'])), int(rc['blockNumber'], 16), time.strftime('%H:%M:%S', time.gmtime(ts)), s['headSeq']))
            except RuntimeError as x:
                fails.append('seal %d: %s' % (s['hour'], x))
    elif not confirmed:
        say('anchors  none yet (%s)' % (anchor.get('note') or 'anchoring starts once the anchor wallet is funded'))
    if fails:
        print('FAIL'); [print('  - ' + f) for f in fails[:50]]
        return 1
    last = max([s for s in confirmed], key=lambda s: s['headSeq'], default=None)
    print('PASS: %d reports, hash chain intact%s.' % (len(entries), '; entries 1..%d are anchored on Robinhood Chain (latest anchor %s)' % (last['headSeq'], last['tx']) if last else '; not anchored on-chain yet'))
    return 0

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