Download tests/test_router.py from PYTHAI/drAIML: direct link, hf CLI and curl.
- Browser
- Download file 14.8 kB
-
https://huggingface.co/spaces/PYTHAI/drAIML/resolve/main/tests/test_router.py
- Command line
-
hf download hf://spaces/PYTHAI/drAIML/tests/test_router.py
-
curl -L -o test_router.py https://huggingface.co/spaces/PYTHAI/drAIML/resolve/main/tests/test_router.py
14.8 kB
| """drAIML.dmind router: delegation end to end with a simulated worker and client.""" | |
| import asyncio | |
| import hashlib | |
| import json | |
| import shutil | |
| import subprocess | |
| import sys | |
| from datetime import datetime, timezone | |
| from pathlib import Path | |
| sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "router")) | |
| import draiml_router as R # noqa: E402 | |
| async def http(port, method, path, body=None, origin="", token="", xff=""): | |
| r, w = await asyncio.open_connection("127.0.0.1", port) | |
| data = json.dumps(body).encode() if body is not None else b"" | |
| hdr = f"{method} {path} HTTP/1.1\r\nHost: x\r\nContent-Length: {len(data)}\r\n" | |
| if xff: | |
| hdr += f"X-Forwarded-For: {xff}\r\n" | |
| if origin: | |
| hdr += f"Origin: {origin}\r\n" | |
| if token: | |
| hdr += f"Authorization: Bearer {token}\r\n" | |
| w.write((hdr + "\r\n").encode() + data) | |
| await w.drain() | |
| raw = await r.read() | |
| w.close() | |
| head, _, payload = raw.partition(b"\r\n\r\n") | |
| lines = head.decode().split("\r\n") | |
| status = int(lines[0].split()[1]) | |
| headers = {k.lower(): v.strip() for k, v in (ln.split(":", 1) for ln in lines[1:])} | |
| return status, headers, (json.loads(payload) if payload and headers.get("content-type", "").startswith("application/json") else payload) | |
| import pytest # noqa: E402 | |
| CAST = shutil.which("cast") or str(Path.home() / ".foundry/bin/cast") | |
| def cast_sign(msg): | |
| key = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" # anvil's public test key 0 | |
| return subprocess.run([CAST, "wallet", "sign", "--private-key", key, msg], capture_output=True, text=True, | |
| check=True).stdout.strip() | |
| def receipt(text, sha=R.BONSAI_SHA256): | |
| return {"response_sha256": hashlib.sha256(text.encode()).hexdigest(), "model_sha256": sha, "bankml": "0.4.2"} | |
| async def scenario(tmp_path): | |
| router = R.Router(str(tmp_path / "ledger.jsonl")) | |
| server = await asyncio.start_server(lambda r, w: R.handle(router, r, w, True), "127.0.0.1", 0) | |
| WORKER = "6.6.6.6, 198.51.100.7" # Apache appends the real address; the first entry is the client's own claim | |
| port = server.sockets[0].getsockname()[1] | |
| out = {} | |
| # no worker: the client is told to come back | |
| s, h, j = await http(port, "POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]}) | |
| out["no_worker"] = (s, h.get("retry-after")) | |
| # login333 · drAIML: sign in with a wallet (anvil's public test key 0, signed by Foundry's cast) | |
| addr = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" | |
| _, _, n = await http(port, "GET", f"/auth/nonce?address={addr}") | |
| issued = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | |
| msg = (f"pythai-draiml.static.hf.space wants you to sign in with your Ethereum account:\n{addr}\n\n" | |
| f"Sign in to drAIML.dmind.\n\nURI: https://pythai-draiml.static.hf.space\nVersion: 1\nChain ID: 1\n" | |
| f"Nonce: {n['nonce']}\nIssued At: {issued}") | |
| sig = cast_sign(msg) | |
| _, _, bad = await http(port, "POST", "/auth/verify", {"message": msg.replace("Chain ID: 1", "Chain ID: 5"), "signature": sig}) | |
| out["wrong_chain"] = bad["ok"] | |
| _, _, v = await http(port, "POST", "/auth/verify", {"message": msg, "signature": sig}) | |
| out["signin"] = v.get("address") | |
| token = v["token"] | |
| _, _, replay = await http(port, "POST", "/auth/verify", {"message": msg, "signature": sig}) | |
| out["replay"] = replay["ok"] | |
| # a worker joins with the wrong model, then the pinned one | |
| s, _, j = await http(port, "POST", "/sharedcpu/join", {"model_sha256": "00" * 32}) | |
| out["wrong_model"] = j["ok"] | |
| s, h, j = await http(port, "POST", "/draiml-dmind/sharedcpu/join", | |
| {"model_sha256": R.BONSAI_SHA256, "share_pct": 10, | |
| "engine": "browseml/draiml", "contributor": "browser"}, | |
| origin="https://pythai-draiml.static.hf.space", token=token, xff=WORKER) | |
| out["join_wallet"] = j["wallet"] | |
| out["cors"] = h.get("access-control-allow-origin") | |
| _, h2, _ = await http(port, "GET", "/health", origin="http://127.0.0.1.evil.example") | |
| out["cors_spoof"] = h2.get("access-control-allow-origin") | |
| out["worker_ip"] = router.workers[j["session"]].ip | |
| session = j["session"] | |
| async def worker(bad=False): | |
| _, _, p = await http(port, "POST", "/sharedcpu/pull", {"session": session}, xff=WORKER) | |
| job = p["job"] | |
| text = "Rest, ice and gentle movement." | |
| rc = receipt("tampered" if bad else text) | |
| _, _, r = await http(port, "POST", "/sharedcpu/result", {"session": session, "job": job["job"], "text": text, | |
| "receipt": rc, "usage": {"completion_tokens": 7}}, xff=WORKER) | |
| return job, r | |
| async def client(): | |
| return await http(port, "POST", "/v1/chat/completions", | |
| {"messages": [{"role": "user", "content": "sprained ankle?"}], "max_tokens": 5000}, xff="203.0.113.5") | |
| # a bad receipt is refused and the job is re-queued; the second try succeeds | |
| c = asyncio.create_task(client()) | |
| await asyncio.sleep(0.1) | |
| job, r_bad = await worker(bad=True) | |
| out["bad_receipt"] = r_bad["ok"] | |
| out["max_tokens_capped"] = job["max_tokens"] | |
| job2, r_ok = await worker() | |
| out["same_job_retried"] = job2["job"] == job["job"] | |
| out["credited"] = r_ok["luv_wei"] | |
| s, _, comp = await c | |
| out["client"] = (s, comp["choices"][0]["message"]["content"], comp["bankml_receipt"]["model_sha256"] == R.BONSAI_SHA256) | |
| s, _, me = await http(port, "GET", "/sharedcpu/me", token=token) | |
| out["me"] = (me["tokens"], me["luv"], me["available_wei"]) | |
| _, _, c = await http(port, "POST", "/sharedcpu/claim", token=token) | |
| out["claim"] = (c["ok"], c["claim"]["luv_wei"], c["available_wei"], c["claimed_wei"]) | |
| _, _, c2 = await http(port, "POST", "/sharedcpu/claim", token=token) | |
| out["claim_again"] = c2["ok"] | |
| _, _, anon = await http(port, "POST", "/sharedcpu/claim") | |
| out["claim_anon"] = anon["ok"] | |
| s, _, ins = await http(port, "GET", "/insight/sharedcpu") | |
| out["insight"] = (ins["workers"], ins["stats"].get("jobs_done"), ins["stats"].get("receipts_bad")) | |
| await http(port, "POST", "/sharedcpu/leave", {"session": session}) | |
| s, _, ins = await http(port, "GET", "/insight/sharedcpu") | |
| out["after_leave"] = ins["workers"] | |
| server.close() | |
| return out | |
| def test_router_delegates_and_maintains(tmp_path): | |
| out = asyncio.run(scenario(tmp_path)) | |
| assert out["no_worker"] == (503, "30") | |
| assert out["wrong_model"] is False | |
| assert out["cors"] == "https://pythai-draiml.static.hf.space" | |
| assert out["bad_receipt"] is False and out["same_job_retried"] | |
| assert out["max_tokens_capped"] == R.MAX_TOKENS | |
| assert out["credited"] == str(7 * 10**18) | |
| assert out["client"] == (200, "Rest, ice and gentle movement.", True) | |
| assert out["wrong_chain"] is False and out["replay"] is False | |
| assert out["signin"] == "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" == out["join_wallet"] | |
| assert out["me"] == (7, "7.000000000000000000", str(7 * 10**18)) | |
| assert out["claim"] == (True, str(7 * 10**18), "0", str(7 * 10**18)) | |
| assert out["claim_again"] is False and out["claim_anon"] is False | |
| assert out["insight"] == (1, 1, 1) | |
| assert out["after_leave"] == 0 | |
| assert out["cors_spoof"] is None and out["worker_ip"] == "198.51.100.7" | |
| # ── abuse cases (the router's own methods, no HTTP) ────────────────────────────────────────────────────────────── | |
| def _router(tmp_path): | |
| return R.Router(str(tmp_path / "ledger.jsonl")) | |
| def _job(r, ip="203.0.113.5", max_tokens=600, temperature=0.3): | |
| j = R.Job("j" + str(len(r.jobs)), "Bonsai-1.7B-Q1_0", [{"role": "user", "content": "q"}], max_tokens, temperature) | |
| j.client_ip = ip | |
| r.jobs[j.id] = j | |
| r.queue.append(j) | |
| return j | |
| def _worker(r, ip, wallet=""): | |
| return r.join({"model_sha256": R.BONSAI_SHA256}, ip, wallet)["session"] | |
| def _answer(r, session, text, claimed): | |
| w = r.workers[session] | |
| j = r._take(w) | |
| return j, r.result({"session": session, "job": j.id, "text": text, "receipt": receipt(text), | |
| "usage": {"completion_tokens": claimed}}) | |
| def test_inflated_token_count_is_capped(tmp_path): | |
| r = _router(tmp_path) | |
| s = _worker(r, "198.51.100.7", "0xabc") | |
| _job(r, max_tokens=50) | |
| _, res = _answer(r, s, "x" * 30, 10**30) | |
| assert res["credited_tokens"] == 30 # bounded by the answer's length | |
| _job(r, max_tokens=50) | |
| _, res = _answer(r, s, "y" * 500, 10**30) | |
| assert res["credited_tokens"] == 50 # bounded by the job's limit | |
| assert r.me("0xabc")["tokens"] == 80 | |
| def test_self_served_answers_earn_nothing(tmp_path): | |
| r = _router(tmp_path) | |
| s = _worker(r, "198.51.100.7", "0xabc") | |
| _job(r, ip="198.51.100.7") | |
| _, res = _answer(r, s, "an answer", 9) | |
| assert res["credited_tokens"] == 0 and res["uncredited"] == "self-served" | |
| def test_daily_ceiling(tmp_path): | |
| r = _router(tmp_path) | |
| s = _worker(r, "198.51.100.7", "0xabc") | |
| r.daily[("0xabc", int(R.time.time()) // 86400)] = R.DAILY_TOKENS - 5 | |
| _job(r) | |
| _, res = _answer(r, s, "z" * 100, 100) | |
| assert res["credited_tokens"] == 5 and res["uncredited"] == "daily ceiling" | |
| def test_cross_check_tie_break_strikes_the_odd_one_out(tmp_path, monkeypatch): | |
| monkeypatch.setattr(R, "CROSS_CHECK", 0.0) # only the copy this test queues, no random extra checks | |
| r = _router(tmp_path) | |
| honest, liar, judge = (_worker(r, ip, wal) for ip, wal in | |
| (("10.0.0.1", "0xa1"), ("10.0.0.2", "0xb2"), ("10.0.0.3", "0xc3"))) | |
| j = _job(r, temperature=0) | |
| j_ = r._take(r.workers[honest]) | |
| r.result({"session": honest, "job": j_.id, "text": "rest", "receipt": receipt("rest"), "usage": {"completion_tokens": 4}}) | |
| c = R.Job("chk", j.model, j.messages, j.max_tokens, 0.0, check_of=j.id, compare={honest: "rest"}, | |
| who={honest: ("0xa1", "10.0.0.1", "")}) | |
| r.jobs[c.id] = c | |
| r.queue.append(c) | |
| assert r._take(r.workers[honest]) is None # never back to the original worker | |
| _, res = _answer(r, liar, "lies", 4) | |
| assert res["credited_tokens"] == 0 and "tie-break" in res["audit"] | |
| assert r._take(r.workers[liar]) is None # nor to the one it disagreed with | |
| _, res = _answer(r, judge, "rest", 4) | |
| assert res["credited_tokens"] == 4 | |
| assert r.strikes["w:0xb2"] == 1 and r.strikes["ip:10.0.0.2"] == 1 and r.strikes["w:0xa1"] == 0 | |
| r.strikes["w:0xb2"] = R.STRIKES_BAR # barred by wallet: a new session does not help | |
| again = _worker(r, "10.9.9.9", "0xb2") | |
| assert asyncio.run(r.pull({"session": again}))["barred"] is True | |
| def test_signin_limits(tmp_path): | |
| r = _router(tmp_path) | |
| addr = "0x" + "11" * 20 | |
| codes = [r.nonce(addr)["nonce"] for _ in range(10)] | |
| assert sum(1 for k in codes if k in r.nonces) == R.NONCES_PER_ADDRESS | |
| for i in range(R.MAX_NONCES + 50): | |
| r.nonce("0x" + f"{i:040x}") | |
| assert len(r.nonces) <= R.MAX_NONCES and r.nonce(addr)["ok"] # evicts instead of locking everyone out | |
| assert "too long" in r.verify({"message": "x" * 5000, "signature": "0x"})["reason"] | |
| async def _raw(port, data, read=True): | |
| rd, wr = await asyncio.open_connection("127.0.0.1", port) | |
| wr.write(data) | |
| await wr.drain() | |
| out = await asyncio.wait_for(rd.read(), 5) if read else b"" | |
| wr.close() | |
| return out | |
| def test_malformed_requests_do_not_crash(tmp_path): | |
| async def go(): | |
| r = _router(tmp_path) | |
| srv = await asyncio.start_server(lambda a, b: R.handle(r, a, b, True), "127.0.0.1", 0) | |
| port = srv.sockets[0].getsockname()[1] | |
| bad_len = await _raw(port, b"POST /x HTTP/1.1\r\nContent-Length: abc\r\n\r\n") | |
| bad_url = await _raw(port, b"GET http://[::1/x HTTP/1.1\r\n\r\n") | |
| not_obj = await _raw(port, b"POST /sharedcpu/join HTTP/1.1\r\nContent-Length: 2\r\n\r\n[]") | |
| ok = await _raw(port, b"GET /health HTTP/1.1\r\n\r\n") | |
| srv.close() | |
| return bad_len, bad_url, not_obj, ok | |
| bad_len, bad_url, not_obj, ok = asyncio.run(go()) | |
| assert bad_len.startswith(b"HTTP/1.1 400") and bad_url.startswith(b"HTTP/1.1 400") | |
| assert not_obj.startswith(b"HTTP/1.1 400") and ok.startswith(b"HTTP/1.1 200") | |
| def test_worker_sessions_are_capped_per_ip(tmp_path): | |
| r = _router(tmp_path) | |
| got = [r.join({"model_sha256": R.BONSAI_SHA256}, "10.0.0.9")["ok"] for _ in range(R.WORKERS_PER_IP + 3)] | |
| assert got.count(True) == R.WORKERS_PER_IP | |
| def test_payout_review_flags(tmp_path): | |
| import payout as P | |
| t = int(R.time.time()) | |
| led = [{"t": t, "wallet": "0xbad", "job": f"j{i}", "tokens": 3, "uncredited": "self-served" if i % 2 else None} for i in range(30)] | |
| led += [{"t": t - 86400 * d, "wallet": "0xgood", "job": f"g{d}", "tokens": 200, "check": d == 3} for d in range(5)] | |
| (tmp_path / "ledger.jsonl").write_text("\n".join(json.dumps({k: v for k, v in e.items() if v is not None}) for e in led) + "\n") | |
| (tmp_path / "strikes.jsonl").write_text(json.dumps({"t": t, "wallet": "0xbad", "why": "lost a cross-check tie-break"}) + "\n") | |
| out = {w: (s, flags) for w, s, flags in P.review(str(tmp_path), {"0xbad", "0xgood"})} | |
| bad = " ".join(out["0xbad"][1]) | |
| assert "strike" in bad and "short answers" in bad and "not or partly credited" in bad | |
| assert out["0xgood"][1] == [] and out["0xgood"][0]["days"] == 5 and out["0xgood"][0]["checks"] == 1 | |
| def test_signin_uri_and_expiry(tmp_path): | |
| r = R.Router(str(tmp_path / "ledger.jsonl")) | |
| addr = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" | |
| now_ = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") | |
| def msg(uri, extra=""): | |
| n = r.nonce(addr)["nonce"] | |
| return (f"pythai-draiml.static.hf.space wants you to sign in with your Ethereum account:\n{addr}\n\nSign in.\n\n" | |
| f"URI: {uri}\nVersion: 1\nChain ID: 1\nNonce: {n}\nIssued At: {now_}{extra}") | |
| m = msg("https://evil.example") | |
| assert r.verify({"message": m, "signature": cast_sign(m)})["ok"] is False | |
| m = msg("https://pythai-draiml.static.hf.space", "\nExpiration Time: 2020-01-01T00:00:00Z") | |
| assert "expired" in r.verify({"message": m, "signature": cast_sign(m)})["reason"] | |
| m = msg("https://pythai-draiml.static.hf.space") | |
| assert r.verify({"message": m, "signature": cast_sign(m)})["ok"] is True | |