File size: 14,806 Bytes
2c514f2
 
 
 
34f6aa9
 
2c514f2
34f6aa9
2c514f2
 
 
 
 
 
c2caad6
2c514f2
 
 
c2caad6
 
2c514f2
 
34f6aa9
 
2c514f2
 
 
 
 
 
 
 
 
 
 
34f6aa9
 
 
 
 
 
 
 
 
 
 
2c514f2
 
 
 
 
 
c2caad6
 
2c514f2
 
 
 
 
 
 
34f6aa9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2c514f2
 
 
 
34f6aa9
 
c2caad6
34f6aa9
2c514f2
c2caad6
 
 
2c514f2
 
 
c2caad6
2c514f2
 
 
 
c2caad6
2c514f2
 
 
 
c2caad6
2c514f2
 
 
 
 
 
 
 
 
 
 
 
 
34f6aa9
 
 
 
 
 
 
 
2c514f2
 
 
 
 
 
 
 
 
34f6aa9
2c514f2
 
 
 
 
 
 
c9248c9
2c514f2
34f6aa9
 
c9248c9
 
34f6aa9
2c514f2
 
c2caad6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1464612
 
c2caad6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1464612
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
"""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


@pytest.mark.skipif(not Path(CAST).exists(), reason="needs Foundry's cast to sign the test login")
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


@pytest.mark.skipif(not Path(CAST).exists(), reason="needs Foundry's cast to sign")
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