"""Independent verifier for the Kerne stock quote agent (schema kerne-stock-quote v1). Shares no code with the Worker. Needs Python 3.9+ and `pip install eth-account`. python -I verify.py [URL] the TSLAc covered call quote (/api/quote) python -I verify.py --multi [URL] the call + put set for every ticker (/api/quotes or /api/quotes/{TICKER}, schema kerne-stock-quotes v1) What it checks: 1. sha256(signed_payload_canonical) equals attestation_hash 2. the EIP-191 signature over that hash recovers to the published signer 3. every displayed field equals the signed field 4. the inputs are real: re-reads the Chainlink rounds and the vault bounds at the signed block on a different public RPC and compares them 5. the numbers follow from the inputs: recomputes realized volatility, expiry, strike and premium with its own integer math and compares to the last digit 6. the EIP-712 signature a contract would check recovers to the same signer The quote is a REFERENCE. Passing these checks means the quote is authentic and follows the published rule. It does not mean the price is right. """ import hashlib import json import math import sys import time import urllib.request TRUST_ROOT = "0x9653Bf177239C979921DC8C0639eD00409F4Db88" # the agent's only signing key DEFAULT_URL = "https://kerne-stock-quote.r4woutreach.workers.dev/api/quote" RPCS = [ "https://mainnet.base.org", "https://base-rpc.publicnode.com", "https://base.drpc.org", "https://1rpc.io/base", "https://gateway.tenderly.co/public/base", ] MULTICALL3 = "0xcA11bde05977b3631167028862bE2a173976CA11" YEAR = 31_536_000 # Kerne runs its own checks with KERNE_SELFTEST=1 so the public counter can leave them out. UA = "quote-verify" + (" kerne-selftest" if __import__("os").environ.get("KERNE_SELFTEST") else "") # ------------------------------------------------------------------ integer math WAD = 10**18 LN2 = 693147180559945309 INV_SQRT_2PI = 398942280401432678 def tdiv(a, b): """Integer division that truncates toward zero (Python's // floors instead).""" q = abs(a) // abs(b) return q if (a >= 0) == (b >= 0) else -q def mul_w(a, b): return tdiv(a * b, WAD) def div_w(a, b): return tdiv(a * WAD, b) def sqrt_w(x): return math.isqrt(x * WAD) def ln_w(x): assert x > 0 k, y = 0, x while y >= 3 * WAD // 2: y, k = y // 2, k + 1 while y < 3 * WAD // 4: y, k = y * 2, k - 1 z = div_w(y - WAD, y + WAD) z2 = mul_w(z, z) term, total, n = z, 0, 0 while n < 40 and term != 0: total += tdiv(term, 2 * n + 1) term = mul_w(term, z2) n += 1 return k * LN2 + 2 * total def exp_w(x): assert -40 * WAD <= x <= 40 * WAD k = tdiv(2 * x + LN2, 2 * LN2) if x >= 0 else tdiv(2 * x - LN2, 2 * LN2) r = x - k * LN2 term, total, n = WAD, WAD, 1 while n <= 30 and term != 0: term = tdiv(mul_w(term, r), n) total += term n += 1 return total * (1 << k) if k >= 0 else tdiv(total, 1 << -k) def norm_cdf_w(x): if x < 0: return WAD - norm_cdf_w(-x) p = 231641900000000000 b = [319381530000000000, -356563782000000000, 1781477937000000000, -1821255978000000000, 1330274429000000000] t = div_w(WAD, WAD + mul_w(p, x)) poly = b[4] for coeff in (b[3], b[2], b[1], b[0]): poly = coeff + mul_w(poly, t) poly = mul_w(poly, t) pdf = mul_w(exp_w(-tdiv(mul_w(x, x), 2)), INV_SQRT_2PI) return WAD - mul_w(pdf, poly) def ceil_div(a, b): return (a + b - 1) // b def utc_date(t): return time.strftime("%Y-%m-%d", time.gmtime(t)) def next_expiry(t, pol): """First Friday 16:00 UTC at least min_tenor away. If the signed policy lists market holidays, a candidate on one moves back a day at a time, and the next week is tried when that falls inside the minimum tenor. A policy without the list (the TSLAc quote, older records) is unchanged. The list is the signer's: this checks that the expiry follows the signed list, not that the list matches the exchange's calendar.""" anchor, period = pol["expiry_anchor_unix"], pol["expiry_period_seconds"] holidays = set(pol.get("market_holidays") or ()) n = -((-(t + pol["min_tenor_seconds"] - anchor)) // period) while True: e = anchor + n * period for _ in range(7): # the same cap as the agent: never more than a week back if utc_date(e) not in holidays: break e -= 86400 if e >= t + pol["min_tenor_seconds"]: return e n += 1 def realized_vol(rounds, window_seconds): """rounds: [(id, answer, updatedAt)] with the anchor first.""" total = 0 for (_, a, _), (_, b, _) in zip(rounds, rounds[1:]): if a <= 0 or b <= 0: # the agent stops summing at the first non-positive answer break r = ln_w(div_w(b, a)) total += mul_w(r, r) ann = total * YEAR // window_seconds if window_seconds > 0 else 0 return total, ann, sqrt_w(ann) def price_call(spot, decimals, vol, block_ts, pol, min_otm_bps, min_premium_bps): expiry = next_expiry(block_ts, pol) tenor = expiry - block_ts priced = vol * (10_000 + pol["vol_markup_bps"]) // 10_000 priced = max(int(pol["vol_floor_wad"]), min(int(pol["vol_cap_wad"]), priced)) sd = mul_w(priced, sqrt_w(tenor * WAD // YEAR)) half_var = mul_w(sd, sd) // 2 target = spot * exp_w(mul_w(int(pol["target_z_wad"]), sd) + half_var) // WAD floor = ceil_div(spot * (10_000 + min_otm_bps + pol["strike_buffer_bps"]), 10_000) step = 10**decimals strike = ceil_div(max(target, floor), step) * step d1 = div_w(ln_w(div_w(spot, strike)) + half_var, sd) d2 = d1 - sd c = max(0, norm_cdf_w(d1) - mul_w(div_w(strike, spot), norm_cdf_w(d2))) model = ceil_div(c * 10_000, WAD) return { "expiry": expiry, "tenor_seconds": tenor, "priced_vol_wad": str(priced), "sd_wad": str(sd), "strike_raw": str(strike), "strike_bound": "delta_target" if target >= floor else "vault_floor_plus_buffer", "strike_otm_bps": (strike - spot) * 10_000 // spot, "d1_wad": str(d1), "call_delta_wad": str(norm_cdf_w(d1)), "premium_fraction_wad": str(c), "model_premium_bps": model, "premium_bps": max(model, min_premium_bps), "premium_floor_applied": max(model, min_premium_bps) != model, } # ------------------------------------------------------------------ chain reads def http_json(url, data=None): req = urllib.request.Request(url, data=json.dumps(data).encode() if data is not None else None, headers={"content-type": "application/json", "user-agent": UA}) return json.load(urllib.request.urlopen(req, timeout=25)) class Rpc: def __init__(self, avoid_host): self.urls = [u for u in RPCS if avoid_host not in u] or RPCS self.used = None def call(self, method, params): last = None for _ in range(2): for u in ([self.used] if self.used else []) + self.urls: try: r = http_json(u, {"jsonrpc": "2.0", "id": 1, "method": method, "params": params}) if "error" in r or r.get("result") is None: raise RuntimeError(str(r.get("error"))[:120]) self.used = u return r["result"] except Exception as e: # noqa: BLE001 last = e self.used = None time.sleep(2) raise last def p32(h): return h.lower().rjust(64, "0") def aggregate3(rpc, calls, block): elems = [] for to, data in calls: d = data[2:] elems.append(p32(to[2:]) + p32("1") + p32("60") + p32(hex(len(d) // 2)[2:]) + d.ljust(-(-len(d) // 64) * 64, "0")) off, offs = len(calls) * 32, [] for e in elems: offs.append(p32(hex(off)[2:])) off += len(e) // 2 data = "0x82ad56cb" + p32("20") + p32(hex(len(calls))[2:]) + "".join(offs) + "".join(elems) h = rpc.call("eth_call", [{"to": MULTICALL3, "data": data}, hex(block)])[2:] w = lambda o: int(h[o * 2:o * 2 + 64], 16) # noqa: E731 arr = w(0) assert w(arr) == len(calls), "multicall length mismatch" base, out = arr + 32, [] for i in range(len(calls)): el = base + w(base + i * 32) do = el + w(el + 32) out.append((w(el) == 1, h[(do + 32) * 2:(do + 32 + w(do)) * 2])) return out def word(data, i, signed=False): v = int(data[i * 64:(i + 1) * 64], 16) return v - (1 << 256) if signed and v >> 255 else v # ------------------------------------------------------------------ main def main(): from eth_account import Account from eth_account.messages import encode_defunct, encode_typed_data global TRUST_ROOT url = sys.argv[1] if len(sys.argv) > 1 else DEFAULT_URL if len(sys.argv) > 2: # only for testing a local build signed by a throwaway key TRUST_ROOT = sys.argv[2] print("NOTE: trust root overridden on the command line:", TRUST_ROOT) doc = http_json(url) results = [] def check(name, ok, detail=""): results.append(ok) print(("PASS " if ok else "FAIL ") + name + ((" " + str(detail)) if detail else "")) canonical = doc["signed_payload_canonical"] p = json.loads(canonical) print("label:", p["label"]) print("status:", p["status"], "| sequence", p["sequence"], "| signed", p["timestamp"]) h = "0x" + hashlib.sha256(canonical.encode()).hexdigest() check("1 sha256(canonical) == attestation_hash", h == doc["attestation_hash"], h) rec = Account.recover_message(encode_defunct(hexstr=doc["attestation_hash"]), signature=doc["signature"]) check("2 EIP-191 signature recovers to the trust root", rec == TRUST_ROOT and p["signer"] == TRUST_ROOT, rec) check("3 displayed fields == signed fields", all(doc.get(k) == v for k, v in p.items())) check("3 canonical form is canonical", json.dumps(p, sort_keys=True, separators=(",", ":")) == canonical) if p["chain"] is None: print("no chain read in this attestation:", p.get("read_errors")) return finish(results) pol, ch, spot, rv, vb, mk = p["policy"], p["chain"], p["spot"], p["realized_vol"], p["vault_bounds"], p["market"] block, block_ts = ch["block_number"], ch["block_timestamp"] rpc = Rpc(ch["rpc_host"]) blk = rpc.call("eth_getBlockByNumber", [hex(block), False]) check("4 block hash and timestamp match", blk["hash"] == ch["block_hash"] and int(blk["timestamp"], 16) == block_ts, f"block {block} via {rpc.used} (the agent used {ch['rpc_host']})") feed, vault = mk["feed"], mk["vault"] names = ["minOtmBps", "minPremiumBps", "minDuration", "maxDuration", "maxStaleness", "epochLive", "salesPaused", "currentEpoch", "depositCap", "lastSettledAt", "idleWindow", "keeper", "feed", "asset", "buyMaxStaleness", "totalAssets"] sels = ["0x90787d8e", "0xd8fcb368", "0x56715761", "0x6db5c8fd", "0x87cf4696", "0x17627ce9", "0xb6b97664", "0x76671808", "0xdbd5edc7", "0x20456ad8", "0x18479a84", "0xaced1661", "0x37a7b7d8", "0x38d52e0f", "0x606d66ef", "0x01e1d114"] res = aggregate3(rpc, [(feed, "0xfeaf968c"), (feed, "0x313ce567")] + [(vault, s) for s in sels], block) lr = res[0][1] check("4 spot is the feed's latest round at that block", str(word(lr, 0)) == spot["round_id"] and str(word(lr, 1, True)) == spot["price_raw"] and word(lr, 3) == spot["updated_at"] and word(res[1][1], 0) == spot["decimals"] and spot["age_seconds"] == block_ts - spot["updated_at"], f"{spot['price']} at round {spot['round_id']}, {spot['age_seconds']}s old") vr = {n: (word(r[1], 0) if r[0] and len(r[1]) >= 64 else None) for n, r in zip(names, res[2:])} same_vault = ( vr["minOtmBps"] == vb["min_otm_bps"] and vr["minPremiumBps"] == vb["min_premium_bps"] and vr["minDuration"] == vb["min_duration_seconds"] and vr["maxDuration"] == vb["max_duration_seconds"] and vr["maxStaleness"] == vb["max_staleness_seconds"] and vr["buyMaxStaleness"] == vb["buy_max_staleness_seconds"] and bool(vr["epochLive"]) == vb["epoch_live"] and bool(vr["salesPaused"]) == vb["sales_paused"] and vr["currentEpoch"] == vb["current_epoch"] and str(vr["depositCap"]) == vb["deposit_cap_raw"] and vr["lastSettledAt"] == vb["last_settled_at"] and vr["idleWindow"] == vb["idle_window_seconds"] and vr["keeper"] == int(vb["keeper"], 16) and vr["feed"] == int(feed, 16) and vr["asset"] == int(mk["stock_token"], 16) and (vb["total_assets_raw"] is None or vr["totalAssets"] is None or str(vr["totalAssets"]) == vb["total_assets_raw"]) ) check("4 vault bounds match the vault at that block", same_vault, f"min OTM {vb['min_otm_bps']} bps, min premium {vb['min_premium_bps']} bps, could_open_now={vb['could_open_now']}") anchor, last = int(rv["anchor_round_id"]), int(rv["last_round_id"]) ids = list(range(anchor - 1, last + 1)) if (anchor & ((1 << 64) - 1)) > 1 else list(range(anchor, last + 1)) rr = aggregate3(rpc, [(feed, "0x9a6fc8f5" + p32(hex(i)[2:])) for i in ids], block) allr = [(i, word(d, 1, True), word(d, 3)) for i, (ok, d) in zip(ids, rr) if ok and len(d) >= 320] rounds = [r for r in allr if r[0] >= anchor] before = [r for r in allr if r[0] < anchor] digest = "0x" + hashlib.sha256("\n".join(f"{i}:{a}:{t}" for i, a, t in rounds).encode()).hexdigest() check("4 the rounds used are the feed's rounds", len(rounds) == last - anchor + 1 and digest == rv["rounds_sha256"] and str(last) == spot["round_id"], f"{len(rounds)} rounds re-read") if rv["truncated"]: window_ok = rv["window_start"] == rounds[0][2] and (not before or last - anchor + 1 == pol["max_rounds_read"]) else: window_ok = (rv["window_start"] == block_ts - pol["lookback_seconds"] and rounds[0][2] <= rv["window_start"] and (len(rounds) < 2 or rounds[1][2] > rv["window_start"])) check("5 window and anchor follow the rule", window_ok and rv["window_end"] == block_ts and rv["window_seconds"] == block_ts - rv["window_start"] and rv["returns"] == len(rounds) - 1, f"{rv['window_seconds']}s, {rv['returns']} returns, truncated={rv['truncated']}") total, ann, vol = realized_vol(rounds, rv["window_seconds"]) check("5 realized volatility recomputed", str(total) == rv["sum_squared_log_returns_wad"] and str(ann) == rv["annualized_variance_wad"] and str(vol) == rv["annualized_vol_wad"], f"{vol / WAD * 100:.2f}% annualized (float cross-check {float_vol(rounds, rv['window_seconds']) * 100:.2f}%)") q = p["quote"] # The agent's gates, in the agent's order. A quote may only exist when none of them trips. bad_round = any(a <= 0 for _, a, _ in rounds) if int(spot["price_raw"]) <= 0: expect = "NO_QUOTE_BAD_FEED_DATA" elif spot["age_seconds"] < 0 or spot["age_seconds"] > vb["max_staleness_seconds"]: expect = "NO_QUOTE_FEED_STALE" elif bad_round or rv["returns"] < pol["min_returns"] or rv["window_seconds"] < pol["min_window_seconds"]: expect = "NO_QUOTE_INSUFFICIENT_HISTORY" else: tenor = next_expiry(block_ts, pol) - block_ts expect = "QUOTE_OK" if vb["min_duration_seconds"] <= tenor <= vb["max_duration_seconds"] else "NO_QUOTE_OUT_OF_VAULT_BOUNDS" check("5 the status follows the agent's gates", p["status"] == expect, f"{p['status']} (expected {expect})") if p["status"] != "QUOTE_OK": check("5 a no-quote record carries no quote", q is None and p["onchain_quote"] is None, p["status_reason"]) return finish(results) mine = price_call(int(spot["price_raw"]), spot["decimals"], vol, block_ts, pol, vb["min_otm_bps"], vb["min_premium_bps"]) diffs = {k: (v, q.get(k)) for k, v in mine.items() if q.get(k) != v} check("5 expiry, strike and premium recomputed", not diffs, diffs or f"strike {q['strike']} ({q['strike_otm_bps']} bps OTM), premium {q['premium_bps']} bps, expiry {q['expiry_time']}") fl = float_premium(int(spot["price_raw"]), int(q["strike_raw"]), int(q["priced_vol_wad"]) / WAD, q["tenor_seconds"]) check("5 float Black-Scholes cross-check within 0.01 bps", abs(fl - int(q["premium_fraction_wad"]) / WAD * 1e4) < 0.01, f"{fl:.4f} bps") floor = ceil_div(int(spot["price_raw"]) * (10_000 + vb["min_otm_bps"]), 10_000) check("5 quote is inside the vault's bounds", int(q["strike_raw"]) >= floor and q["premium_bps"] >= vb["min_premium_bps"] and vb["min_duration_seconds"] <= q["tenor_seconds"] <= vb["max_duration_seconds"] and q["valid_until"] == block_ts + pol["quote_ttl_seconds"] and q["sale_window_seconds"] == pol["sale_window_seconds"] and q["bound_to_round_id"] == spot["round_id"] and q["sellable_now"] == (spot["age_seconds"] <= vb["buy_max_staleness_seconds"]), f"sellable_now={q['sellable_now']}") oc = p["onchain_quote"] m = oc["message"] check("6 on-chain message equals the quote", m == { "vault": vault, "feed": feed, "roundId": spot["round_id"], "spot": spot["price_raw"], "strike": q["strike_raw"], "premiumBps": q["premium_bps"], "saleWindow": q["sale_window_seconds"], "expiry": q["expiry"], "validUntil": q["valid_until"]}) typed = { "types": { "EIP712Domain": [{"name": "name", "type": "string"}, {"name": "version", "type": "string"}, {"name": "chainId", "type": "uint256"}], "Quote": [{"name": n, "type": t} for t, n in (f.split(" ") for f in oc["type"][len("Quote("):-1].split(","))], }, "primaryType": "Quote", "domain": oc["domain"], "message": {**m, "roundId": int(m["roundId"]), "spot": int(m["spot"]), "strike": int(m["strike"])}, } signable = encode_typed_data(full_message=typed) rec712 = Account.recover_message(signable, signature=oc["signature"]) from eth_utils import keccak dg = "0x" + keccak(b"\x19\x01" + signable.header + signable.body).hex() check("6 EIP-712 signature recovers to the trust root", rec712 == TRUST_ROOT and dg == oc["digest"], rec712) age = int(time.time()) - block_ts print(f"quote age {age}s; valid_until is {'still ahead' if time.time() <= q['valid_until'] else 'past (a newer quote should exist)'}") return finish(results) # ------------------------------------------------------------------ multi-ticker set (schema kerne-stock-quotes v1) MULTI_URL = "https://kerne-stock-quote.r4woutreach.workers.dev/api/quotes" # The feeds the agent quotes, read from Chainlink's Base feed directory. Checked against the # signed document and against each feed's description() on chain. MULTI_FEEDS = { "AAPL": "0x787f13dEa48Db0897CbCDD985de77809D837F988", "AMZN": "0x06A8E4b3aBB3B7543d8396FB2B763d22820cB295", "COIN": "0x408e44f504A7371a345F03a73dDC96A4b48e8aa7", "CRCL": "0x0231cF2635D1E17bB5c2462cc7504Ba1fBd61f33", "GOOGL": "0x5bF49E0ffA937CE2FfF033c739aD7C634c4D34F2", "INTC": "0xAB657C39bac0D5886250D70849e2E3E008F2EECB", "META": "0x6526aE6797A76123638b863AeE4dD27Ba4E4b27D", "MSFT": "0xeB10A6c9aa7E537aEd766C08c35Dae35B321b18c", "MSTR": "0xB3cE282CD188b35DA0E38D8Bc7d58e33173D202a", "NVDA": "0x04689a41629776563E6822F76f2e57D148d28513", "SNDK": "0x388b0dC46C0Fb05A74BeE0994fa5b02c6Fcca2eA", "SPCX": "0x6A634B235903C4ad6376892180d6fF8612e3Fa68", "TSLA": "0xFaf869185383a24F8cb00e27BdA6b63B9905DCb4", } OPTION_QUOTE_TYPE = "OptionQuote(address feed,uint8 kind,uint80 roundId,uint256 spot,uint256 strike,uint32 premiumBps,uint64 saleWindow,uint64 expiry,uint64 validUntil)" QUOTE_BATCH_TYPE = "QuoteBatch(bytes32 root,uint64 count,uint64 validUntil)" def m_strike_step(spot, decimals): one = 10**decimals return one if spot >= 100 * one else (one // 2 if spot >= 25 * one else one // 10) def m_sale_window(t, pol): dow = (t // 86400 + 4) % 7 sec = t % 86400 date = utc_date(t) if dow < 1 or dow > 5 or date in (pol.get("market_holidays") or ()): return 0 close = pol["sale_close_utc_seconds"] if date in (pol.get("market_early_closes") or ()): close = pol["sale_close_early_utc_seconds"] if sec < pol["sale_open_utc_seconds"] or sec >= close: return 0 w = close - sec - pol["quote_ttl_seconds"] return w if w >= pol["min_sale_window_seconds"] else 0 def m_common(vol, block_ts, pol): expiry = next_expiry(block_ts, pol) tenor = expiry - block_ts priced = vol * (10_000 + pol["vol_markup_bps"]) // 10_000 priced = max(int(pol["vol_floor_wad"]), min(int(pol["vol_cap_wad"]), priced)) sd = mul_w(priced, sqrt_w(tenor * WAD // YEAR)) return expiry, tenor, priced, sd, mul_w(sd, sd) // 2 def m_leg(kind, expiry, tenor, priced, sd, strike, bound, otm, d1, delta, frac, min_bps): model = ceil_div(frac * 10_000, WAD) prem = max(model, min_bps) return {"kind": kind, "expiry": expiry, "tenor_seconds": tenor, "priced_vol_wad": str(priced), "sd_wad": str(sd), "strike_raw": str(strike), "strike_bound": bound, "strike_otm_bps": otm, "d1_wad": str(d1), "abs_delta_wad": str(delta), "premium_fraction_wad": str(frac), "model_premium_bps": model, "premium_bps": prem, "premium_floor_applied": prem != model} def m_price_call(spot, dec, vol, block_ts, pol): expiry, tenor, priced, sd, half = m_common(vol, block_ts, pol) target = spot * exp_w(mul_w(int(pol["target_z_wad"]), sd) + half) // WAD floor = ceil_div(spot * (10_000 + pol["min_otm_bps"]), 10_000) step = m_strike_step(spot, dec) strike = ceil_div(max(target, floor), step) * step d1 = div_w(ln_w(div_w(spot, strike)) + half, sd) c = max(0, norm_cdf_w(d1) - mul_w(div_w(strike, spot), norm_cdf_w(d1 - sd))) return m_leg("call", expiry, tenor, priced, sd, strike, "delta_target" if target >= floor else "policy_min_otm", (strike - spot) * 10_000 // spot, d1, norm_cdf_w(d1), c, pol["call_min_premium_bps"]) def m_price_put(spot, dec, vol, block_ts, pol): expiry, tenor, priced, sd, half = m_common(vol, block_ts, pol) target = spot * exp_w(half - mul_w(int(pol["target_z_wad"]), sd)) // WAD cap = spot * (10_000 - pol["min_otm_bps"]) // 10_000 step = m_strike_step(spot, dec) strike = (min(target, cap) // step) * step d1 = div_w(ln_w(div_w(spot, strike)) + half, sd) p = max(0, (WAD - norm_cdf_w(d1 - sd)) - mul_w(div_w(spot, strike), WAD - norm_cdf_w(d1))) return m_leg("put", expiry, tenor, priced, sd, strike, "delta_target" if target <= cap else "policy_min_otm", (spot - strike) * 10_000 // spot, d1, WAD - norm_cdf_w(d1), p, pol["put_min_premium_bps"]) def float_put(spot, strike, vol, tenor): sd = vol * math.sqrt(tenor / YEAR) d1 = (math.log(spot / strike) + sd * sd / 2) / sd n = lambda x: 0.5 * math.erfc(-x / math.sqrt(2)) # noqa: E731 return (n(-(d1 - sd)) - spot / strike * n(-d1)) * 1e4 def main_multi(url): from eth_account import Account from eth_account.messages import encode_defunct, encode_typed_data from eth_utils import keccak if url.startswith("http"): doc = http_json(url) else: # a saved record (testing) with open(url, encoding="utf-8") as fh: doc = json.load(fh) results = [] def check(name, ok, detail=""): results.append(bool(ok)) print(("PASS " if ok else "FAIL ") + name + ((" " + str(detail)) if detail else "")) canonical = doc["signed_payload_canonical"] p = json.loads(canonical) print("label:", p["label"]) print("status:", p["status"], "| set", p["sequence"], "| signed", p["timestamp"], "|", p.get("quotes_ok"), "of", p.get("tickers_total"), "quoted") check("schema is kerne-stock-quotes v1", p["schema"] == "kerne-stock-quotes" and p["schema_version"] == 1) h = "0x" + hashlib.sha256(canonical.encode()).hexdigest() check("1 sha256(canonical) == attestation_hash", h == doc["attestation_hash"], h) rec = Account.recover_message(encode_defunct(hexstr=doc["attestation_hash"]), signature=doc["signature"]) check("2 EIP-191 signature recovers to the trust root", rec == TRUST_ROOT and p["signer"] == TRUST_ROOT, rec) if "quotes" in doc: # the full set; /api/quotes/{TICKER} returns row + batch instead check("3 displayed fields == signed fields", all(doc.get(k) == v for k, v in p.items())) elif "row" in doc: row = next((q for q in p["quotes"] if q["ticker"] == doc.get("ticker")), None) check("3 displayed row and batch == signed", doc.get("row") == row and doc.get("batch") == p["batch"], doc.get("ticker")) check("3 canonical form is canonical", json.dumps(p, sort_keys=True, separators=(",", ":")) == canonical) if p["chain"] is None: print("no chain read in this record:", p.get("status_reason"), p.get("read_errors")) return finish(results) pol, ch = p["policy"], p["chain"] block, block_ts = ch["block_number"], ch["block_timestamp"] rpc = Rpc(ch["rpc_host"]) blk = rpc.call("eth_getBlockByNumber", [hex(block), False]) check("4 block hash and timestamp match", blk["hash"] == ch["block_hash"] and int(blk["timestamp"], 16) == block_ts, f"block {block} via {rpc.used} (the agent used {ch['rpc_host']})") check("4 every listed feed is in the published feed list, none missing", sorted(q["ticker"] for q in p["quotes"]) == sorted(MULTI_FEEDS) and all(MULTI_FEEDS[q["ticker"]] == q["feed"] for q in p["quotes"])) sw = m_sale_window(block_ts, pol) check("5 sale window follows the in-session rule", p["in_sale_hours"] == (sw > 0), f"{sw}s at block time {ch['block_time']}") heads = aggregate3(rpc, [c for q in p["quotes"] for c in ((q["feed"], "0xfeaf968c"), (q["feed"], "0x313ce567"), (q["feed"], "0x7284e416"))], block) leaves, legs = [], [] for i, q in enumerate(p["quotes"]): t = q["ticker"] (ok_lr, lr), (ok_d, dd), (ok_s, ds) = heads[i * 3], heads[i * 3 + 1], heads[i * 3 + 2] desc = bytes.fromhex(ds[128:128 + 2 * word(ds, 1)]).decode() if ok_s else "" check(f"4 {t}: feed description is {q['feed_description']}", desc == q["feed_description"] == f"Coinbase {t}") if q["status"] in ("NO_QUOTE_WARMING_UP", "NO_QUOTE_READ_FAILED"): check(f"5 {t}: {q['status']} carries no quote", q["call"] is None and q["put"] is None and q["spot"] is None, q["status_reason"]) continue spot, rv = q["spot"], q["realized_vol"] check(f"4 {t}: spot is the latest round at that block", str(word(lr, 0)) == spot["round_id"] and str(word(lr, 1, True)) == spot["price_raw"] and word(lr, 3) == spot["updated_at"] and word(dd, 0) == spot["decimals"] and spot["age_seconds"] == block_ts - spot["updated_at"], f"{spot['price']}, {spot['age_seconds']}s old") anchor, last = int(rv["anchor_round_id"]), int(rv["last_round_id"]) ids = list(range(anchor - 1, last + 1)) if (anchor & ((1 << 64) - 1)) > 1 else list(range(anchor, last + 1)) rr = aggregate3(rpc, [(q["feed"], "0x9a6fc8f5" + p32(hex(x)[2:])) for x in ids], block) allr = [(x, word(d, 1, True), word(d, 3)) for x, (ok, d) in zip(ids, rr) if ok and len(d) >= 320] rounds = [r for r in allr if r[0] >= anchor] before = [r for r in allr if r[0] < anchor] digest = "0x" + hashlib.sha256("\n".join(f"{a}:{b}:{c}" for a, b, c in rounds).encode()).hexdigest() if rv["truncated"]: agg_last = last & ((1 << 64) - 1) # truncation is only legitimate when the oldest round read is newer than the lookback start window_ok = rv["window_start"] == rounds[0][2] and rounds[0][2] > block_ts - pol["lookback_seconds"] and ( not before or last - anchor + 1 == pol["max_rounds_read"] or (agg_last <= pol["max_rounds_read"] and (anchor & ((1 << 64) - 1)) == 1)) else: window_ok = rv["window_start"] == block_ts - pol["lookback_seconds"] and rounds[0][2] <= rv["window_start"] and (len(rounds) < 2 or rounds[1][2] > rv["window_start"]) check(f"4 {t}: rounds re-read and window follows the rule", len(rounds) == last - anchor + 1 and digest == rv["rounds_sha256"] and str(last) == spot["round_id"] and window_ok and rv["window_end"] == block_ts and rv["returns"] == len(rounds) - 1, f"{len(rounds)} rounds, truncated={rv['truncated']}") total, ann, vol = realized_vol(rounds, rv["window_seconds"]) check(f"5 {t}: realized volatility recomputed", str(total) == rv["sum_squared_log_returns_wad"] and str(ann) == rv["annualized_variance_wad"] and str(vol) == rv["annualized_vol_wad"], f"{vol / WAD * 100:.2f}% (float {float_vol(rounds, rv['window_seconds']) * 100:.2f}%)") if int(spot["price_raw"]) <= 0: expect = "NO_QUOTE_BAD_FEED_DATA" elif spot["age_seconds"] < 0 or spot["age_seconds"] > pol["max_spot_age_seconds"]: expect = "NO_QUOTE_FEED_STALE" elif any(a <= 0 for _, a, _ in rounds) or rv["returns"] < pol["min_returns"] or rv["window_seconds"] < pol["min_window_seconds"]: expect = "NO_QUOTE_INSUFFICIENT_HISTORY" else: expect = "QUOTE_OK" s_, dec_ = int(spot["price_raw"]), spot["decimals"] if expect == "QUOTE_OK" and q["status"] == "NO_QUOTE_OUT_OF_BOUNDS": # only legitimate if the recomputed quote really is out of bounds try: c_, p_ = m_price_call(s_, dec_, vol, block_ts, pol), m_price_put(s_, dec_, vol, block_ts, pol) oob = c_["premium_bps"] >= 10_000 or p_["premium_bps"] >= 10_000 or int(p_["strike_raw"]) <= 0 except Exception: # noqa: BLE001 oob = True expect = "NO_QUOTE_OUT_OF_BOUNDS" if oob else "QUOTE_OK" check(f"5 {t}: status follows the gates", q["status"] == expect, f"{q['status']} (expected {expect})") if q["status"] != "QUOTE_OK": check(f"5 {t}: a no-quote row carries no quote", q["call"] is None and q["put"] is None, q["status_reason"]) continue s, dec = s_, dec_ check(f"5 {t}: in_sale_hours", q["in_sale_hours"] == (sw > 0)) for leg, mine, flt in (("call", m_price_call(s, dec, vol, block_ts, pol), float_premium), ("put", m_price_put(s, dec, vol, block_ts, pol), float_put)): got = q[leg] diffs = {k: (v, got.get(k)) for k, v in mine.items() if got.get(k) != v} one = 10**dec disp = f"{int(got['strike_raw']) // one}.{int(got['strike_raw']) % one:0{dec}d}" per1 = (got.get("premium_per_1_share_in_stock") if leg == "call" else got.get("premium_per_1_share_in_usd")) per1_raw = ceil_div(one * got["premium_bps"], 10_000) if leg == "call" else ceil_div(int(got["strike_raw"]) * got["premium_bps"], 10_000) check(f"5 {t} {leg}: strike, premium, expiry recomputed", not diffs and got["strike"] == disp and per1 == f"{per1_raw // one}.{per1_raw % one:0{dec}d}", diffs or f"strike {got['strike']}, {got['premium_bps']} bps") fl = flt(s, int(got["strike_raw"]), int(got["priced_vol_wad"]) / WAD, got["tenor_seconds"]) check(f"5 {t} {leg}: float Black-Scholes within 0.01 bps", abs(fl - int(got["premium_fraction_wad"]) / WAD * 1e4) < 0.01, f"{fl:.4f} bps") msg = got["typed"]["message"] kind = 0 if leg == "call" else 1 want = {"feed": q["feed"], "kind": kind, "roundId": spot["round_id"], "spot": spot["price_raw"], "strike": got["strike_raw"], "premiumBps": got["premium_bps"], "saleWindow": sw, "expiry": got["expiry"], "validUntil": block_ts + pol["quote_ttl_seconds"]} sh = keccak(keccak(text=OPTION_QUOTE_TYPE) + bytes.fromhex(p32(q["feed"][2:])) + b"".join( v.to_bytes(32, "big") for v in (kind, int(msg["roundId"]), int(msg["spot"]), int(msg["strike"]), msg["premiumBps"], msg["saleWindow"], msg["expiry"], msg["validUntil"]))) check(f"6 {t} {leg}: typed message and struct hash", msg == want and got["sale_window_seconds"] == sw and got["valid_until"] == want["validUntil"] and "0x" + sh.hex() == got["typed"]["struct_hash"] and got["typed"]["leaf_index"] == len(leaves)) leaves.append(sh) legs.append(got) n_ok = sum(1 for q in p["quotes"] if q["status"] == "QUOTE_OK") check("5 quotes_ok and status match the rows", p["quotes_ok"] == n_ok and p["status"] == ("QUOTES_OK" if n_ok else "NO_QUOTES"), f"{n_ok} rows quoted") b = p["batch"] if not leaves: check("6 no quotes, no batch", b is None) return finish(results) def pair(x, y): return keccak(x + y if x <= y else y + x) level = leaves[:] while len(level) > 1: level = [pair(level[i], level[i + 1]) if i + 1 < len(level) else level[i] for i in range(0, len(level), 2)] root = level[0] proofs_ok = True for leaf, g in zip(leaves, legs): x = leaf for pr in g["typed"]["proof"]: x = pair(x, bytes.fromhex(pr[2:])) proofs_ok = proofs_ok and x == root check("6 Merkle root recomputed and every proof verifies", "0x" + root.hex() == b["message"]["root"] and b["message"]["count"] == len(leaves) and proofs_ok, f"{len(leaves)} leaves") typed = { "types": {"EIP712Domain": [{"name": "name", "type": "string"}, {"name": "version", "type": "string"}, {"name": "chainId", "type": "uint256"}], "QuoteBatch": [{"name": "root", "type": "bytes32"}, {"name": "count", "type": "uint64"}, {"name": "validUntil", "type": "uint64"}]}, "primaryType": "QuoteBatch", "domain": b["domain"], "message": {"root": bytes.fromhex(b["message"]["root"][2:]), "count": b["message"]["count"], "validUntil": b["message"]["validUntil"]}, } signable = encode_typed_data(full_message=typed) rec712 = Account.recover_message(signable, signature=b["signature"]) dg = "0x" + keccak(b"\x19\x01" + signable.header + signable.body).hex() check("6 EIP-712 QuoteBatch signature recovers to the trust root", rec712 == TRUST_ROOT and dg == b["digest"] and b["type"] == QUOTE_BATCH_TYPE and b["domain"] == {"name": "KerneStockQuote", "version": "2", "chainId": 8453} and b["leaf_type"] == OPTION_QUOTE_TYPE and b["message"]["validUntil"] == block_ts + pol["quote_ttl_seconds"], rec712) print(f"set age {int(time.time()) - block_ts}s") return finish(results) def float_vol(rounds, window_seconds): s = sum(math.log(b / a) ** 2 for (_, a, _), (_, b, _) in zip(rounds, rounds[1:])) return math.sqrt(s * YEAR / window_seconds) def float_premium(spot, strike, vol, tenor): sd = vol * math.sqrt(tenor / YEAR) d1 = (math.log(spot / strike) + sd * sd / 2) / sd n = lambda x: 0.5 * math.erfc(-x / math.sqrt(2)) # noqa: E731 return (n(d1) - strike / spot * n(d1 - sd)) * 1e4 def finish(results): ok = all(results) print("ALL OK" if ok else "FAILED") return 0 if ok else 1 if __name__ == "__main__": if "--multi" in sys.argv: args = [a for a in sys.argv[1:] if a != "--multi"] if len(args) > 1: # only for testing a local build signed by a throwaway key TRUST_ROOT = args[1] print("NOTE: trust root overridden on the command line:", TRUST_ROOT) sys.exit(main_multi(args[0] if args else MULTI_URL)) sys.exit(main())