donation panel: login333 · drAIML sign-in, confirmed CPU/RAM/GPU shares, live measurement, earnings and payout requests; router 0.2.0 (SIWE, claims, payout tool)
Browse filesFiles changed (13)
- README.md+2-1
- app/draiml/bonsai.py+7
- app/manifest.json+1-1
- app/views/consult.py+9-45
- bonsai.js+54-30
- dmind.js+48-13
- donate.jsAdded+213
- index.html+102
- router/README.md+15
- router/draiml_router.py+118-11
- router/payout.pyAdded+83
- router/siwe.pyAdded+138
- tests/test_router.py+51-6
54 unmodified lines5556575859606154 unmodified lines- **Bonsai in your browser.** Accept drAIML's Agreement once and prism-ml's Bonsai-1.7B (1-bit, Apache-2.0)is downloaded (248 MB, sha256-pinned) and run by the [browseML](https://github.com/browseML/browseML)WebAssembly engine on your own computer: free, private, no account, no key. Every answer carries a bankML receipt.- **Help save lives.** A toggle lends a share of your computer (10% by default) to drAIML.dmind, the distributed mind,through the same in-browser engine. Rewards: SHAMBA LUV, 1 wei per generated token, measured to 18 decimals(SCIEN·TIFIC) and valued in BANKON PAI (1 PAI = 1 USDC), SATPAY, BTC and GLDB. It waits while you ask, in a hiddentab and on battery.54 unmodified lines555657585960616254 unmodified lines- **Bonsai in your browser.** Accept drAIML's Agreement once and prism-ml's Bonsai-1.7B (1-bit, Apache-2.0)is downloaded (248 MB, sha256-pinned) and run by the [browseML](https://github.com/browseML/browseML)WebAssembly engine on your own computer: free, private, no account, no key. Every answer carries a bankML receipt.- **Help save lives.** The ❤️ Donate panel lets you sign in with login333 · drAIML (one signed message, no gas), choose andconfirm your CPU, RAM and GPU shares, and watch live measurements, earnings and payout requests. It lends a share of your computer (10% by default) to drAIML.dmind, the distributed mind,through the same in-browser engine. Rewards: SHAMBA LUV, 1 wei per generated token, measured to 18 decimals(SCIEN·TIFIC) and valued in BANKON PAI (1 PAI = 1 USDC), SATPAY, BTC and GLDB. It waits while you ask, in a hiddentab and on battery.
169 unmodified lines170171172173174175169 unmodified lines_queues.pop(rid, None)def request_signin() -> None:"""Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""if available():169 unmodified lines170171172173174175176177178179180181182169 unmodified lines_queues.pop(rid, None)def open_donate() -> None:"""Open the page's donation panel."""if available():_open()_post({"id": f"open-{next(_ids)}", "type": "open_donate"})def request_signin() -> None:"""Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""if available():
12345{"build": "0ef2748dad8d","requirements": [],"files": ["app.py",12345{"build": "d9f7947549d9","requirements": [],"files": ["app.py",
88 unmodified lines899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813988 unmodified linesif bonsai.available():st.subheader("❤️ Help save lives")ds = await bonsai.donate_status() # noqa: F704if ss.pop("don_reset", False): # the Agreement was declined: the toggle goes back offss.don_on = Falsess.setdefault("don_on", bool(ds.get("on")))ss.setdefault("don_pct", int(ds.get("pct") or 10))ss.setdefault("don_wallet", ds.get("wallet") or "")st.toggle(f"Donate compute to {ds.get('host', 'drAIML.dmind')}", key="don_on",help="Lend a share of this computer's CPU, RAM and GPU to drAIML's distributed mind. It runs ""only while this tab is open and visible, waits while you ask, and on a laptop waits for the ""charger. Needs Bonsai in this browser (the Agreement opens first).")st.slider("Share of this computer", 5, 50, step=5, key="don_pct", format="%d%%",help="10% means: after each job, rest nine times as long as it took.")st.text_input("LUV wallet for rewards (0x…)", key="don_wallet", placeholder="0x… (Ethereum)")wallet_ok = not ss.don_wallet or (ss.don_wallet.startswith("0x") and len(ss.don_wallet) == 42)if not wallet_ok:st.warning("That doesn't look like an Ethereum address (0x + 40 hex characters).")want = (ss.don_on, ss.don_pct, ss.don_wallet if wallet_ok else ds.get("wallet", ""))have = (bool(ds.get("on")), int(ds.get("pct") or 10), ds.get("wallet") or "")if want != have:with st.spinner("Updating your donation…"):try:ds = await bonsai.donate(*want) # noqa: F704except bonsai.BonsaiError as e:st.error(f"Donation unchanged: {e}")if ds.get("declined"):ss.don_reset = Truess.don_declined = Truest.rerun()if ss.pop("don_declined", False):st.info("Donating needs Bonsai in this browser: accept the Agreement to start.")if ds.get("on") or int(ds.get("jobs") or 0):if ds.get("note"):st.caption(f"{'🟢' if ds.get('state') == 'sharing' else '⏸️'} {ds['note']}")st.markdown(f"**{ds.get('luv', '0')} LUV** earned · {ds.get('jobs', 0)} jobs · "f"{ds.get('tokens', '0')} tokens · {ds.get('engine_s', 0)} s of thinking")w = ds.get("worth") or {}if "error" in w:st.caption(f"Prices unavailable: {w['error']}")elif w:with st.expander("What it is worth (SCIEN·TIFIC, 18 decimals)"):for unit, label in (("PAI", "BANKON PAI (1 = 1 USDC)"), ("SATPAY", "BANKON SATPAY (1 = 1 sat)"),("BTC", "BTC"), ("GLDB", "gld.basket GLDB")):st.markdown(f"`{w[unit]['exact']}` {label} · ≈ {w[unit]['sci']}")st.caption(f"1 LUV = {w['LUV_USD']['sci']} USD from Uniswap reserves at block {ds.get('block')}; ""BTC and gold from DeFiLlama. LUV paid: 1 wei per generated token. BANKON PAI, ""SATPAY and GLDB are not deployed: units of account only.")ss.second_on = st.toggle("Second opinion (compare two models)", ss.second_on and ss.engine != "bonsai",disabled=ss.engine == "bonsai",88 unmodified lines899091929394959697989910010110210388 unmodified linesif bonsai.available():st.subheader("❤️ Help save lives")ds = await bonsai.donate_status() # noqa: F704if ds.get("on"):st.caption(f"{'🟢' if ds.get('state') == 'sharing' else '⏸️'} {ds.get('note') or 'donating'} · "f"{ds.get('jobs', 0)} jobs · {ds.get('luv', '0')} LUV")else:st.caption("Lend part of this computer (CPU, RAM, GPU) to drAIML.dmind and earn SHAMBA LUV.")if st.button("❤️ Open the donation panel", use_container_width=True,help="Sign in with login333 · drAIML, choose and confirm your CPU / RAM / GPU share, ""watch the measurements and your earnings, and request payouts."):bonsai.open_donate()ss.second_on = st.toggle("Second opinion (compare two models)", ss.second_on and ss.engine != "bonsai",disabled=ss.engine == "bonsai",
61 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001014 unmodified lines1061071081091101111121138 unmodified lines12212312412512612712812913013113213313413513661 unmodified linesc.dataset.state = state;}// ── the bridge ────────────────────────────────────────────────────────────────────────────────────────────────────export function startBridge(pageId, { signin } = {}) {const ch = new BroadcastChannel(CHANNEL);const reply = (id, msg) => ch.postMessage({ ...msg, id, to: "py:" + pageId });let ensuring = null;// donate compute to drAIML.dmind: lends the engine Bonsai already loaded, so it starts after the Agreementconst donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,(text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });async function ensure(id) {const b = await mod();if (b.isReady()) return { model: b.MODEL.title };const cachedAlready = await b.isCached();if (!(agreed() && cachedAlready)) {if (!(await agreement(cachedAlready))) return null;} else {document.getElementById("bonsai-agreement").showModal();}const say = (text, frac) => { showProgress(text, frac); reply(id, { type: "progress", text, frac }); };say(cachedAlready ? "Opening Bonsai from this browser…" : "Downloading Bonsai…", 0);// half the cores (at most 4): Streamlit's own Python worker shares this tab, and all cores at once// crashed a 4-core, 6 GB laptop while the engine openedconst threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2)));const info = await b.load((got, total, phase) => {if (phase === "download") say(`Downloading Bonsai · ${mb(got)} of ${mb(total)} MB`, got / total);else if (phase === "retry") say(`Connection cut at ${mb(got)} MB · resuming…`, got / total);else if (phase === "cache") say("Bonsai found in this browser", 1);else if (phase === "verify") say("Checking the model against its sha256 pin and starting bankML…", null);}, () => {}, { threads });document.getElementById("bonsai-agreement").close();chip("Bonsai · ready in this browser", "ready");if (donor.ledger.on && !donor.running) donor.start(); // a donation pledged earlier resumes with the enginereturn { model: b.MODEL.title, sha256: info.sha256, threads: info.threads };}ch.onmessage = async (ev) => {const m = ev.data || {};4 unmodified linesconst b = await mod(); // importing the module is small: the engine and the model load only on ensurereply(id, { type: "status", agreed: agreed(), loaded: b.isReady(), loading: b.isLoading(), cached: await b.isCached() });} else if (type === "ensure") {ensuring ||= ensure(id).finally(() => { ensuring = null; });const info = await ensuring;reply(id, info ? { type: "ready", info } : { type: "declined" });} else if (type === "chat") {const b = await mod();8 unmodified linesconst speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : "";reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" });} else if (type === "donate") {if (m.on) {ensuring ||= ensure(id).finally(() => { ensuring = null; });if (!(await ensuring)) { reply(id, { type: "status", ...(await donor.status()), declined: true }); return; }}donor.settings({ on: m.on, pct: m.pct, wallet: m.wallet });await new Promise((r) => setTimeout(r, 300));reply(id, { type: "status", ...(await donor.status()) });} else if (type === "donate_status") {reply(id, { type: "status", ...(await donor.status()) });} else if (type === "signin") {if (signin) signin();} else if (type === "forget") {61 unmodified lines62636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251264 unmodified lines1311321331341351361378 unmodified lines14614714814915015115215315415515615715815916061 unmodified linesc.dataset.state = state;}// ── the engine, shared by the bridge (Python) and the donation panel ─────────────────────────────────────────────/** Donate compute to drAIML.dmind: lends the engine Bonsai already loaded (so it starts after the Agreement). */export const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,(text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });export { mod as engineModule };let ensuring = null;/** Load Bonsai, after the Agreement when this browser has not agreed or holds no copy. Resolves to what bankML* verified, or null when the visitor declines. One load at a time. */export function ensureEngine(onProgress = () => {}) {ensuring ||= ensureOnce(onProgress).finally(() => { ensuring = null; });return ensuring;}async function ensureOnce(onProgress) {const b = await mod();if (b.isReady()) return { model: b.MODEL.title, threads: b.loadStats && b.loadStats.threads };const cachedAlready = await b.isCached();if (!(agreed() && cachedAlready)) {if (!(await agreement(cachedAlready))) return null;} else {document.getElementById("bonsai-agreement").showModal();}const say = (text, frac) => { showProgress(text, frac); onProgress(text, frac); };say(cachedAlready ? "Opening Bonsai from this browser…" : "Downloading Bonsai…", 0);// half the cores (at most 4): Streamlit's own Python worker shares this tab, and all cores at once// crashed a 4-core, 6 GB laptop while the engine openedconst threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2)));const e = donor.engineOptions(); // the visitor's GPU choice (off unless they turned it on)try {const info = await b.load((got, total, phase) => {if (phase === "download") say(`Downloading Bonsai · ${mb(got)} of ${mb(total)} MB`, got / total);else if (phase === "retry") say(`Connection cut at ${mb(got)} MB · resuming…`, got / total);else if (phase === "cache") say("Bonsai found in this browser", 1);else if (phase === "verify") say("Checking the model against its sha256 pin and starting bankML…", null);}, () => {}, { threads, ...e });chip("Bonsai · ready in this browser", "ready");if (donor.ledger.on && !donor.running) donor.start(); // a donation pledged earlier resumes with the enginereturn { model: b.MODEL.title, sha256: info.sha256, threads: info.threads };} finally {document.getElementById("bonsai-agreement").close();}}/** Start the engine again with new options (the GPU share): waits for the answer being written, if any. */export async function reloadEngine(onProgress = () => {}) {const b = await mod();for (let i = 0; i < 600 && (b.isBusy() || visitorBusy); i++) await new Promise((r) => setTimeout(r, 500));const wasOn = donor.running;if (wasOn) donor.stop();if (b.isReady()) b.unload();const info = await ensureEngine(onProgress);if (info && wasOn) donor.settings({ on: true });return info;}// ── the bridge ────────────────────────────────────────────────────────────────────────────────────────────────────export function startBridge(pageId, { signin } = {}) {const ch = new BroadcastChannel(CHANNEL);const reply = (id, msg) => ch.postMessage({ ...msg, id, to: "py:" + pageId });const ensure = (id) => ensureEngine((text, frac) => reply(id, { type: "progress", text, frac }));ch.onmessage = async (ev) => {const m = ev.data || {};4 unmodified linesconst b = await mod(); // importing the module is small: the engine and the model load only on ensurereply(id, { type: "status", agreed: agreed(), loaded: b.isReady(), loading: b.isLoading(), cached: await b.isCached() });} else if (type === "ensure") {const info = await ensure(id);reply(id, info ? { type: "ready", info } : { type: "declined" });} else if (type === "chat") {const b = await mod();8 unmodified linesconst speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : "";reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" });} else if (type === "donate") {if (m.on && !(await ensure(id))) { reply(id, { type: "status", ...(await donor.status()), declined: true }); return; }donor.settings({ on: m.on, pct: m.pct, wallet: m.wallet });await new Promise((r) => setTimeout(r, 300));reply(id, { type: "status", ...(await donor.status()) });} else if (type === "donate_status") {reply(id, { type: "status", ...(await donor.status()) });} else if (type === "open_donate") {window.dispatchEvent(new CustomEvent("draiml:donate"));reply(id, { type: "done" });} else if (type === "signin") {if (signin) signin();} else if (type === "forget") {
30 unmodified lines31323334353637383950 unmodified lines909192939495961 unmodified line989910010110210310410510610710810911011111211322 unmodified lines1361371381391401411421431441451461 unmodified line1481491501511521538 unmodified lines16216316416516616712 unmodified lines1801811821831841852 unmodified lines18818919019119219319430 unmodified linesconst sci = (x18) => (x18 === 0n ? "0" : (Number(x18) / 1e18).toExponential(3));// ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────function readLedger() {try { const l = JSON.parse(localStorage.getItem(STORE) || "{}"); return { tokens: BigInt(l.tokens || 0), jobs: l.jobs || 0, engineMs: l.engineMs || 0, wallet: l.wallet || "", pct: l.pct || 10, on: !!l.on }; }catch { return { tokens: 0n, jobs: 0, engineMs: 0, wallet: "", pct: 10, on: false }; }}function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }50 unmodified linesthis.busy = isVisitorBusy; // () => boolean: the visitor's own question is runningthis.ledger = readLedger();this.host = null; this.session = ""; this.running = false; this.state = "off"; this.note = ""; this.wake = null;}async config() {if (this.host) return this.host;try { this.host = await (await fetch(new URL("./dmind-host.json", import.meta.url), { cache: "no-cache" })).json(); }1 unmodified linereturn this.host;}async call(path, body, keepalive = false) {const h = this.host, token = h.token_key ? (localStorage.getItem(h.token_key) || "") : "";const r = await fetch(h.url.replace(/\/$/, "") + path, { method: "POST", credentials: "omit", keepalive,headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(body) });if (r.status === 401 || r.status === 403) throw Object.assign(new Error("the host asks you to sign in to share"), { final: true });return r.json();}settings({ on, pct, wallet }) {if (pct) this.ledger.pct = Math.max(5, Math.min(50, Math.round(pct / 5) * 5));if (wallet !== undefined) this.ledger.wallet = /^0x[0-9a-fA-F]{40}$/.test(wallet) ? wallet : "";this.ledger.on = !!on; writeLedger(this.ledger);if (on && !this.running) this.start(); else if (!on && this.running) this.stop();if (this.session) this.call("/sharedcpu/update", { session: this.session, share_pct: this.ledger.pct }).catch(() => {});if (this.wake) this.wake();22 unmodified linesconst why = this.pauseReason();if (why) { if (this.state !== "paused") { this.state = "paused"; this.emit(); } this.note = why; if (this.session) await this.call("/sharedcpu/update", { session: this.session, paused: true }).catch(() => {}); await this.rest(5000); continue; }if (!this.session) {const j = await this.call("/sharedcpu/join", { model: b.MODEL.name, model_sha256: MODEL_SHA256, threads: 1,share_pct: this.ledger.pct, max_job_tokens: 256, engine: "browseml/draiml", contributor: "browser",...(this.ledger.wallet ? { wallet: this.ledger.wallet } : {}) });if (!j.ok) throw Object.assign(new Error(`the host refused: ${j.reason || "no reason given"}`), { final: !!j.barred });this.session = String(j.session);}if (this.state !== "sharing") { this.state = "sharing"; this.emit(); }this.note = `lending ${this.ledger.pct}% to ${h.label}`;1 unmodified lineif (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });if (!got.ok) { if (/session/.test(String(got.reason))) this.session = ""; await this.rest(got.retry_after_s ? got.retry_after_s * 1000 : 5000); continue; }const job = got.job; if (!job) continue;if (this.busy()) { await this.call("/sharedcpu/decline", { session: this.session, job: job.job, reason: "the visitor is asking" }).catch(() => {}); continue; }let cancelled = false;const beat = setInterval(() => { this.call("/sharedcpu/update", { session: this.session }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);8 unmodified linesif (r.ok) {const n = BigInt((res.usage && res.usage.completion_tokens) || 0);this.ledger.tokens += n * WEI_PER_TOKEN; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);this.emit();}backoff = 0;12 unmodified linesif (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }if (this.wake) this.wake();}async status() {const h = await this.config(), l = this.ledger;const luvWei = l.tokens; // 1 wei per token2 unmodified linesworth = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, { exact: format18(x), sci: sci(x) }]));worth.LUV_USD = { exact: format18(p.luvUsd18), sci: sci(p.luvUsd18) };} catch (e) { worth = { error: String(e.message || e) }; }return { on: l.on, pct: l.pct, wallet: l.wallet, host: h.label, open: !!h.url, state: this.state, note: this.note,jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),luv: format18(luvWei), luv_wei: luvWei.toString(), worth, block };}30 unmodified lines3132333435363738394041424344454647484950 unmodified lines1001011021031041051061071081091101 unmodified line11211311411511611711811912012112212312412512612712812913013122 unmodified lines1541551561571581591601611621631641651 unmodified line1671681691701711721738 unmodified lines18218318418518618718818919012 unmodified lines2032042052062072082092102112122132142152162172182192202 unmodified lines22322422522622722822930 unmodified linesconst sci = (x18) => (x18 === 0n ? "0" : (Number(x18) / 1e18).toExponential(3));// ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────const DEFAULTS = { tokens: 0n, jobs: 0, engineMs: 0, pct: 10, on: false, gpu: false, gpuPct: 25, jobTokens: 256 };function readLedger() {try {const l = JSON.parse(localStorage.getItem(STORE) || "{}");return { ...DEFAULTS, ...l, tokens: BigInt(l.tokens || 0), on: !!l.on, gpu: !!l.gpu };} catch { return { ...DEFAULTS }; }}// ── login333 · drAIML: the signed-in wallet (Sign-In with Ethereum, verified by the router) ────────────────────export const LOGIN_KEY = "draiml-login333";export function login() {try { const s = JSON.parse(localStorage.getItem(LOGIN_KEY) || "null"); return s && s.token && s.exp * 1000 > Date.now() ? s : null; }catch { return null; }}function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }50 unmodified linesthis.busy = isVisitorBusy; // () => boolean: the visitor's own question is runningthis.ledger = readLedger();this.host = null; this.session = ""; this.running = false; this.state = "off"; this.note = ""; this.wake = null;// measurement of this visit: when lending began, the engine's time on jobs, the last job's speedsthis.m = { since: 0, engineMs: 0, jobs: 0, tokens: 0, promptTps: 0, genTps: 0, lastJob: 0, lastMs: 0 };}/** The engine's load options from the visitor's GPU choice. */engineOptions() { return this.ledger.gpu ? { gpu: "low-power", gpuTime: this.ledger.gpuPct } : { gpu: "off" }; } // WebGPU power preferenceasync config() {if (this.host) return this.host;try { this.host = await (await fetch(new URL("./dmind-host.json", import.meta.url), { cache: "no-cache" })).json(); }1 unmodified linereturn this.host;}async call(path, body, keepalive = false) {const h = this.host, s = login(), token = s ? s.token : "";const r = await fetch(h.url.replace(/\/$/, "") + path, { method: body === undefined ? "GET" : "POST", credentials: "omit", keepalive,headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });if (r.status === 401 || r.status === 403) throw Object.assign(new Error("the host asks you to sign in to share"), { final: true });return r.json();}/** The visitor's confirmed share: on, CPU %, GPU on and its % of the card's time, the largest job (RAM). */settings({ on, pct, gpu, gpuPct, jobTokens }) {if (pct) this.ledger.pct = Math.max(5, Math.min(50, Math.round(pct / 5) * 5));if (gpu !== undefined) this.ledger.gpu = !!gpu;if (gpuPct) this.ledger.gpuPct = Math.max(25, Math.min(100, Math.round(gpuPct / 5) * 5));if (jobTokens) this.ledger.jobTokens = [128, 256, 512].includes(+jobTokens) ? +jobTokens : 256;if (on !== undefined) this.ledger.on = !!on;on = this.ledger.on; writeLedger(this.ledger);if (on && !this.running) this.start(); else if (!on && this.running) this.stop();if (this.session) this.call("/sharedcpu/update", { session: this.session, share_pct: this.ledger.pct }).catch(() => {});if (this.wake) this.wake();22 unmodified linesconst why = this.pauseReason();if (why) { if (this.state !== "paused") { this.state = "paused"; this.emit(); } this.note = why; if (this.session) await this.call("/sharedcpu/update", { session: this.session, paused: true }).catch(() => {}); await this.rest(5000); continue; }if (!this.session) {const j = await this.call("/sharedcpu/join", { model: b.MODEL.name, model_sha256: MODEL_SHA256,threads: (b.loadStats && b.loadStats.threads) || 1, share_pct: this.ledger.pct, max_job_tokens: this.ledger.jobTokens,engine: "browseml/draiml", contributor: "browser",...(b.gpuStatus ? { gpu: { name: String(b.gpuStatus.card || b.gpuStatus.name || "gpu"), share: this.ledger.gpuPct / 100 } } : {}) });if (!j.ok) throw Object.assign(new Error(`the host refused: ${j.reason || "no reason given"}`), { final: !!j.barred });this.session = String(j.session); this.wallet = j.wallet || ""; if (!this.m.since) this.m.since = Date.now();}if (this.state !== "sharing") { this.state = "sharing"; this.emit(); }this.note = `lending ${this.ledger.pct}% to ${h.label}`;1 unmodified lineif (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });if (!got.ok) { if (/session/.test(String(got.reason))) this.session = ""; await this.rest(got.retry_after_s ? got.retry_after_s * 1000 : 5000); continue; }const job = got.job; if (!job) continue;if (job.max_tokens > this.ledger.jobTokens) job.max_tokens = this.ledger.jobTokens; // the visitor's RAM limitif (this.busy()) { await this.call("/sharedcpu/decline", { session: this.session, job: job.job, reason: "the visitor is asking" }).catch(() => {}); continue; }let cancelled = false;const beat = setInterval(() => { this.call("/sharedcpu/update", { session: this.session }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);8 unmodified linesif (r.ok) {const n = BigInt((res.usage && res.usage.completion_tokens) || 0);this.ledger.tokens += n * WEI_PER_TOKEN; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);const t = res.timings || {};Object.assign(this.m, { engineMs: this.m.engineMs + ms, jobs: this.m.jobs + 1, tokens: this.m.tokens + Number(n),promptTps: t.prompt_per_second || 0, genTps: t.predicted_per_second || 0, lastJob: Date.now(), lastMs: ms });this.emit();}backoff = 0;12 unmodified linesif (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }if (this.wake) this.wake();}/** What this visit measured: the engine's threads and memory, the GPU, the duty cycle actually given. */async measure() {let b = null; try { b = await this.engine(); } catch {}const wall = this.m.since ? Date.now() - this.m.since : 0;return { threads: (b && b.loadStats && b.loadStats.threads) || 0, cores: navigator.hardwareConcurrency || 0,memoryMB: b ? Math.round(b.memoryBytes / 1048576) : 0, deviceMemoryGB: navigator.deviceMemory || null,gpu: b ? b.gpuStatus : null, gpuWanted: this.ledger.gpu, dutyPct: wall ? (100 * this.m.engineMs / wall) : 0,...this.m, wallMs: wall };}/** The router's account for the signed-in wallet: earned, claimed, paid, available. */async earnings() { await this.config(); if (!login()) return null; return this.call("/sharedcpu/me"); }async claim() { await this.config(); return this.call("/sharedcpu/claim", {}); }async status() {const h = await this.config(), l = this.ledger;const luvWei = l.tokens; // 1 wei per token2 unmodified linesworth = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, { exact: format18(x), sci: sci(x) }]));worth.LUV_USD = { exact: format18(p.luvUsd18), sci: sci(p.luvUsd18) };} catch (e) { worth = { error: String(e.message || e) }; }return { on: l.on, pct: l.pct, gpu: l.gpu, gpuPct: l.gpuPct, jobTokens: l.jobTokens, wallet: (login() || {}).address || "", host: h.label, open: !!h.url, state: this.state, note: this.note,jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),luv: format18(luvWei), luv_wei: luvWei.toString(), worth, block };}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213// SPDX-License-Identifier: MIT// drAIML · the donation panel: sign in with login333 · drAIML, choose the CPU, RAM and GPU shares, confirm them, then// watch what this computer gives (measured) and what it earns (SHAMBA LUV, 1 wei per generated token, valued in// BANKON units), and request a payout to the signed-in wallet. Everything here runs in the page; the router only// verifies the sign-in, keeps the ledger and records payout claims, which the drAIML operator pays.
import { donor, ensureEngine, reloadEngine } from "./bonsai.js";import { LOGIN_KEY, login, format18, prices, valuation } from "./dmind.js";
const $ = (sel) => document.querySelector(sel);const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "");const ETHERSCAN = "https://etherscan.io/tx/";let timer = null;
// ── login333 · drAIML ─────────────────────────────────────────────────────────────────────────────────────────────function siweMessage(address, nonce) { const domain = location.host, uri = location.origin, issued = new Date().toISOString().replace(/\.\d{3}Z$/, "Z"); return `${domain} wants you to sign in with your Ethereum account:\n${address}\n\n` + "Sign in to drAIML.dmind to receive SHAMBA LUV for the compute you donate. No transaction, no gas, nothing moves.\n\n" + `URI: ${uri}\nVersion: 1\nChain ID: 1\nNonce: ${nonce}\nIssued At: ${issued}`;}function step(k, state) { const li = document.querySelector(`#dn-seq [data-k="${k}"]`); if (li) li.dataset.state = state; }async function routerUrl() { return (await donor.config()).url.replace(/\/$/, ""); }
async function handshake(manual) { const say = (t) => { $("#dn-login-status").textContent = t; }; try { $("#dn-seq").hidden = false; let address; if (manual) { address = $("#dn-addr").value.trim(); if (!/^0x[0-9a-fA-F]{40}$/.test(address)) { say("Enter the wallet address (0x + 40 hex characters) first."); return; } } else { if (!window.ethereum) { say("No browser wallet found. Use “Sign elsewhere” below."); $("#dn-manual").open = true; return; } [address] = await window.ethereum.request({ method: "eth_requestAccounts" }); } step("wallet", "done"); const base = await routerUrl(); const n = await (await fetch(`${base}/auth/nonce?address=${address}`)).json(); if (!n.ok) throw new Error(n.reason); step("nonce", "done"); const message = siweMessage(address, n.nonce); let signature; if (manual) { $("#dn-msg").value = message; say("Sign this exact message with your wallet (for example `cast wallet sign`), paste the signature, then press Verify."); $("#dn-verify").hidden = false; $("#dn-verify").onclick = () => finish(base, message, $("#dn-sig").value.trim(), say); return; } signature = await window.ethereum.request({ method: "personal_sign", params: [message, address] }); await finish(base, message, signature, say); } catch (e) { say(`Sign-in stopped: ${(e && e.message) || e}`); }}async function finish(base, message, signature, say) { step("sign", "done"); const v = await (await fetch(`${base}/auth/verify`, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ message, signature }) })).json(); if (!v.ok) { say(`Not signed in: ${v.reason}`); return; } step("verify", "done"); const exp = Math.floor(Date.now() / 1000) + v.expires_days * 86400; try { localStorage.setItem(LOGIN_KEY, JSON.stringify({ address: v.address, token: v.token, exp })); } catch {} step("open", "done"); say(""); if (donor.running) { donor.stop(); donor.settings({ on: true }); } // rejoin, now paid to this wallet render();}function signOut() { try { localStorage.removeItem(LOGIN_KEY); } catch {} document.querySelectorAll("#dn-seq li").forEach((li) => { li.dataset.state = ""; }); $("#dn-seq").hidden = true; if (donor.running) { donor.stop(); donor.settings({ on: true }); } render();}
// ── the share and its confirmation ────────────────────────────────────────────────────────────────────────────────function wanted() { return { cpu: $("#dn-cpu-on").checked, pct: +$("#dn-cpu").value, ram: $("#dn-ram-on").checked, jobTokens: +$("#dn-ram").value, gpu: $("#dn-gpu-on").checked, gpuPct: +$("#dn-gpu").value };}function describe(w) { const threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2))); return [ ["CPU", w.cpu ? `${w.pct}% of its time on ${threads} of ${navigator.hardwareConcurrency || "?"} cores — after each job it rests ${((100 - w.pct) / w.pct).toFixed(0)}× as long` : "not shared"], ["RAM", w.ram ? `Bonsai stays loaded (about 320 MB) · jobs up to ${w.jobTokens} tokens` : "not shared"], ["GPU", w.gpu ? `up to ${w.gpuPct}% of the graphics card's time (WebGPU, low-power), when this browser has a verified card` : "off"], ["Rewards", login() ? `SHAMBA LUV to ${short(login().address)} · 1 wei per token your computer writes` : "not signed in — your work counts, but no wallet earns it"], ["Pauses", "while you ask a question, when this tab is hidden, and on battery"], ];}function refreshLabels() { const w = wanted(); $("#dn-cpu-val").textContent = `${w.pct}%`; $("#dn-gpu-val").textContent = `${w.gpuPct}%`; $("#dn-cpu").disabled = !w.cpu; $("#dn-ram").disabled = !w.ram; $("#dn-gpu").disabled = !w.gpu; const go = $("#dn-review"); go.disabled = !(w.cpu && w.ram); go.textContent = donor.ledger.on ? "Review and update" : "Review and start donating"; $("#dn-need").hidden = w.cpu && w.ram;}function review() { const w = wanted(), dlg = $("#dn-confirm"); $("#dn-confirm-list").replaceChildren(...describe(w).map(([k, v]) => { const li = document.createElement("li"); const b = document.createElement("b"); b.textContent = k + " "; li.append(b, v); return li; })); dlg.showModal(); $("#dn-confirm-yes").onclick = async () => { dlg.close(); const gpuChanged = w.gpu !== donor.ledger.gpu || (w.gpu && w.gpuPct !== donor.ledger.gpuPct); donor.settings({ pct: w.pct, gpu: w.gpu, gpuPct: w.gpuPct, jobTokens: w.jobTokens }); const say = (t) => { $("#dn-state").textContent = t; }; const mod = await import("./browseml/browseml.js"); let ok; if (gpuChanged && mod.isReady()) { say("Restarting Bonsai with the new GPU share…"); ok = await reloadEngine((t) => say(t)); } else ok = await ensureEngine((t) => say(t)); if (!ok) { say("Donating needs Bonsai in this browser: accept the Agreement to start."); return; } donor.settings({ on: true }); render(); }; $("#dn-confirm-no").onclick = () => dlg.close();}function stop() { donor.settings({ on: false }); render(); }
// ── measurement and earnings ──────────────────────────────────────────────────────────────────────────────────────function row(k, v) { const d = document.createElement("div"); const a = document.createElement("dt"); const b = document.createElement("dd"); a.textContent = k; b.textContent = v; d.append(a, b); return d; }async function render() { const s = login(); $("#dn-signed").hidden = !s; $("#dn-signin").hidden = !!s; if (s) $("#dn-who").textContent = s.address; $("#dn-stop").hidden = !donor.ledger.on; refreshLabels();
const st = await donor.status(), m = await donor.measure(); const label = { sharing: "🟢 Lending", paused: "⏸️ Paused", waiting: "⏳ Pledged", retrying: "🔄 Reconnecting", stopped: "⛔ Stopped", off: "Off" }[st.state] || st.state; $("#dn-state").textContent = st.on ? `${label}${st.note ? " · " + st.note : ""}` : "Not donating."; const gpu = m.gpu ? `${m.gpu.card || m.gpu.name || "card"} · share ${m.gpu.share ?? "?"}` : (m.gpuWanted ? "asked for, but no verified WebGPU card here" : "off"); $("#dn-measure").replaceChildren( row("Threads", m.threads ? `${m.threads} of ${m.cores} cores` : "engine not loaded"), row("Engine memory", m.memoryMB ? `${m.memoryMB} MB${m.deviceMemoryGB ? ` of ~${m.deviceMemoryGB} GB` : ""}` : "—"), row("GPU", gpu), row("CPU given", m.lastMs ? `last job ${(m.lastMs / 1000).toFixed(0)} s working, then ${(m.lastMs * (100 - st.pct) / st.pct / 1000).toFixed(0)} s resting = ${st.pct}% per cycle` + (m.wallMs > 300000 ? ` · ${m.dutyPct.toFixed(1)}% on average since you started` : " · the average settles over a few cycles") : "no job yet"), row("Jobs this visit", `${m.jobs} · ${m.tokens} tokens · ${(m.engineMs / 1000).toFixed(0)} s of thinking`), row("Last job speed", m.genTps ? `reads ${m.promptTps.toFixed(1)} · writes ${m.genTps.toFixed(1)} tokens/s` : "—"), );
// earnings: this browser's own count, the router's account, and their worth const local = BigInt(st.luv_wei || "0"); let acct = null; try { acct = await donor.earnings(); } catch {} const earned = acct ? BigInt(acct.luv_wei) : local; const rows = [row("Earned (this browser)", `${format18(local)} LUV`)]; if (acct) { rows.push(row("Earned (drAIML.dmind ledger)", `${format18(BigInt(acct.luv_wei))} LUV · ${acct.jobs} jobs`), row("Claimed · paid", `${format18(BigInt(acct.claimed_wei))} · ${format18(BigInt(acct.paid_wei))} LUV`), row("Available to claim", `${format18(BigInt(acct.available_wei))} LUV`)); } try { const p = await prices(), v = valuation(earned, p); // 18 decimals round tiny amounts to zero: the approximation beside each keeps every significant digit const usd = Number(earned) / 1e18 * Number(p.luvUsd18) / 1e18, btc = Number(p.btcUsd18) / 1e18, xau = Number(p.xauUsd18) / 1e18; const ap = (x) => (x ? x.toExponential(3) : "0"); rows.push(row("Worth (18 decimals)", `${format18(v.PAI)} PAI · ${format18(v.SATPAY)} SATPAY · ${format18(v.BTC)} BTC · ${format18(v.GLDB)} GLDB`), row("Worth (≈)", `${ap(usd)} PAI · ${btc ? ap(usd / btc * 1e8) : "?"} SATPAY · ${btc ? ap(usd / btc) : "?"} BTC · ${xau ? ap(usd / (xau * 0.000241833)) : "?"} GLDB`), row("Price used", `1 LUV = ${ap(Number(p.luvUsd18) / 1e18)} USD (Uniswap reserves, block ${p.block}) · 1 BTC = ${btc.toFixed(0)} USD`)); } catch { rows.push(row("Worth", "prices unavailable right now")); } $("#dn-earn").replaceChildren(...rows); const pay = $("#dn-payout"); pay.disabled = !(acct && BigInt(acct.available_wei) > 0n); pay.textContent = s ? `Request payout to ${short(s.address)}` : "Sign in to request a payout"; const list = $("#dn-claims"); list.replaceChildren(...((acct && acct.claims) || []).slice().reverse().map((c) => { const li = document.createElement("li"); li.textContent = `${new Date(c.t * 1000).toLocaleString()} · ${format18(BigInt(c.luv_wei))} LUV · ${c.status === "paid" ? "paid " : "requested — paid by the drAIML operator in batches"}`; if (c.tx) { const a = document.createElement("a"); a.href = ETHERSCAN + c.tx; a.target = "_blank"; a.rel = "noopener"; a.textContent = short(c.tx); li.append(a); } return li; }));}async function payout() { const s = login(); if (!s) return; $("#dn-payout").disabled = true; try { const r = await donor.claim(); $("#dn-pay-status").textContent = r.ok ? `Requested ${format18(BigInt(r.claim.luv_wei))} LUV to ${short(s.address)}.` : `Not requested: ${r.reason}`; } catch (e) { $("#dn-pay-status").textContent = `Not requested: ${e.message || e}`; } render();}
// ── the drawer ────────────────────────────────────────────────────────────────────────────────────────────────────export function open() { const d = $("#donate"); if (!d) return; const l = donor.ledger; $("#dn-cpu-on").checked = true; $("#dn-cpu").value = l.pct; $("#dn-ram-on").checked = true; $("#dn-ram").value = String(l.jobTokens); $("#dn-gpu-on").checked = l.gpu; $("#dn-gpu").value = l.gpuPct; d.showModal(); render(); clearInterval(timer); timer = setInterval(() => { if (d.open) render(); else clearInterval(timer); }, 5000);}export function init() { $("#donate-open").addEventListener("click", open); $("#dmind-chip").addEventListener("click", open); window.addEventListener("draiml:donate", open); $("#dn-close").onclick = () => $("#donate").close(); $("#dn-go").onclick = () => handshake(false); $("#dn-manual-go").onclick = () => handshake(true); $("#dn-signout").onclick = signOut; ["#dn-cpu-on", "#dn-cpu", "#dn-ram-on", "#dn-ram", "#dn-gpu-on", "#dn-gpu"].forEach((s) => $(s).addEventListener("input", refreshLabels)); $("#dn-review").onclick = review; $("#dn-stop").onclick = stop; $("#dn-payout").onclick = payout;}62 unmodified lines6364656667685 unmodified lines7475767778791 unmodified line81828384858630 unmodified lines11711811912012112212312412512662 unmodified lines.agree .prog b { display: block; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; margin-top: 6px; }.agree .prog i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .3s; }button.hf:disabled { opacity: .55; cursor: default; }</style></head><body>5 unmodified lines<span class="spacer"></span><span class="sos">Emergency? Call your local emergency number.</span><span class="chip" id="bonsai-chip" hidden role="status"></span><span class="chip" id="dmind-chip" hidden role="status" title="Your donation to drAIML.dmind: LUV at 1 wei per token you generated"></span><span class="who" id="who"></span><button class="hf primary" id="signin" hidden>Sign in with Hugging Face</button>1 unmodified line</header><div id="root"><div id="boot"><div><strong>Starting drAIML…</strong><br />Loading Python and Streamlit in your browser (first visit ≈ 20–40 s).<div class="bar"><i></i></div></div></div></div><dialog id="bonsai-agreement" aria-labelledby="agree-title"><div class="agree"><h2 id="agree-title">drAIML Agreement · Bonsai in this browser</h2>30 unmodified linesimport { mount } from "https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.js";import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";import { startBridge } from "./bonsai.js";// this tab's id: Python (in its Web Worker) and this page find each other by it over a BroadcastChannelconst PAGE_ID = (crypto.randomUUID && crypto.randomUUID()) || String(Math.random()).slice(2);startBridge(PAGE_ID, { signin: () => document.getElementById("signin").click() });const KEY = "draiml-oauth";const vars = (window.huggingface && window.huggingface.variables) || {};62 unmodified lines636465666768697071727374757677787980818283848586878889909192939495969798991001015 unmodified lines1071081091101111121131 unmodified line11511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518630 unmodified lines21721821922022122222322422522622722862 unmodified lines.agree .prog b { display: block; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; margin-top: 6px; }.agree .prog i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .3s; }button.hf:disabled { opacity: .55; cursor: default; }#dmind-chip { cursor: pointer; }button.heart { border-color: var(--warn); color: var(--warn); }dialog.panel { max-width: min(620px, calc(100vw - 32px)); width: 100%; border: 1px solid var(--line); border-radius: 14px;padding: 0; background: var(--surface); color: var(--ink); box-shadow: 0 20px 60px rgba(0,0,0,.25); }dialog.panel::backdrop { background: rgba(6, 20, 19, .55); }.dn { padding: 18px 22px 20px; max-height: calc(100vh - 64px); overflow-y: auto; box-sizing: border-box; }.dn header.top { display: flex; align-items: center; gap: 10px; padding: 0; border: 0; min-height: 0; background: none; }.dn h2 { margin: 0; font-size: 1.2rem; flex: 1; }.dn h3 { margin: 18px 0 6px; font-size: 0.82rem; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }.dn p, .dn li, .dn label, .dn dd, .dn dt { font-size: 0.93rem; line-height: 1.45; }.dn .lede { margin: 4px 0 0; color: var(--muted); }.dn .card { border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; margin-top: 6px; }.dn .brand333 { font-weight: 700; letter-spacing: .02em; }.dn .brand333 span { color: var(--accent); }.dn ol.seq { margin: 8px 0 0; padding-left: 20px; color: var(--muted); }.dn ol.seq li[data-state="done"] { color: var(--accent); }.dn ol.seq li[data-state="done"]::after { content: " ✓"; }.dn .row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: 8px; }.dn .share { display: grid; grid-template-columns: auto 1fr auto; gap: 8px 12px; align-items: center; }.dn .share input[type=range] { width: 100%; accent-color: var(--accent); }.dn .share select { font: inherit; padding: 3px 6px; border-radius: 6px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); }.dn .hint { color: var(--muted); font-size: 0.84rem; margin: 4px 0 0; }.dn dl { margin: 0; display: grid; gap: 4px; }.dn dl div { display: grid; grid-template-columns: 170px 1fr; gap: 10px; }.dn dt { color: var(--muted); }.dn dd { margin: 0; word-break: break-word; font-variant-numeric: tabular-nums; }.dn textarea, .dn input[type=text] { width: 100%; box-sizing: border-box; font: 0.85rem ui-monospace, monospace; padding: 6px;border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); }.dn details summary { cursor: pointer; color: var(--muted); font-size: 0.88rem; margin-top: 8px; }.dn .state { font-weight: 600; margin: 4px 0 0; }.dn ul.claims { margin: 6px 0 0; padding-left: 18px; color: var(--muted); }.dn ul.claims a { color: var(--accent); margin-left: 4px; }@media (max-width: 560px) { .dn dl div { grid-template-columns: 1fr; gap: 0; } }</style></head><body>5 unmodified lines<span class="spacer"></span><span class="sos">Emergency? Call your local emergency number.</span><span class="chip" id="bonsai-chip" hidden role="status"></span><button class="hf heart" id="donate-open" title="Donate compute to drAIML.dmind and earn SHAMBA LUV">❤️ Donate</button><span class="chip" id="dmind-chip" hidden role="status" title="Your donation to drAIML.dmind: LUV at 1 wei per token you generated"></span><span class="who" id="who"></span><button class="hf primary" id="signin" hidden>Sign in with Hugging Face</button>1 unmodified line</header><div id="root"><div id="boot"><div><strong>Starting drAIML…</strong><br />Loading Python and Streamlit in your browser (first visit ≈ 20–40 s).<div class="bar"><i></i></div></div></div></div><dialog id="donate" class="panel" aria-labelledby="dn-title"><div class="dn"><header class="top"><h2 id="dn-title">❤️ Help save lives · drAIML.dmind</h2><button class="hf" id="dn-close" aria-label="Close">✕</button></header><p class="lede">Lend part of this computer to drAIML's distributed mind: it answers other people's health questions withBonsai, in this browser, and you earn SHAMBA LUV for every token it writes.</p><h3>1 · Sign in</h3><div class="card" id="dn-signin"><div class="brand333">login333 · <span>drAIML</span></div><p class="hint">Sign one message with your wallet to prove the key is yours. No transaction, no gas, nothing moves.Your payouts go to this wallet.</p><div class="row"><button class="hf primary" id="dn-go">Begin the HANDSHAKE</button></div><ol class="seq" id="dn-seq" hidden><li data-k="wallet">Wallet connected</li><li data-k="nonce">One-time code issued</li><li data-k="sign">HANDSHAKE signed</li><li data-k="verify">Signature checked by drAIML.dmind</li><li data-k="open">Signed in</li></ol><details id="dn-manual"><summary>No browser wallet? Sign elsewhere and paste the signature</summary><p class="hint">Your wallet address:</p><input type="text" id="dn-addr" placeholder="0x…" autocomplete="off" /><div class="row"><button class="hf" id="dn-manual-go">Get the message to sign</button></div><textarea id="dn-msg" rows="7" readonly aria-label="Message to sign"></textarea><p class="hint">Signature (0x…):</p><input type="text" id="dn-sig" autocomplete="off" /><div class="row"><button class="hf primary" id="dn-verify" hidden>Verify</button></div></details><p class="hint" id="dn-login-status" role="status"></p></div><div class="card" id="dn-signed" hidden><div class="brand333">login333 · <span>drAIML</span> ✓</div><p class="hint">Signed in as <code id="dn-who"></code></p><div class="row"><button class="hf" id="dn-signout">Sign out</button></div></div><h3>2 · What to share</h3><div class="card share"><input type="checkbox" id="dn-cpu-on" checked aria-label="Share CPU" /><label for="dn-cpu">CPU <input type="range" id="dn-cpu" min="5" max="50" step="5" value="10" /></label><b id="dn-cpu-val">10%</b><input type="checkbox" id="dn-ram-on" checked aria-label="Share RAM" /><label for="dn-ram">RAM · largest job<select id="dn-ram"><option value="128">small (128 tokens)</option><option value="256" selected>medium (256 tokens)</option><option value="512">large (512 tokens)</option></select></label><span></span><input type="checkbox" id="dn-gpu-on" aria-label="Share GPU" /><label for="dn-gpu">GPU <input type="range" id="dn-gpu" min="25" max="100" step="5" value="25" /></label><b id="dn-gpu-val">25%</b></div><p class="hint" id="dn-need" hidden>CPU and RAM are both needed to donate: Bonsai runs on the processor and stays in memory.</p><div class="row"><button class="hf primary" id="dn-review">Review and start donating</button><button class="hf" id="dn-stop" hidden>Stop donating</button></div><p class="state" id="dn-state" role="status"></p><h3>3 · Measured</h3><div class="card"><dl id="dn-measure"></dl></div><h3>4 · Earnings and payout</h3><div class="card"><dl id="dn-earn"></dl><div class="row"><button class="hf primary" id="dn-payout" disabled>Request payout</button></div><p class="hint" id="dn-pay-status" role="status"></p><ul class="claims" id="dn-claims"></ul><p class="hint">1 wei of SHAMBA LUV (0x2711…8254, Ethereum) per generated token, counted to 18 decimals (SCIEN·TIFIC).Payouts are sent by the drAIML operator from the ledger in batches. BANKON PAI (1 = 1 USDC), SATPAY (1 sat) andGLDB are units of account only.</p></div></div></dialog><dialog id="dn-confirm" class="panel" aria-labelledby="dn-confirm-title"><div class="dn"><h2 id="dn-confirm-title">Confirm what this computer shares</h2><ul id="dn-confirm-list"></ul><p class="hint">You can change or stop this at any time from ❤️ Donate. Nothing runs when this tab is closed.</p><div class="row"><button class="hf" id="dn-confirm-no">Cancel</button><button class="hf primary" id="dn-confirm-yes">Confirm and donate</button></div></div></dialog><dialog id="bonsai-agreement" aria-labelledby="agree-title"><div class="agree"><h2 id="agree-title">drAIML Agreement · Bonsai in this browser</h2>30 unmodified linesimport { mount } from "https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.js";import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";import { startBridge } from "./bonsai.js";import { init as initDonate } from "./donate.js";// this tab's id: Python (in its Web Worker) and this page find each other by it over a BroadcastChannelconst PAGE_ID = (crypto.randomUUID && crypto.randomUUID()) || String(Math.random()).slice(2);startBridge(PAGE_ID, { signin: () => document.getElementById("signin").click() });initDonate();const KEY = "draiml-oauth";const vars = (window.huggingface && window.huggingface.variables) || {};
41 unmodified lines42434445464741 unmodified lines- Queue cap 64, request body 64 KB.- CORS only for drAIML's origins.## FootprintPython standard library only (asyncio), one process, about 14 MB of memory, idle between requests. It runs onthe busy one-core VPS as a sandboxed systemd service:41 unmodified lines42434445464748495051525354555657585960616241 unmodified lines- Queue cap 64, request body 64 KB.- CORS only for drAIML's origins.## login333 · drAIML sign-in, earnings and payouts- `GET /auth/nonce?address=0x…` issues a one-time code, valid for 5 minutes.- `POST /auth/verify {message, signature}` checks the Sign-In with Ethereum message (EIP-4361) and itspersonal_sign signature (EIP-191).- Recovery runs offline in `siwe.py`: keccak-256 and secp256k1, standard library only, about 30 ms of CPU.- The message must be for drAIML's domain and chain 1, and the code must be unused.- It returns a 7-day token.- A donor who joins with that token earns to that wallet; without one, its work is counted but no wallet earns it.- `GET /sharedcpu/me` (token) shows LUV earned, claimed, paid and available.- `POST /sharedcpu/claim` (token) records a payout claim for everything available.- `payout.py` is the operator's side. It holds no key and sends nothing: the operator pays from their own wallet.- `list` shows open claims.- `batch` writes a CSV (address, amount in wei).- `mark ID 0xTX` records a payment, which donors then see in the panel with its transaction link.## FootprintPython standard library only (asyncio), one process, about 14 MB of memory, idle between requests. It runs onthe busy one-core VPS as a sandboxed systemd service:
30 unmodified lines31323334353637383940414243444511 unmodified lines57585960616236 unmodified lines9910010110210310473 unmodified lines178179180181182183184185186187188189190191192193194195196197198139 unmodified lines33833934034134234312 unmodified lines35635735835936036136236342 unmodified lines40640740840941041141241341430 unmodified linesimport asyncioimport collectionsimport hashlibimport jsonimport osimport randomimport secretsimport timefrom dataclasses import dataclass, fieldfrom urllib.parse import parse_qs, urlsplitVERSION = "0.1.0"HOST_LABEL = "drAIML.dmind"BONSAI_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"MODELS = { # what workers may serve: name -> pinned sha256 and engine group (members must agree token for token)11 unmodified linesCROSS_CHECK = 0.05 # share of temperature-0 jobs also sent to a second workerRATE = (6, 60) # client requests per IP: 6 per 60 sWEI_PER_TOKEN = 1def now() -> float:36 unmodified linesclass Router:def __init__(self, ledger_path: str, keys_path: str | None = None):self.workers: dict[str, Worker] = {}self.queue: collections.deque[Job] = collections.deque()self.jobs: dict[str, Job] = {}73 unmodified linesself.jobs.pop(j.id, None)# ── worker API (dmind) ───────────────────────────────────────────────────────────────────────────────────────def join(self, b: dict, ip: str) -> dict:sha = str(b.get("model_sha256", "")).lower()model = next((m for m, v in MODELS.items() if v["sha256"] == sha), None)if not model:return {"ok": False, "reason": "this host serves only pinned models", "models": MODELS}wallet = str(b.get("wallet") or "")if wallet and not (wallet.startswith("0x") and len(wallet) == 42):wallet = ""s = secrets.token_hex(16)self.workers[s] = Worker(s, model, str(b.get("engine", ""))[:40], max(1, min(100, int(b.get("share_pct") or 10))),wallet, str(b.get("contributor", ""))[:20], ip)self.stats["joins"] += 1return {"ok": True, "session": s, "host": HOST_LABEL, "model": model, "engine_group": MODELS[model]["group"],"ttl_s": SESSION_TTL_S, "pull_wait_s": PULL_WAIT_S, "lease_s": LEASE_S,"trust": {"note": "receipts checked; occasional cross-checks between workers"}}def _worker(self, b: dict) -> Worker | None:w = self.workers.get(str(b.get("session", "")))139 unmodified lines"usage": u, "timings": r["timings"], "bankml_receipt": r["receipt"],"draiml_dmind": {"host": HOST_LABEL, "worker": r["worker"]}}def insight(self) -> dict:return {"host": HOST_LABEL, "version": VERSION, "up_s": int(time.time() - self.started),"workers": len(self.workers), "lending": sum(1 for w in self.workers.values() if not w.paused),12 unmodified linestokens += int(e.get("tokens", 0))jobs += 1wei = tokens * WEI_PER_TOKENreturn {"wallet": wallet, "jobs": jobs, "tokens": tokens, "luv_wei": str(wei),"luv": f"{wei // 10**18}.{wei % 10**18:018d}", "rule": "1 wei of SHAMBA LUV per generated token"}# ── a minimal HTTP/1.1 server (stdlib asyncio) ───────────────────────────────────────────────────────────────────42 unmodified lineselif method == "GET" and path in ("/v1/models", "/models"):out = {"object": "list", "data": [{"id": m, "object": "model", "owned_by": HOST_LABEL} for m in MODELS]}elif method == "GET" and path == "/sharedcpu/me":out = router.me(parse_qs(urlsplit(target).query).get("wallet", [""])[0])elif method == "POST" and path == "/sharedcpu/join":out = router.join(body, ip)elif method == "POST" and path == "/sharedcpu/update":out = router.update(body)elif method == "POST" and path == "/sharedcpu/pull":30 unmodified lines3132333435363738394041424344454647484911 unmodified lines616263646566676836 unmodified lines10510610710810911011111211311411511611711811973 unmodified lines193194195196197198199200201202203204205206207208209210139 unmodified lines35035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944012 unmodified lines45345445545645745845946046146246342 unmodified lines50650750850951051151251351451551651751851952052130 unmodified linesimport asyncioimport collectionsimport hashlibimport hmacimport jsonimport osimport randomimport secretsimport timefrom dataclasses import dataclass, fieldfrom datetime import datetime, timezonefrom urllib.parse import parse_qs, urlsplitimport siweVERSION = "0.2.0"HOST_LABEL = "drAIML.dmind"BONSAI_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"MODELS = { # what workers may serve: name -> pinned sha256 and engine group (members must agree token for token)11 unmodified linesCROSS_CHECK = 0.05 # share of temperature-0 jobs also sent to a second workerRATE = (6, 60) # client requests per IP: 6 per 60 sWEI_PER_TOKEN = 1SIWE_DOMAINS = ("pythai-draiml.static.hf.space", "127.0.0.1:8766", "localhost:8766")TOKEN_DAYS = 7def now() -> float:36 unmodified linesclass Router:def __init__(self, ledger_path: str, keys_path: str | None = None):state = os.path.dirname(os.path.abspath(ledger_path))self.claims_path = os.path.join(state, "claims.jsonl")secret = os.path.join(state, "secret.key")if not os.path.exists(secret):with open(os.open(secret, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as f:f.write(secrets.token_bytes(32))with open(secret, "rb") as f:self.secret = f.read()self.nonces: dict[str, tuple[str, float]] = {}self.workers: dict[str, Worker] = {}self.queue: collections.deque[Job] = collections.deque()self.jobs: dict[str, Job] = {}73 unmodified linesself.jobs.pop(j.id, None)# ── worker API (dmind) ───────────────────────────────────────────────────────────────────────────────────────def join(self, b: dict, ip: str, wallet: str = "") -> dict:sha = str(b.get("model_sha256", "")).lower()model = next((m for m, v in MODELS.items() if v["sha256"] == sha), None)if not model:return {"ok": False, "reason": "this host serves only pinned models", "models": MODELS}s = secrets.token_hex(16) # the wallet comes only from a login333 · drAIML sign-inself.workers[s] = Worker(s, model, str(b.get("engine", ""))[:40], max(1, min(100, int(b.get("share_pct") or 10))),wallet, str(b.get("contributor", ""))[:20], ip)self.stats["joins"] += 1return {"ok": True, "session": s, "host": HOST_LABEL, "model": model, "engine_group": MODELS[model]["group"],"ttl_s": SESSION_TTL_S, "pull_wait_s": PULL_WAIT_S, "lease_s": LEASE_S,"wallet": wallet, "trust": {"note": "receipts checked; occasional cross-checks between workers"}}def _worker(self, b: dict) -> Worker | None:w = self.workers.get(str(b.get("session", "")))139 unmodified lines"usage": u, "timings": r["timings"], "bankml_receipt": r["receipt"],"draiml_dmind": {"host": HOST_LABEL, "worker": r["worker"]}}# ── login333 · drAIML: Sign-In with Ethereum ────────────────────────────────────────────────────────────────def nonce(self, address: str) -> dict:if not (address.startswith("0x") and len(address) == 42):return {"ok": False, "reason": "an Ethereum address is required"}t = now()for k, (_, exp) in list(self.nonces.items()):if exp < t:self.nonces.pop(k, None)if len(self.nonces) > 2000:return {"ok": False, "reason": "too many sign-ins in progress; try again soon"}n = secrets.token_hex(8)self.nonces[n] = (address.lower(), t + 300)return {"ok": True, "nonce": n, "expires_s": 300, "domains": SIWE_DOMAINS, "chain_id": 1}def _token(self, address: str) -> str:exp = int(time.time()) + TOKEN_DAYS * 86400mac = hmac.new(self.secret, f"{address}|{exp}".encode(), "sha256").hexdigest()[:40]return f"{address}.{exp}.{mac}"def wallet_of(self, auth: str) -> str:"""The signed-in wallet a bearer token names, or "" if it is missing, forged or expired."""try:address, exp, mac = auth.removeprefix("Bearer ").strip().split(".")except ValueError:return ""good = hmac.new(self.secret, f"{address}|{exp}".encode(), "sha256").hexdigest()[:40]return address if hmac.compare_digest(good, mac) and int(exp) > time.time() else ""def verify(self, b: dict) -> dict:msg, sig = str(b.get("message", "")), str(b.get("signature", ""))try:f = siwe.parse_siwe(msg)except ValueError as e:return {"ok": False, "reason": str(e)}if f["domain"] not in SIWE_DOMAINS or f["chain"] != "1":return {"ok": False, "reason": "this sign-in is for another site or chain"}held = self.nonces.pop(f["nonce"], None)if not held or held[0] != f["address"].lower() or held[1] < now():return {"ok": False, "reason": "the one-time code is unknown or expired: sign in again"}try:issued = datetime.fromisoformat(f["issued"].replace("Z", "+00:00"))if abs((datetime.now(timezone.utc) - issued).total_seconds()) > 600:return {"ok": False, "reason": "the sign-in message is too old"}signer = siwe.personal_signer(msg, sig)except ValueError as e:return {"ok": False, "reason": f"the signature does not check: {e}"}if signer.lower() != f["address"].lower():return {"ok": False, "reason": "the signature is from another wallet"}self.stats["signins"] += 1return {"ok": True, "address": signer, "token": self._token(signer), "expires_days": TOKEN_DAYS}# ── earnings and payout claims ──────────────────────────────────────────────────────────────────────────────def _claims(self, wallet: str) -> tuple[int, int, list]:claimed = paid = 0rows: dict[str, dict] = {}if os.path.exists(self.claims_path):with open(self.claims_path) as f:for line in f:try:e = json.loads(line)except ValueError:continueif e.get("wallet", "").lower() != wallet.lower():continuerows.setdefault(e["id"], {}).update(e)for c in rows.values():claimed += int(c.get("luv_wei", 0))if c.get("status") == "paid":paid += int(c.get("luv_wei", 0))return claimed, paid, sorted(rows.values(), key=lambda c: c.get("t", 0))[-10:]def claim(self, wallet: str) -> dict:if not wallet:return {"ok": False, "reason": "sign in with login333 · drAIML first"}m = self.me(wallet)avail = int(m["available_wei"])if avail <= 0:return {"ok": False, "reason": "nothing to claim yet", **m}c = {"id": secrets.token_hex(6), "t": int(time.time()), "wallet": wallet, "luv_wei": str(avail),"token": "SHAMBA LUV 0x2711111111683b8708cb9a48cbf36a51315f8254", "status": "requested"}with open(self.claims_path, "a") as f:f.write(json.dumps(c, separators=(",", ":")) + "\n")self.stats["claims"] += 1return {"ok": True, "claim": c, **self.me(wallet)}def insight(self) -> dict:return {"host": HOST_LABEL, "version": VERSION, "up_s": int(time.time() - self.started),"workers": len(self.workers), "lending": sum(1 for w in self.workers.values() if not w.paused),12 unmodified linestokens += int(e.get("tokens", 0))jobs += 1wei = tokens * WEI_PER_TOKENclaimed, paid, claims = self._claims(wallet) if wallet else (0, 0, [])f18 = lambda x: f"{x // 10**18}.{x % 10**18:018d}" # noqa: E731return {"wallet": wallet, "jobs": jobs, "tokens": tokens, "luv_wei": str(wei), "luv": f18(wei),"claimed_wei": str(claimed), "paid_wei": str(paid), "available_wei": str(wei - claimed),"available": f18(wei - claimed), "claims": claims, "rule": "1 wei of SHAMBA LUV per generated token"}# ── a minimal HTTP/1.1 server (stdlib asyncio) ───────────────────────────────────────────────────────────────────42 unmodified lineselif method == "GET" and path in ("/v1/models", "/models"):out = {"object": "list", "data": [{"id": m, "object": "model", "owned_by": HOST_LABEL} for m in MODELS]}elif method == "GET" and path == "/sharedcpu/me":out = router.me(router.wallet_of(h.get("authorization", ""))or parse_qs(urlsplit(target).query).get("wallet", [""])[0])elif method == "GET" and path == "/auth/nonce":out = router.nonce(parse_qs(urlsplit(target).query).get("address", [""])[0])elif method == "POST" and path == "/auth/verify":out = router.verify(body)elif method == "POST" and path == "/sharedcpu/claim":out = router.claim(router.wallet_of(h.get("authorization", "")))elif method == "POST" and path == "/sharedcpu/join":out = router.join(body, ip, router.wallet_of(h.get("authorization", "")))elif method == "POST" and path == "/sharedcpu/update":out = router.update(body)elif method == "POST" and path == "/sharedcpu/pull":
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283#!/usr/bin/env python3# SPDX-License-Identifier: MIT"""drAIML.dmind payouts — the operator's side of a donor's claim.
Donors sign in with login333 · drAIML and press "Request payout"; the router appends a claim (wallet, LUV in wei)to claims.jsonl. This tool lists the open claims, writes them as a batch a wallet or multisend app can pay, andrecords each payment's transaction hash once the operator has made it. It holds no key and sends nothing: movingLUV is a step the operator takes in their own wallet.
payout.py list --state /var/lib/draiml-dmind payout.py batch --state /var/lib/draiml-dmind --out batch.csv # address,amount_wei (SHAMBA LUV, 18 decimals) payout.py mark --state /var/lib/draiml-dmind CLAIM_ID 0xTXHASH # after paying it"""from __future__ import annotations
import argparseimport csvimport jsonimport osimport reimport sysimport time
LUV = "0x2711111111683b8708cb9a48cbf36a51315f8254"
def claims(state: str) -> dict[str, dict]: rows: dict[str, dict] = {} path = os.path.join(state, "claims.jsonl") if os.path.exists(path): with open(path) as f: for line in f: try: e = json.loads(line) except ValueError: continue rows.setdefault(e["id"], {}).update(e) return rows
def f18(wei: int) -> str: return f"{wei // 10**18}.{wei % 10**18:018d}"
def main() -> int: ap = argparse.ArgumentParser(description=__doc__.split("\n")[0]) ap.add_argument("cmd", choices=["list", "batch", "mark"]) ap.add_argument("args", nargs="*") ap.add_argument("--state", default="/var/lib/draiml-dmind") ap.add_argument("--out", default="batch.csv") a = ap.parse_args() open_ = {k: c for k, c in claims(a.state).items() if c.get("status") == "requested"} if a.cmd == "list": total = 0 for c in sorted(open_.values(), key=lambda c: c["t"]): total += int(c["luv_wei"]) print(f"{c['id']} {time.strftime('%Y-%m-%d %H:%M', time.gmtime(c['t']))} {c['wallet']} {f18(int(c['luv_wei']))} LUV") print(f"{len(open_)} open claims · {f18(total)} LUV ({total} wei) · token {LUV}") elif a.cmd == "batch": by: dict[str, int] = {} for c in open_.values(): by[c["wallet"]] = by.get(c["wallet"], 0) + int(c["luv_wei"]) with open(a.out, "w", newline="") as f: w = csv.writer(f) w.writerow(["address", "amount_wei", "amount_luv", "claims"]) for addr, wei in sorted(by.items()): ids = " ".join(k for k, c in open_.items() if c["wallet"] == addr) w.writerow([addr, wei, f18(wei), ids]) print(f"wrote {a.out}: {len(by)} wallets, {f18(sum(by.values()))} LUV — pay it from your own wallet, " f"then `payout.py mark ID TX` for each claim") elif a.cmd == "mark": if len(a.args) != 2 or a.args[0] not in open_ or not re.fullmatch(r"0x[0-9a-fA-F]{64}", a.args[1]): print("usage: payout.py mark CLAIM_ID 0xTXHASH (an open claim id, a 32-byte transaction hash)", file=sys.stderr) return 2 with open(os.path.join(a.state, "claims.jsonl"), "a") as f: f.write(json.dumps({"id": a.args[0], "wallet": open_[a.args[0]]["wallet"], "status": "paid", "tx": a.args[1], "paid_t": int(time.time())}, separators=(",", ":")) + "\n") print(f"claim {a.args[0]} marked paid by {a.args[1]}") return 0
if __name__ == "__main__": raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138# SPDX-License-Identifier: MIT"""Sign-In with Ethereum for the drAIML.dmind router, standard library only.
keccak-256 (Ethereum's, not SHA3-256), secp256k1 public-key recovery, EIP-191 personal_sign, EIP-55 addresses andan EIP-4361 message parser — enough to learn which wallet signed a login, offline, with no dependencies. Recoverycosts a few tens of milliseconds of CPU, once per sign-in."""from __future__ import annotations
import re
# ── keccak-256 ───────────────────────────────────────────────────────────────────────────────────────────────────_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, 36, 3, 41, 18], [1, 44, 10, 45, 2], [62, 6, 43, 15, 61], [28, 55, 25, 21, 56], [27, 20, 39, 8, 14]]_M = (1 << 64) - 1
def _rol(x, n): return ((x << n) | (x >> (64 - n))) & _M if n else x
def _f(a): for rc in _RC: c = [a[x][0] ^ a[x][1] ^ a[x][2] ^ a[x][3] ^ a[x][4] for x in range(5)] d = [c[(x - 1) % 5] ^ _rol(c[(x + 1) % 5], 1) for x in range(5)] a = [[a[x][y] ^ d[x] for y in range(5)] for x in range(5)] b = [[0] * 5 for _ in range(5)] for x in range(5): for y in range(5): b[y][(2 * x + 3 * y) % 5] = _rol(a[x][y], _ROT[x][y]) a = [[b[x][y] ^ ((~b[(x + 1) % 5][y]) & b[(x + 2) % 5][y]) for y in range(5)] for x in range(5)] a[0][0] ^= rc return a
def keccak256(data: bytes) -> bytes: rate = 136 q = rate - len(data) % rate p = bytearray(data) + (b"\x81" if q == 1 else b"\x01" + b"\x00" * (q - 2) + b"\x80") a = [[0] * 5 for _ in range(5)] for off in range(0, len(p), rate): blk = p[off:off + rate] for i in range(rate // 8): x, y = i % 5, i // 5 a[x][y] ^= int.from_bytes(blk[8 * i:8 * i + 8], "little") a = _f(a) out = b"" for i in range(4): out += a[i % 5][i // 5].to_bytes(8, "little") return out
# ── secp256k1 recovery ───────────────────────────────────────────────────────────────────────────────────────────_P = 2**256 - 2**32 - 977_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798, 0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
def _add(p, q): if p is None: return q if q is None: return p if p[0] == q[0] and (p[1] + q[1]) % _P == 0: return None if p == q: lam = 3 * p[0] * p[0] * pow(2 * p[1], -1, _P) % _P else: lam = (q[1] - p[1]) * pow(q[0] - p[0], -1, _P) % _P x = (lam * lam - p[0] - q[0]) % _P return x, (lam * (p[0] - x) - p[1]) % _P
def _mul(k, p): r = None while k: if k & 1: r = _add(r, p) p = _add(p, p) k >>= 1 return r
def recover(msg_hash: bytes, sig: bytes) -> bytes: """The 64-byte public key (x‖y) that signed msg_hash, from a 65-byte r‖s‖v signature.""" if len(sig) != 65: raise ValueError("a signature is 65 bytes") r, s, v = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:64], "big"), sig[64] if v >= 27: v -= 27 if v not in (0, 1) or not (0 < r < _N and 0 < s < _N) or s > _N // 2: raise ValueError("not a valid signature") y2 = (pow(r, 3, _P) + 7) % _P y = pow(y2, (_P + 1) // 4, _P) if y * y % _P != y2: raise ValueError("r is not on the curve") if y % 2 != v: y = _P - y z = int.from_bytes(msg_hash, "big") rinv = pow(r, -1, _N) q = _add(_mul(s * rinv % _N, (r, y)), _mul((-z * rinv) % _N, _G)) if q is None: raise ValueError("no key") return q[0].to_bytes(32, "big") + q[1].to_bytes(32, "big")
def checksum(addr: str) -> str: a = addr.lower().removeprefix("0x") h = keccak256(a.encode()).hex() return "0x" + "".join(c.upper() if int(h[i], 16) >= 8 else c for i, c in enumerate(a))
def personal_signer(message: str, signature: str) -> str: """The EIP-55 address that signed `message` with personal_sign (EIP-191).""" m = message.encode() digest = keccak256(b"\x19Ethereum Signed Message:\n" + str(len(m)).encode() + m) pub = recover(digest, bytes.fromhex(signature.removeprefix("0x"))) return checksum("0x" + keccak256(pub)[-20:].hex())
# ── EIP-4361 ─────────────────────────────────────────────────────────────────────────────────────────────────────_SIWE = re.compile( r"^(?P<domain>[^\s]+) wants you to sign in with your Ethereum account:\n(?P<address>0x[0-9a-fA-F]{40})\n\n" r"(?:(?P<statement>[^\n]*)\n\n)?URI: (?P<uri>[^\n]+)\nVersion: (?P<version>1)\nChain ID: (?P<chain>\d+)\n" r"Nonce: (?P<nonce>[A-Za-z0-9]{8,})\nIssued At: (?P<issued>[^\n]+)(?:\nExpiration Time: (?P<expires>[^\n]+))?" r"(?:\n[^\n]*)*$")
def parse_siwe(message: str) -> dict: m = _SIWE.match(message) if not m: raise ValueError("not a Sign-In with Ethereum message") return m.groupdict()1 unmodified line2345678910111213141516171819205 unmodified lines2627282930318 unmodified lines40414243444546474849505122 unmodified lines74757677787980813 unmodified lines8586878889903 unmodified lines9495969798991 unmodified lineimport asyncioimport hashlibimport jsonimport sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "router"))import draiml_router as R # noqa: E402async def http(port, method, path, body=None, origin=""):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 origin:hdr += f"Origin: {origin}\r\n"w.write((hdr + "\r\n").encode() + data)await w.drain()raw = await r.read()5 unmodified linesreturn status, headers, (json.loads(payload) if payload and headers.get("content-type", "").startswith("application/json") else payload)def receipt(text, sha=R.BONSAI_SHA256):return {"response_sha256": hashlib.sha256(text.encode()).hexdigest(), "model_sha256": sha, "bankml": "0.4.2"}8 unmodified liness, h, j = await http(port, "POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]})out["no_worker"] = (s, h.get("retry-after"))# a worker joins with the wrong model, then the pinned ones, _, 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, "wallet": "0x" + "ab" * 20,"engine": "browseml/draiml", "contributor": "browser"}, origin="https://pythai-draiml.static.hf.space")out["cors"] = h.get("access-control-allow-origin")session = j["session"]22 unmodified liness, _, comp = await cout["client"] = (s, comp["choices"][0]["message"]["content"], comp["bankml_receipt"]["model_sha256"] == R.BONSAI_SHA256)s, _, me = await http(port, "GET", "/sharedcpu/me?wallet=0x" + "ab" * 20)out["me"] = (me["tokens"], me["luv"])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})3 unmodified linesreturn outdef test_router_delegates_and_maintains(tmp_path):out = asyncio.run(scenario(tmp_path))assert out["no_worker"] == (503, "30")3 unmodified linesassert out["max_tokens_capped"] == R.MAX_TOKENSassert out["credited"] == "7"assert out["client"] == (200, "Rest, ice and gentle movement.", True)assert out["me"] == (7, "0.000000000000000007")assert out["insight"] == (1, 1, 1)assert out["after_leave"] == 01 unmodified line23456789101112131415161718192021222324255 unmodified lines31323334353637383940414243444546478 unmodified lines56575859606162636465666768697071727374757677787980818283848522 unmodified lines1081091101111121131141151161171181191201213 unmodified lines1251261271281291301313 unmodified lines1351361371381391401411421431441 unmodified lineimport asyncioimport hashlibimport jsonimport shutilimport subprocessimport sysfrom datetime import datetime, timezonefrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "router"))import draiml_router as R # noqa: E402async def http(port, method, path, body=None, origin="", token=""):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 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()5 unmodified linesreturn status, headers, (json.loads(payload) if payload and headers.get("content-type", "").startswith("application/json") else payload)import pytest # noqa: E402CAST = shutil.which("cast") or str(Path.home() / ".foundry/bin/cast")def cast_sign(msg):key = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" # anvil's public test key 0return 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"}8 unmodified liness, 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 ones, _, 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)out["join_wallet"] = j["wallet"]out["cors"] = h.get("access-control-allow-origin")session = j["session"]22 unmodified liness, _, comp = await cout["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})3 unmodified linesreturn 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")3 unmodified linesassert out["max_tokens_capped"] == R.MAX_TOKENSassert out["credited"] == "7"assert out["client"] == (200, "Rest, ice and gentle movement.", True)assert out["wrong_chain"] is False and out["replay"] is Falseassert out["signin"] == "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" == out["join_wallet"]assert out["me"] == (7, "0.000000000000000007", "7")assert out["claim"] == (True, "7", "0", "7")assert out["claim_again"] is False and out["claim_anon"] is Falseassert out["insight"] == (1, 1, 1)assert out["after_leave"] == 0
README.md+2-1
app/draiml/bonsai.py+7
app/manifest.json+1-1
app/views/consult.py+9-45
bonsai.js+54-30
dmind.js+48-13
donate.jsAdded+213
index.html+102
router/README.md+15
router/draiml_router.py+118-11
router/payout.pyAdded+83
router/siwe.pyAdded+138
tests/test_router.py+51-6