#!/usr/bin/env python3
"""Sealtide open verifier (Python 3.8+, standard library only). https://sealtide.xyz/verifier/

MIT License
Copyright (c) 2026 Sealtide

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation
files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy,
modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software
is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

What it checks, using public data only (Sealtide's read-only API, Lighter's public API, any Robinhood Chain RPC):
  1. ledgers: downloads the full ledger of the six house agents, re-hashes every row (co1) and every prevHash link, and
     compares the head with the server's;
  2. fills: checks N sample fills against Lighter's own 1h candles (close, open on a gap, or the stop / take level inside the range);
  3. anchors: reads each hourly anchor transaction from a Robinhood Chain RPC (chain id 4663), decodes its calldata
     ("CO1" + hour + root + decisionHash) and compares the root with the one recomputed here from the downloaded ledgers,
     and the decision hash with Cortex's stored decision of that hour; also checks the sender and when it was mined.
Paper trading: every fill is simulated at real Lighter prices; nothing here is a promise of profit.

usage: python3 verify.py [--base https://sealtide.xyz] [--samples 12] [--anchors 24|all] [--rpc <url>] [--agent <id>]
"""
import hashlib, json, sys, time, urllib.error, urllib.request
from decimal import Decimal


def arg(k, d):
    a = sys.argv
    return a[a.index('--' + k) + 1] if '--' + k in a and a.index('--' + k) + 1 < len(a) else d


BASE = arg('base', 'https://sealtide.xyz').rstrip('/')
SAMPLES = max(0, int(arg('samples', '12') or 0))
ANCH = arg('anchors', '24')
RPCS = [arg('rpc', '')] if arg('rpc', '') else ['https://robinhood-rpc.publicnode.com', 'https://robinhood.drpc.org', 'https://rpc.mainnet.chain.robinhood.com']
ONLY = arg('agent', '')
LIGHTER = 'https://api.rh.lighter.xyz/api/v1'
AGENTS = ['band', 'breakout', 'cortex', 'cross', 'drift', 'rebound']   # the six house agents, in the anchor's order
ZERO, H = '0' * 64, 3600
UA = {'user-agent': 'sealtide-verify/1.0 (python)', 'accept': 'application/json'}

tally = {'PASS': 0, 'FAIL': 0, 'WARN': 0, 'SKIP': 0}
def out(st, text):
    tally[st] += 1
    print(st.ljust(5) + text, flush=True)
def utc(t): return time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(t))


def get_json(url, allow404=False):
    for i in range(4):
        try:
            return json.loads(urllib.request.urlopen(urllib.request.Request(url, headers=UA), timeout=40).read())
        except urllib.error.HTTPError as e:
            if allow404 and e.code == 404: return None
            if i == 3: raise RuntimeError(f'{url}: HTTP {e.code}')
        except Exception as e:
            if i == 3: raise RuntimeError(f'{url}: {e}')
        time.sleep(0.8 * (i + 1))


def rpc(method, params):
    last = None
    for u in RPCS:
        try:
            body = json.dumps({'jsonrpc': '2.0', 'id': 1, 'method': method, 'params': params}).encode()
            j = json.loads(urllib.request.urlopen(urllib.request.Request(u, data=body, headers={**UA, 'content-type': 'application/json'}), timeout=30).read())
            if 'result' in j: return j['result']
            last = (j.get('error') or {}).get('message')
        except Exception as e:
            last = str(e)
    raise RuntimeError(f'no RPC answered {method} ({last})')


# ---- keccak-256 (Ethereum's Keccak, padding 0x01; hashlib.sha3_256 is the different NIST padding) ----
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]   # index x + 5y
M64 = (1 << 64) - 1
def _rol(v, n): return ((v << n) | (v >> (64 - n))) & M64 if n else v
def _keccak_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):
    rate, p = 136, bytearray(data) + b'\x01'
    while len(p) % rate: p.append(0)
    p[-1] |= 0x80
    A = [0] * 25
    for off in range(0, len(p), rate):
        for i in range(rate // 8): A[i] ^= int.from_bytes(p[off + 8 * i: off + 8 * i + 8], 'little')
        A = _keccak_f(A)
    return b''.join(A[i].to_bytes(8, 'little') for i in range(4)).hex()
assert keccak256(b'') == 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470', 'keccak self-test'


# ---- JavaScript's JSON.stringify, reproduced (the hashes are defined on it) ----
def jsnum(x):
    if isinstance(x, bool): return 'true' if x else 'false'
    if isinstance(x, int): return str(x)
    if x != x or x in (float('inf'), float('-inf')): return 'null'
    if x == int(x) and abs(x) < 1e21: return str(int(x))
    r = repr(x)
    if 'e' in r:
        exp = int(r.split('e')[1])
        if -7 < exp < 21: return format(Decimal(r), 'f')
        m, e = r.split('e'); return m + 'e' + ('+' if int(e) > 0 else '-') + str(abs(int(e)))
    return r
def jsstringify(v):
    if v is None: return 'null'
    if isinstance(v, (bool, int, float)): return jsnum(v)
    if isinstance(v, str): return json.dumps(v, ensure_ascii=False)
    if isinstance(v, list): return '[' + ','.join(jsstringify(x) for x in v) + ']'
    raise TypeError(type(v))


def row_hash(t):
    a = ['co1', t['prevHash'], t['agent'], t['seq'], t['mode'], t['sym'], t['marketId'], t['side'], t['kind'], t['hour'],
         t['price'], t['qty'], t['value'], t['fee'], t['pnl'], t['template']]
    return hashlib.sha256(jsstringify(a).encode('utf-8')).hexdigest()
def root_of(heads): return keccak256(bytes.fromhex(''.join(heads)))
def pledge_of(c):
    return keccak256(jsstringify(['co1-pledge', c['hour'], c['model'], c['system'], c['input'], c['outputText'], c.get('raw') or '']).encode('utf-8'))
def head_at(rows, hour):
    best = None
    for t in rows:
        if t['hour'] <= hour and (best is None or t['seq'] > best['seq']): best = t
    return best['hash'] if best else ZERO
def r8(x):   # JavaScript Math.round(x * 1e8) / 1e8 for positive x
    import math
    return math.floor(x * 1e8 + 0.5) / 1e8


print(f"Sealtide open verifier · {BASE} · {time.strftime('%Y-%m-%d %H:%M', time.gmtime())} UTC\n")
# 1. ledgers
ledgers, rules = {}, {}
for aid in AGENTS + ([ONLY] if ONLY and ONLY not in AGENTS else []):
    det = get_json(f'{BASE}/api/v1/agents/{aid}', allow404=True)
    if not det:
        ledgers[aid] = []; out('SKIP', f'ledger {aid}: no such agent yet (its anchor head is 64 zeros)'); continue
    rules[aid] = (det.get('agent') or {}).get('rule') or {}
    rows, after = [], None
    while True:
        page = get_json(f'{BASE}/api/v1/agents/{aid}/trades?all=1&limit=500' + (f'&after={after}' if after is not None else ''))
        rows += page['trades']; after = page.get('nextAfter')
        if after is None: break
    ledgers[aid] = rows
    prev, bad = ZERO, None
    for i, t in enumerate(rows):
        if t['seq'] != i + 1: bad = f"row {i + 1} missing (found seq {t['seq']})"; break
        if t['prevHash'] != prev: bad = f"row {t['seq']} does not link to row {t['seq'] - 1}"; break
        if row_hash(t) != t['hash']: bad = f"row {t['seq']} was changed: its content no longer gives its hash"; break
        prev = t['hash']
    srv = get_json(f'{BASE}/api/v1/verify/chain/{aid}')
    if bad: out('FAIL', f'ledger {aid}: {bad}')
    elif srv.get('head') != prev: out('FAIL', f"ledger {aid}: {len(rows)} rows re-hashed, but the head {prev[:12]}… differs from the server's {str(srv.get('head'))[:12]}…")
    else: out('PASS', f"ledger {aid}: {len(rows)} fills re-hashed (co1), every link intact, head {prev[:12] + '…' if rows else '(empty)'} = server")

# 2. fills vs Lighter's candles
allf = [t for rows in ledgers.values() for t in rows if not ONLY or t['agent'] == ONLY]
if SAMPLES and allf:
    pick = []
    for k in ['entry', 'take', 'stop', 'exit', 'maxhold', 'ai']:
        xs = [t for t in allf if t['kind'] == k]
        if xs: pick.append(xs[-1])
    i = 0
    while len(pick) < min(SAMPLES, len(allf)) and i < 4 * len(allf):
        t = allf[(i * 7919) % len(allf)]; i += 1
        if t not in pick: pick.append(t)
    for t in pick[:SAMPLES]:
        j = get_json(f"{LIGHTER}/candles?market_id={t['marketId']}&resolution=1h&start_timestamp={t['hour'] - H}&end_timestamp={t['hour'] + H - 1}&count_back=2")
        c = next((x for x in (j or {}).get('c', []) if round(x['t'] / 1000) == t['hour']), None)
        if not c: out('WARN', f"fill {t['id']}: Lighter returned no {t['sym']} candle for {utc(t['hour'])} right now"); continue
        f, ex = (t.get('candle') or {}).get('field'), (rules.get(t['agent']) or {}).get('exit') or {}
        if f == 'c':
            good, why = t['price'] == c['c'], f"close {c['c']}"
        else:
            stop = t['kind'] == 'stop'; pct = ex.get('stopPct') if stop else ex.get('takePct')
            lvl = r8(t['entry'] * ((1 - pct / 100) if stop else (1 + pct / 100))) if t.get('entry') is not None and pct is not None else None
            if f == 'o':
                good = t['price'] == c['o'] and lvl is not None and (c['o'] <= lvl if stop else c['o'] >= lvl); why = f"open {c['o']} past the {'stop' if stop else 'target'} {lvl}"
            else:
                good = lvl is not None and t['price'] == lvl and c['l'] <= t['price'] <= c['h']; why = f"{'stop' if stop else 'target'} {lvl} inside {c['l']}–{c['h']}"
        out('PASS' if good else 'FAIL', f"fill {t['id']} ({t['sym']} {t['side']} {t['kind']}, {utc(t['hour'])}): {t['price']} vs Lighter {why}")
elif not SAMPLES:
    out('SKIP', 'fills vs Lighter: --samples 0')

# 3. anchors on Robinhood Chain
st = get_json(f'{BASE}/api/v1/anchor/status', allow404=True)
want = float('inf') if ANCH == 'all' else max(0, int(ANCH or 0))
anchors, before = [], None
while len(anchors) < want:
    page = get_json(f'{BASE}/api/v1/anchors?status=confirmed&limit=100' + (f'&before={before}' if before else ''), allow404=True)
    if not page: break
    anchors += page['anchors']; before = page.get('nextBefore')
    if not before: break
wallet = (st or {}).get('wallet')
wallet = wallet.lower() if wallet else None
if not anchors:
    out('SKIP', 'anchors: none yet' + (' (anchoring starts once the anchor wallet is funded)' if st and not st.get('funded') else ''))
for a in anchors[:int(want) if want != float('inf') else None]:
    label = f"anchor {utc(a['hour'])}"
    try:
        tx = rpc('eth_getTransactionByHash', [a['tx']])
        rc = tx and rpc('eth_getTransactionReceipt', [a['tx']])
        blk = tx and tx.get('blockNumber') and rpc('eth_getBlockByNumber', [tx['blockNumber'], False])
    except Exception as e:
        out('WARN', f'{label}: {e}'); continue
    if not tx: out('FAIL', f"{label}: tx {a['tx']} not found on Robinhood Chain"); continue
    frm, to, block = str(tx.get('from')).lower(), str(tx.get('to') or '').lower(), int(tx['blockNumber'], 16)
    ts = int(blk['timestamp'], 16) if blk else None
    ok_tx = bool(rc) and rc.get('status') == '0x1' and (not wallet or frm == wallet) and to == frm and int(tx.get('value') or '0x0', 16) == 0
    out('PASS' if ok_tx else 'FAIL', f"{label}: tx {a['tx'][:12]}… mined in block {block}, " + ('sent by the anchor wallet to itself, value 0' if ok_tx else f"from {frm} to {to}, status {rc and rc.get('status')}"))
    b = bytes.fromhex(str(tx.get('input', '')).replace('0x', '', 1))
    if len(b) < 75 or b[:3] != b'CO1': out('FAIL', f'{label}: calldata is not a CO1 anchor'); continue
    hour, root, dec = int.from_bytes(b[3:11], 'big'), b[11:43].hex(), b[43:75].hex()
    mine = root_of([head_at(ledgers.get(aid, []), hour) for aid in AGENTS])
    out('PASS' if hour == a['hour'] and root == mine else 'FAIL', f"{label}: on-chain root {root[:12]}… {'=' if root == mine else '≠'} root of the six ledgers recomputed here" + (f" (calldata hour {hour} ≠ {a['hour']})" if hour != a['hour'] else ''))
    call = get_json(f'{BASE}/api/v1/ai/calls/{hour}', allow404=True)
    exp = pledge_of(call) if call else ZERO
    out('PASS' if dec == exp else 'FAIL', f"{label}: Cortex decision hash {'(no decision that hour)' if dec == ZERO else dec[:12] + '…'} {'=' if dec == exp else '≠'} " + ('keccak of its stored input, output and model' if call else 'zeros'))
    if ts is not None:
        out('PASS' if ts < hour + 2 * H else 'WARN', f"{label}: mined {utc(ts)}, {'before' if ts < hour + 2 * H else 'AFTER'} the next candle closed ({utc(hour + 2 * H)})")

print(f"\n{tally['PASS']} passed, {tally['FAIL']} failed, {tally['WARN']} warnings, {tally['SKIP']} skipped")
print('RESULT: ' + ('FAIL' if tally['FAIL'] else 'PASS'))
sys.exit(1 if tally['FAIL'] else 0)
