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 files- README.md +2 -1
- app/draiml/bonsai.py +7 -0
- app/manifest.json +1 -1
- app/views/consult.py +9 -45
- bonsai.js +54 -30
- dmind.js +48 -13
- donate.js +213 -0
- index.html +102 -0
- router/README.md +15 -0
- router/draiml_router.py +118 -11
- router/payout.py +83 -0
- router/siwe.py +138 -0
- tests/test_router.py +51 -6
README.md
CHANGED
|
@@ -55,7 +55,8 @@ your consultation is stored.
|
|
| 55 |
- **Bonsai in your browser.** Accept drAIML's Agreement once and prism-ml's Bonsai-1.7B (1-bit, Apache-2.0)
|
| 56 |
is downloaded (248 MB, sha256-pinned) and run by the [browseML](https://github.com/browseML/browseML)
|
| 57 |
WebAssembly engine on your own computer: free, private, no account, no key. Every answer carries a bankML receipt.
|
| 58 |
-
- **Help save lives.**
|
|
|
|
| 59 |
through the same in-browser engine. Rewards: SHAMBA LUV, 1 wei per generated token, measured to 18 decimals
|
| 60 |
(SCIEN·TIFIC) and valued in BANKON PAI (1 PAI = 1 USDC), SATPAY, BTC and GLDB. It waits while you ask, in a hidden
|
| 61 |
tab and on battery.
|
|
|
|
| 55 |
- **Bonsai in your browser.** Accept drAIML's Agreement once and prism-ml's Bonsai-1.7B (1-bit, Apache-2.0)
|
| 56 |
is downloaded (248 MB, sha256-pinned) and run by the [browseML](https://github.com/browseML/browseML)
|
| 57 |
WebAssembly engine on your own computer: free, private, no account, no key. Every answer carries a bankML receipt.
|
| 58 |
+
- **Help save lives.** The ❤️ Donate panel lets you sign in with login333 · drAIML (one signed message, no gas), choose and
|
| 59 |
+
confirm 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,
|
| 60 |
through the same in-browser engine. Rewards: SHAMBA LUV, 1 wei per generated token, measured to 18 decimals
|
| 61 |
(SCIEN·TIFIC) and valued in BANKON PAI (1 PAI = 1 USDC), SATPAY, BTC and GLDB. It waits while you ask, in a hidden
|
| 62 |
tab and on battery.
|
app/draiml/bonsai.py
CHANGED
|
@@ -170,6 +170,13 @@ async def donate_status() -> dict:
|
|
| 170 |
_queues.pop(rid, None)
|
| 171 |
|
| 172 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 173 |
def request_signin() -> None:
|
| 174 |
"""Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""
|
| 175 |
if available():
|
|
|
|
| 170 |
_queues.pop(rid, None)
|
| 171 |
|
| 172 |
|
| 173 |
+
def open_donate() -> None:
|
| 174 |
+
"""Open the page's donation panel."""
|
| 175 |
+
if available():
|
| 176 |
+
_open()
|
| 177 |
+
_post({"id": f"open-{next(_ids)}", "type": "open_donate"})
|
| 178 |
+
|
| 179 |
+
|
| 180 |
def request_signin() -> None:
|
| 181 |
"""Ask the page to start Sign in with Hugging Face (the page leaves for the OAuth screen)."""
|
| 182 |
if available():
|
app/manifest.json
CHANGED
|
@@ -1,5 +1,5 @@
|
|
| 1 |
{
|
| 2 |
-
"build": "
|
| 3 |
"requirements": [],
|
| 4 |
"files": [
|
| 5 |
"app.py",
|
|
|
|
| 1 |
{
|
| 2 |
+
"build": "d9f7947549d9",
|
| 3 |
"requirements": [],
|
| 4 |
"files": [
|
| 5 |
"app.py",
|
app/views/consult.py
CHANGED
|
@@ -89,51 +89,15 @@ with st.sidebar:
|
|
| 89 |
if bonsai.available():
|
| 90 |
st.subheader("❤️ Help save lives")
|
| 91 |
ds = await bonsai.donate_status() # noqa: F704
|
| 92 |
-
if
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
st.
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
st.slider("Share of this computer", 5, 50, step=5, key="don_pct", format="%d%%",
|
| 102 |
-
help="10% means: after each job, rest nine times as long as it took.")
|
| 103 |
-
st.text_input("LUV wallet for rewards (0x…)", key="don_wallet", placeholder="0x… (Ethereum)")
|
| 104 |
-
wallet_ok = not ss.don_wallet or (ss.don_wallet.startswith("0x") and len(ss.don_wallet) == 42)
|
| 105 |
-
if not wallet_ok:
|
| 106 |
-
st.warning("That doesn't look like an Ethereum address (0x + 40 hex characters).")
|
| 107 |
-
want = (ss.don_on, ss.don_pct, ss.don_wallet if wallet_ok else ds.get("wallet", ""))
|
| 108 |
-
have = (bool(ds.get("on")), int(ds.get("pct") or 10), ds.get("wallet") or "")
|
| 109 |
-
if want != have:
|
| 110 |
-
with st.spinner("Updating your donation…"):
|
| 111 |
-
try:
|
| 112 |
-
ds = await bonsai.donate(*want) # noqa: F704
|
| 113 |
-
except bonsai.BonsaiError as e:
|
| 114 |
-
st.error(f"Donation unchanged: {e}")
|
| 115 |
-
if ds.get("declined"):
|
| 116 |
-
ss.don_reset = True
|
| 117 |
-
ss.don_declined = True
|
| 118 |
-
st.rerun()
|
| 119 |
-
if ss.pop("don_declined", False):
|
| 120 |
-
st.info("Donating needs Bonsai in this browser: accept the Agreement to start.")
|
| 121 |
-
if ds.get("on") or int(ds.get("jobs") or 0):
|
| 122 |
-
if ds.get("note"):
|
| 123 |
-
st.caption(f"{'🟢' if ds.get('state') == 'sharing' else '⏸️'} {ds['note']}")
|
| 124 |
-
st.markdown(f"**{ds.get('luv', '0')} LUV** earned · {ds.get('jobs', 0)} jobs · "
|
| 125 |
-
f"{ds.get('tokens', '0')} tokens · {ds.get('engine_s', 0)} s of thinking")
|
| 126 |
-
w = ds.get("worth") or {}
|
| 127 |
-
if "error" in w:
|
| 128 |
-
st.caption(f"Prices unavailable: {w['error']}")
|
| 129 |
-
elif w:
|
| 130 |
-
with st.expander("What it is worth (SCIEN·TIFIC, 18 decimals)"):
|
| 131 |
-
for unit, label in (("PAI", "BANKON PAI (1 = 1 USDC)"), ("SATPAY", "BANKON SATPAY (1 = 1 sat)"),
|
| 132 |
-
("BTC", "BTC"), ("GLDB", "gld.basket GLDB")):
|
| 133 |
-
st.markdown(f"`{w[unit]['exact']}` {label} · ≈ {w[unit]['sci']}")
|
| 134 |
-
st.caption(f"1 LUV = {w['LUV_USD']['sci']} USD from Uniswap reserves at block {ds.get('block')}; "
|
| 135 |
-
"BTC and gold from DeFiLlama. LUV paid: 1 wei per generated token. BANKON PAI, "
|
| 136 |
-
"SATPAY and GLDB are not deployed: units of account only.")
|
| 137 |
|
| 138 |
ss.second_on = st.toggle("Second opinion (compare two models)", ss.second_on and ss.engine != "bonsai",
|
| 139 |
disabled=ss.engine == "bonsai",
|
|
|
|
| 89 |
if bonsai.available():
|
| 90 |
st.subheader("❤️ Help save lives")
|
| 91 |
ds = await bonsai.donate_status() # noqa: F704
|
| 92 |
+
if ds.get("on"):
|
| 93 |
+
st.caption(f"{'🟢' if ds.get('state') == 'sharing' else '⏸️'} {ds.get('note') or 'donating'} · "
|
| 94 |
+
f"{ds.get('jobs', 0)} jobs · {ds.get('luv', '0')} LUV")
|
| 95 |
+
else:
|
| 96 |
+
st.caption("Lend part of this computer (CPU, RAM, GPU) to drAIML.dmind and earn SHAMBA LUV.")
|
| 97 |
+
if st.button("❤️ Open the donation panel", use_container_width=True,
|
| 98 |
+
help="Sign in with login333 · drAIML, choose and confirm your CPU / RAM / GPU share, "
|
| 99 |
+
"watch the measurements and your earnings, and request payouts."):
|
| 100 |
+
bonsai.open_donate()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 101 |
|
| 102 |
ss.second_on = st.toggle("Second opinion (compare two models)", ss.second_on and ss.engine != "bonsai",
|
| 103 |
disabled=ss.engine == "bonsai",
|
bonsai.js
CHANGED
|
@@ -62,40 +62,65 @@ function chip(text, state = "busy") {
|
|
| 62 |
c.dataset.state = state;
|
| 63 |
}
|
| 64 |
|
| 65 |
-
// ── the bridge ─────────────────────────────────────────────
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
const
|
| 69 |
-
|
| 70 |
-
// donate compute to drAIML.dmind: lends the engine Bonsai already loaded, so it starts after the Agreement
|
| 71 |
-
const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,
|
| 72 |
-
(text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });
|
| 73 |
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
const info = await b.load((got, total, phase) => {
|
| 89 |
if (phase === "download") say(`Downloading Bonsai · ${mb(got)} of ${mb(total)} MB`, got / total);
|
| 90 |
else if (phase === "retry") say(`Connection cut at ${mb(got)} MB · resuming…`, got / total);
|
| 91 |
else if (phase === "cache") say("Bonsai found in this browser", 1);
|
| 92 |
else if (phase === "verify") say("Checking the model against its sha256 pin and starting bankML…", null);
|
| 93 |
-
}, () => {}, { threads });
|
| 94 |
-
document.getElementById("bonsai-agreement").close();
|
| 95 |
chip("Bonsai · ready in this browser", "ready");
|
| 96 |
if (donor.ledger.on && !donor.running) donor.start(); // a donation pledged earlier resumes with the engine
|
| 97 |
return { model: b.MODEL.title, sha256: info.sha256, threads: info.threads };
|
|
|
|
|
|
|
| 98 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 99 |
|
| 100 |
ch.onmessage = async (ev) => {
|
| 101 |
const m = ev.data || {};
|
|
@@ -106,8 +131,7 @@ export function startBridge(pageId, { signin } = {}) {
|
|
| 106 |
const b = await mod(); // importing the module is small: the engine and the model load only on ensure
|
| 107 |
reply(id, { type: "status", agreed: agreed(), loaded: b.isReady(), loading: b.isLoading(), cached: await b.isCached() });
|
| 108 |
} else if (type === "ensure") {
|
| 109 |
-
|
| 110 |
-
const info = await ensuring;
|
| 111 |
reply(id, info ? { type: "ready", info } : { type: "declined" });
|
| 112 |
} else if (type === "chat") {
|
| 113 |
const b = await mod();
|
|
@@ -122,15 +146,15 @@ export function startBridge(pageId, { signin } = {}) {
|
|
| 122 |
const speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : "";
|
| 123 |
reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" });
|
| 124 |
} else if (type === "donate") {
|
| 125 |
-
if (m.on) {
|
| 126 |
-
ensuring ||= ensure(id).finally(() => { ensuring = null; });
|
| 127 |
-
if (!(await ensuring)) { reply(id, { type: "status", ...(await donor.status()), declined: true }); return; }
|
| 128 |
-
}
|
| 129 |
donor.settings({ on: m.on, pct: m.pct, wallet: m.wallet });
|
| 130 |
await new Promise((r) => setTimeout(r, 300));
|
| 131 |
reply(id, { type: "status", ...(await donor.status()) });
|
| 132 |
} else if (type === "donate_status") {
|
| 133 |
reply(id, { type: "status", ...(await donor.status()) });
|
|
|
|
|
|
|
|
|
|
| 134 |
} else if (type === "signin") {
|
| 135 |
if (signin) signin();
|
| 136 |
} else if (type === "forget") {
|
|
|
|
| 62 |
c.dataset.state = state;
|
| 63 |
}
|
| 64 |
|
| 65 |
+
// ── the engine, shared by the bridge (Python) and the donation panel ─────────────────────────────────────────────
|
| 66 |
+
/** Donate compute to drAIML.dmind: lends the engine Bonsai already loaded (so it starts after the Agreement). */
|
| 67 |
+
export const donor = new Donor(async () => { const b = await mod(); if (!b.isReady()) throw new Error("Bonsai is not loaded"); return b; }, () => visitorBusy,
|
| 68 |
+
(text, state) => { const c = document.getElementById("dmind-chip"); if (!c) return; c.hidden = !text; c.textContent = text; c.dataset.state = state === "sharing" ? "ready" : "busy"; });
|
| 69 |
+
export { mod as engineModule };
|
|
|
|
|
|
|
|
|
|
| 70 |
|
| 71 |
+
let ensuring = null;
|
| 72 |
+
/** Load Bonsai, after the Agreement when this browser has not agreed or holds no copy. Resolves to what bankML
|
| 73 |
+
* verified, or null when the visitor declines. One load at a time. */
|
| 74 |
+
export function ensureEngine(onProgress = () => {}) {
|
| 75 |
+
ensuring ||= ensureOnce(onProgress).finally(() => { ensuring = null; });
|
| 76 |
+
return ensuring;
|
| 77 |
+
}
|
| 78 |
+
async function ensureOnce(onProgress) {
|
| 79 |
+
const b = await mod();
|
| 80 |
+
if (b.isReady()) return { model: b.MODEL.title, threads: b.loadStats && b.loadStats.threads };
|
| 81 |
+
const cachedAlready = await b.isCached();
|
| 82 |
+
if (!(agreed() && cachedAlready)) {
|
| 83 |
+
if (!(await agreement(cachedAlready))) return null;
|
| 84 |
+
} else {
|
| 85 |
+
document.getElementById("bonsai-agreement").showModal();
|
| 86 |
+
}
|
| 87 |
+
const say = (text, frac) => { showProgress(text, frac); onProgress(text, frac); };
|
| 88 |
+
say(cachedAlready ? "Opening Bonsai from this browser…" : "Downloading Bonsai…", 0);
|
| 89 |
+
// half the cores (at most 4): Streamlit's own Python worker shares this tab, and all cores at once
|
| 90 |
+
// crashed a 4-core, 6 GB laptop while the engine opened
|
| 91 |
+
const threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2)));
|
| 92 |
+
const e = donor.engineOptions(); // the visitor's GPU choice (off unless they turned it on)
|
| 93 |
+
try {
|
| 94 |
const info = await b.load((got, total, phase) => {
|
| 95 |
if (phase === "download") say(`Downloading Bonsai · ${mb(got)} of ${mb(total)} MB`, got / total);
|
| 96 |
else if (phase === "retry") say(`Connection cut at ${mb(got)} MB · resuming…`, got / total);
|
| 97 |
else if (phase === "cache") say("Bonsai found in this browser", 1);
|
| 98 |
else if (phase === "verify") say("Checking the model against its sha256 pin and starting bankML…", null);
|
| 99 |
+
}, () => {}, { threads, ...e });
|
|
|
|
| 100 |
chip("Bonsai · ready in this browser", "ready");
|
| 101 |
if (donor.ledger.on && !donor.running) donor.start(); // a donation pledged earlier resumes with the engine
|
| 102 |
return { model: b.MODEL.title, sha256: info.sha256, threads: info.threads };
|
| 103 |
+
} finally {
|
| 104 |
+
document.getElementById("bonsai-agreement").close();
|
| 105 |
}
|
| 106 |
+
}
|
| 107 |
+
/** Start the engine again with new options (the GPU share): waits for the answer being written, if any. */
|
| 108 |
+
export async function reloadEngine(onProgress = () => {}) {
|
| 109 |
+
const b = await mod();
|
| 110 |
+
for (let i = 0; i < 600 && (b.isBusy() || visitorBusy); i++) await new Promise((r) => setTimeout(r, 500));
|
| 111 |
+
const wasOn = donor.running;
|
| 112 |
+
if (wasOn) donor.stop();
|
| 113 |
+
if (b.isReady()) b.unload();
|
| 114 |
+
const info = await ensureEngine(onProgress);
|
| 115 |
+
if (info && wasOn) donor.settings({ on: true });
|
| 116 |
+
return info;
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
// ── the bridge ────────────────────────────────────────────────────────────────────────────────────────────────────
|
| 120 |
+
export function startBridge(pageId, { signin } = {}) {
|
| 121 |
+
const ch = new BroadcastChannel(CHANNEL);
|
| 122 |
+
const reply = (id, msg) => ch.postMessage({ ...msg, id, to: "py:" + pageId });
|
| 123 |
+
const ensure = (id) => ensureEngine((text, frac) => reply(id, { type: "progress", text, frac }));
|
| 124 |
|
| 125 |
ch.onmessage = async (ev) => {
|
| 126 |
const m = ev.data || {};
|
|
|
|
| 131 |
const b = await mod(); // importing the module is small: the engine and the model load only on ensure
|
| 132 |
reply(id, { type: "status", agreed: agreed(), loaded: b.isReady(), loading: b.isLoading(), cached: await b.isCached() });
|
| 133 |
} else if (type === "ensure") {
|
| 134 |
+
const info = await ensure(id);
|
|
|
|
| 135 |
reply(id, info ? { type: "ready", info } : { type: "declined" });
|
| 136 |
} else if (type === "chat") {
|
| 137 |
const b = await mod();
|
|
|
|
| 146 |
const speed = t.predicted_per_second ? ` · ${t.predicted_per_second.toFixed(1)} tok/s` : "";
|
| 147 |
reply(id, { type: "done", verdict: rc ? `${ok ? "✓" : "✗"} bankML receipt · answer sha256 ${ok ? "matches" : "does NOT match"}${speed}` : "no receipt" });
|
| 148 |
} else if (type === "donate") {
|
| 149 |
+
if (m.on && !(await ensure(id))) { reply(id, { type: "status", ...(await donor.status()), declined: true }); return; }
|
|
|
|
|
|
|
|
|
|
| 150 |
donor.settings({ on: m.on, pct: m.pct, wallet: m.wallet });
|
| 151 |
await new Promise((r) => setTimeout(r, 300));
|
| 152 |
reply(id, { type: "status", ...(await donor.status()) });
|
| 153 |
} else if (type === "donate_status") {
|
| 154 |
reply(id, { type: "status", ...(await donor.status()) });
|
| 155 |
+
} else if (type === "open_donate") {
|
| 156 |
+
window.dispatchEvent(new CustomEvent("draiml:donate"));
|
| 157 |
+
reply(id, { type: "done" });
|
| 158 |
} else if (type === "signin") {
|
| 159 |
if (signin) signin();
|
| 160 |
} else if (type === "forget") {
|
dmind.js
CHANGED
|
@@ -31,9 +31,19 @@ export function parse18(s) {
|
|
| 31 |
const sci = (x18) => (x18 === 0n ? "0" : (Number(x18) / 1e18).toExponential(3));
|
| 32 |
|
| 33 |
// ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────
|
|
|
|
| 34 |
function readLedger() {
|
| 35 |
-
try {
|
| 36 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 37 |
}
|
| 38 |
function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }
|
| 39 |
|
|
@@ -90,7 +100,11 @@ export class Donor {
|
|
| 90 |
this.busy = isVisitorBusy; // () => boolean: the visitor's own question is running
|
| 91 |
this.ledger = readLedger();
|
| 92 |
this.host = null; this.session = ""; this.running = false; this.state = "off"; this.note = ""; this.wake = null;
|
|
|
|
|
|
|
| 93 |
}
|
|
|
|
|
|
|
| 94 |
async config() {
|
| 95 |
if (this.host) return this.host;
|
| 96 |
try { this.host = await (await fetch(new URL("./dmind-host.json", import.meta.url), { cache: "no-cache" })).json(); }
|
|
@@ -98,16 +112,20 @@ export class Donor {
|
|
| 98 |
return this.host;
|
| 99 |
}
|
| 100 |
async call(path, body, keepalive = false) {
|
| 101 |
-
const h = this.host, token =
|
| 102 |
-
const r = await fetch(h.url.replace(/\/$/, "") + path, { method: "POST", credentials: "omit", keepalive,
|
| 103 |
-
headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: JSON.stringify(body) });
|
| 104 |
if (r.status === 401 || r.status === 403) throw Object.assign(new Error("the host asks you to sign in to share"), { final: true });
|
| 105 |
return r.json();
|
| 106 |
}
|
| 107 |
-
|
|
|
|
| 108 |
if (pct) this.ledger.pct = Math.max(5, Math.min(50, Math.round(pct / 5) * 5));
|
| 109 |
-
if (
|
| 110 |
-
this.ledger.
|
|
|
|
|
|
|
|
|
|
| 111 |
if (on && !this.running) this.start(); else if (!on && this.running) this.stop();
|
| 112 |
if (this.session) this.call("/sharedcpu/update", { session: this.session, share_pct: this.ledger.pct }).catch(() => {});
|
| 113 |
if (this.wake) this.wake();
|
|
@@ -136,11 +154,12 @@ export class Donor {
|
|
| 136 |
const why = this.pauseReason();
|
| 137 |
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; }
|
| 138 |
if (!this.session) {
|
| 139 |
-
const j = await this.call("/sharedcpu/join", { model: b.MODEL.name, model_sha256: MODEL_SHA256,
|
| 140 |
-
|
| 141 |
-
|
|
|
|
| 142 |
if (!j.ok) throw Object.assign(new Error(`the host refused: ${j.reason || "no reason given"}`), { final: !!j.barred });
|
| 143 |
-
this.session = String(j.session);
|
| 144 |
}
|
| 145 |
if (this.state !== "sharing") { this.state = "sharing"; this.emit(); }
|
| 146 |
this.note = `lending ${this.ledger.pct}% to ${h.label}`;
|
|
@@ -148,6 +167,7 @@ export class Donor {
|
|
| 148 |
if (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });
|
| 149 |
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; }
|
| 150 |
const job = got.job; if (!job) continue;
|
|
|
|
| 151 |
if (this.busy()) { await this.call("/sharedcpu/decline", { session: this.session, job: job.job, reason: "the visitor is asking" }).catch(() => {}); continue; }
|
| 152 |
let cancelled = false;
|
| 153 |
const beat = setInterval(() => { this.call("/sharedcpu/update", { session: this.session }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);
|
|
@@ -162,6 +182,9 @@ export class Donor {
|
|
| 162 |
if (r.ok) {
|
| 163 |
const n = BigInt((res.usage && res.usage.completion_tokens) || 0);
|
| 164 |
this.ledger.tokens += n * WEI_PER_TOKEN; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);
|
|
|
|
|
|
|
|
|
|
| 165 |
this.emit();
|
| 166 |
}
|
| 167 |
backoff = 0;
|
|
@@ -180,6 +203,18 @@ export class Donor {
|
|
| 180 |
if (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }
|
| 181 |
if (this.wake) this.wake();
|
| 182 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 183 |
async status() {
|
| 184 |
const h = await this.config(), l = this.ledger;
|
| 185 |
const luvWei = l.tokens; // 1 wei per token
|
|
@@ -188,7 +223,7 @@ export class Donor {
|
|
| 188 |
worth = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, { exact: format18(x), sci: sci(x) }]));
|
| 189 |
worth.LUV_USD = { exact: format18(p.luvUsd18), sci: sci(p.luvUsd18) };
|
| 190 |
} catch (e) { worth = { error: String(e.message || e) }; }
|
| 191 |
-
return { on: l.on, pct: l.pct,
|
| 192 |
jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),
|
| 193 |
luv: format18(luvWei), luv_wei: luvWei.toString(), worth, block };
|
| 194 |
}
|
|
|
|
| 31 |
const sci = (x18) => (x18 === 0n ? "0" : (Number(x18) / 1e18).toExponential(3));
|
| 32 |
|
| 33 |
// ── the ledger, kept in this browser ─────────────────────────────────────────────────────────────────────────────
|
| 34 |
+
const DEFAULTS = { tokens: 0n, jobs: 0, engineMs: 0, pct: 10, on: false, gpu: false, gpuPct: 25, jobTokens: 256 };
|
| 35 |
function readLedger() {
|
| 36 |
+
try {
|
| 37 |
+
const l = JSON.parse(localStorage.getItem(STORE) || "{}");
|
| 38 |
+
return { ...DEFAULTS, ...l, tokens: BigInt(l.tokens || 0), on: !!l.on, gpu: !!l.gpu };
|
| 39 |
+
} catch { return { ...DEFAULTS }; }
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
// ── login333 · drAIML: the signed-in wallet (Sign-In with Ethereum, verified by the router) ────────────────────
|
| 43 |
+
export const LOGIN_KEY = "draiml-login333";
|
| 44 |
+
export function login() {
|
| 45 |
+
try { const s = JSON.parse(localStorage.getItem(LOGIN_KEY) || "null"); return s && s.token && s.exp * 1000 > Date.now() ? s : null; }
|
| 46 |
+
catch { return null; }
|
| 47 |
}
|
| 48 |
function writeLedger(l) { try { localStorage.setItem(STORE, JSON.stringify({ ...l, tokens: l.tokens.toString() })); } catch {} }
|
| 49 |
|
|
|
|
| 100 |
this.busy = isVisitorBusy; // () => boolean: the visitor's own question is running
|
| 101 |
this.ledger = readLedger();
|
| 102 |
this.host = null; this.session = ""; this.running = false; this.state = "off"; this.note = ""; this.wake = null;
|
| 103 |
+
// measurement of this visit: when lending began, the engine's time on jobs, the last job's speeds
|
| 104 |
+
this.m = { since: 0, engineMs: 0, jobs: 0, tokens: 0, promptTps: 0, genTps: 0, lastJob: 0, lastMs: 0 };
|
| 105 |
}
|
| 106 |
+
/** The engine's load options from the visitor's GPU choice. */
|
| 107 |
+
engineOptions() { return this.ledger.gpu ? { gpu: "low-power", gpuTime: this.ledger.gpuPct } : { gpu: "off" }; } // WebGPU power preference
|
| 108 |
async config() {
|
| 109 |
if (this.host) return this.host;
|
| 110 |
try { this.host = await (await fetch(new URL("./dmind-host.json", import.meta.url), { cache: "no-cache" })).json(); }
|
|
|
|
| 112 |
return this.host;
|
| 113 |
}
|
| 114 |
async call(path, body, keepalive = false) {
|
| 115 |
+
const h = this.host, s = login(), token = s ? s.token : "";
|
| 116 |
+
const r = await fetch(h.url.replace(/\/$/, "") + path, { method: body === undefined ? "GET" : "POST", credentials: "omit", keepalive,
|
| 117 |
+
headers: { "content-type": "application/json", ...(token ? { authorization: `Bearer ${token}` } : {}) }, body: body === undefined ? undefined : JSON.stringify(body) });
|
| 118 |
if (r.status === 401 || r.status === 403) throw Object.assign(new Error("the host asks you to sign in to share"), { final: true });
|
| 119 |
return r.json();
|
| 120 |
}
|
| 121 |
+
/** The visitor's confirmed share: on, CPU %, GPU on and its % of the card's time, the largest job (RAM). */
|
| 122 |
+
settings({ on, pct, gpu, gpuPct, jobTokens }) {
|
| 123 |
if (pct) this.ledger.pct = Math.max(5, Math.min(50, Math.round(pct / 5) * 5));
|
| 124 |
+
if (gpu !== undefined) this.ledger.gpu = !!gpu;
|
| 125 |
+
if (gpuPct) this.ledger.gpuPct = Math.max(25, Math.min(100, Math.round(gpuPct / 5) * 5));
|
| 126 |
+
if (jobTokens) this.ledger.jobTokens = [128, 256, 512].includes(+jobTokens) ? +jobTokens : 256;
|
| 127 |
+
if (on !== undefined) this.ledger.on = !!on;
|
| 128 |
+
on = this.ledger.on; writeLedger(this.ledger);
|
| 129 |
if (on && !this.running) this.start(); else if (!on && this.running) this.stop();
|
| 130 |
if (this.session) this.call("/sharedcpu/update", { session: this.session, share_pct: this.ledger.pct }).catch(() => {});
|
| 131 |
if (this.wake) this.wake();
|
|
|
|
| 154 |
const why = this.pauseReason();
|
| 155 |
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; }
|
| 156 |
if (!this.session) {
|
| 157 |
+
const j = await this.call("/sharedcpu/join", { model: b.MODEL.name, model_sha256: MODEL_SHA256,
|
| 158 |
+
threads: (b.loadStats && b.loadStats.threads) || 1, share_pct: this.ledger.pct, max_job_tokens: this.ledger.jobTokens,
|
| 159 |
+
engine: "browseml/draiml", contributor: "browser",
|
| 160 |
+
...(b.gpuStatus ? { gpu: { name: String(b.gpuStatus.card || b.gpuStatus.name || "gpu"), share: this.ledger.gpuPct / 100 } } : {}) });
|
| 161 |
if (!j.ok) throw Object.assign(new Error(`the host refused: ${j.reason || "no reason given"}`), { final: !!j.barred });
|
| 162 |
+
this.session = String(j.session); this.wallet = j.wallet || ""; if (!this.m.since) this.m.since = Date.now();
|
| 163 |
}
|
| 164 |
if (this.state !== "sharing") { this.state = "sharing"; this.emit(); }
|
| 165 |
this.note = `lending ${this.ledger.pct}% to ${h.label}`;
|
|
|
|
| 167 |
if (got.barred || got.final) throw Object.assign(new Error(got.reason || "stopped by the host"), { final: true });
|
| 168 |
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; }
|
| 169 |
const job = got.job; if (!job) continue;
|
| 170 |
+
if (job.max_tokens > this.ledger.jobTokens) job.max_tokens = this.ledger.jobTokens; // the visitor's RAM limit
|
| 171 |
if (this.busy()) { await this.call("/sharedcpu/decline", { session: this.session, job: job.job, reason: "the visitor is asking" }).catch(() => {}); continue; }
|
| 172 |
let cancelled = false;
|
| 173 |
const beat = setInterval(() => { this.call("/sharedcpu/update", { session: this.session }).then((u) => { if (u.cancelled === job.job) cancelled = true; }).catch(() => {}); }, 30000);
|
|
|
|
| 182 |
if (r.ok) {
|
| 183 |
const n = BigInt((res.usage && res.usage.completion_tokens) || 0);
|
| 184 |
this.ledger.tokens += n * WEI_PER_TOKEN; this.ledger.jobs++; this.ledger.engineMs += Math.round(ms); writeLedger(this.ledger);
|
| 185 |
+
const t = res.timings || {};
|
| 186 |
+
Object.assign(this.m, { engineMs: this.m.engineMs + ms, jobs: this.m.jobs + 1, tokens: this.m.tokens + Number(n),
|
| 187 |
+
promptTps: t.prompt_per_second || 0, genTps: t.predicted_per_second || 0, lastJob: Date.now(), lastMs: ms });
|
| 188 |
this.emit();
|
| 189 |
}
|
| 190 |
backoff = 0;
|
|
|
|
| 203 |
if (this.session) { this.call("/sharedcpu/leave", { session: this.session }, true).catch(() => {}); this.session = ""; }
|
| 204 |
if (this.wake) this.wake();
|
| 205 |
}
|
| 206 |
+
/** What this visit measured: the engine's threads and memory, the GPU, the duty cycle actually given. */
|
| 207 |
+
async measure() {
|
| 208 |
+
let b = null; try { b = await this.engine(); } catch {}
|
| 209 |
+
const wall = this.m.since ? Date.now() - this.m.since : 0;
|
| 210 |
+
return { threads: (b && b.loadStats && b.loadStats.threads) || 0, cores: navigator.hardwareConcurrency || 0,
|
| 211 |
+
memoryMB: b ? Math.round(b.memoryBytes / 1048576) : 0, deviceMemoryGB: navigator.deviceMemory || null,
|
| 212 |
+
gpu: b ? b.gpuStatus : null, gpuWanted: this.ledger.gpu, dutyPct: wall ? (100 * this.m.engineMs / wall) : 0,
|
| 213 |
+
...this.m, wallMs: wall };
|
| 214 |
+
}
|
| 215 |
+
/** The router's account for the signed-in wallet: earned, claimed, paid, available. */
|
| 216 |
+
async earnings() { await this.config(); if (!login()) return null; return this.call("/sharedcpu/me"); }
|
| 217 |
+
async claim() { await this.config(); return this.call("/sharedcpu/claim", {}); }
|
| 218 |
async status() {
|
| 219 |
const h = await this.config(), l = this.ledger;
|
| 220 |
const luvWei = l.tokens; // 1 wei per token
|
|
|
|
| 223 |
worth = Object.fromEntries(Object.entries(v).map(([k, x]) => [k, { exact: format18(x), sci: sci(x) }]));
|
| 224 |
worth.LUV_USD = { exact: format18(p.luvUsd18), sci: sci(p.luvUsd18) };
|
| 225 |
} catch (e) { worth = { error: String(e.message || e) }; }
|
| 226 |
+
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,
|
| 227 |
jobs: l.jobs, tokens: l.tokens.toString(), engine_s: Math.round(l.engineMs / 1000),
|
| 228 |
luv: format18(luvWei), luv_wei: luvWei.toString(), worth, block };
|
| 229 |
}
|
donate.js
ADDED
|
@@ -0,0 +1,213 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
// SPDX-License-Identifier: MIT
|
| 2 |
+
// drAIML · the donation panel: sign in with login333 · drAIML, choose the CPU, RAM and GPU shares, confirm them, then
|
| 3 |
+
// watch what this computer gives (measured) and what it earns (SHAMBA LUV, 1 wei per generated token, valued in
|
| 4 |
+
// BANKON units), and request a payout to the signed-in wallet. Everything here runs in the page; the router only
|
| 5 |
+
// verifies the sign-in, keeps the ledger and records payout claims, which the drAIML operator pays.
|
| 6 |
+
|
| 7 |
+
import { donor, ensureEngine, reloadEngine } from "./bonsai.js";
|
| 8 |
+
import { LOGIN_KEY, login, format18, prices, valuation } from "./dmind.js";
|
| 9 |
+
|
| 10 |
+
const $ = (sel) => document.querySelector(sel);
|
| 11 |
+
const short = (a) => (a ? `${a.slice(0, 6)}…${a.slice(-4)}` : "");
|
| 12 |
+
const ETHERSCAN = "https://etherscan.io/tx/";
|
| 13 |
+
let timer = null;
|
| 14 |
+
|
| 15 |
+
// ── login333 · drAIML ─────────────────────────────────────────────────────────────────────────────────────────────
|
| 16 |
+
function siweMessage(address, nonce) {
|
| 17 |
+
const domain = location.host, uri = location.origin, issued = new Date().toISOString().replace(/\.\d{3}Z$/, "Z");
|
| 18 |
+
return `${domain} wants you to sign in with your Ethereum account:\n${address}\n\n` +
|
| 19 |
+
"Sign in to drAIML.dmind to receive SHAMBA LUV for the compute you donate. No transaction, no gas, nothing moves.\n\n" +
|
| 20 |
+
`URI: ${uri}\nVersion: 1\nChain ID: 1\nNonce: ${nonce}\nIssued At: ${issued}`;
|
| 21 |
+
}
|
| 22 |
+
function step(k, state) { const li = document.querySelector(`#dn-seq [data-k="${k}"]`); if (li) li.dataset.state = state; }
|
| 23 |
+
async function routerUrl() { return (await donor.config()).url.replace(/\/$/, ""); }
|
| 24 |
+
|
| 25 |
+
async function handshake(manual) {
|
| 26 |
+
const say = (t) => { $("#dn-login-status").textContent = t; };
|
| 27 |
+
try {
|
| 28 |
+
$("#dn-seq").hidden = false;
|
| 29 |
+
let address;
|
| 30 |
+
if (manual) {
|
| 31 |
+
address = $("#dn-addr").value.trim();
|
| 32 |
+
if (!/^0x[0-9a-fA-F]{40}$/.test(address)) { say("Enter the wallet address (0x + 40 hex characters) first."); return; }
|
| 33 |
+
} else {
|
| 34 |
+
if (!window.ethereum) { say("No browser wallet found. Use “Sign elsewhere” below."); $("#dn-manual").open = true; return; }
|
| 35 |
+
[address] = await window.ethereum.request({ method: "eth_requestAccounts" });
|
| 36 |
+
}
|
| 37 |
+
step("wallet", "done");
|
| 38 |
+
const base = await routerUrl();
|
| 39 |
+
const n = await (await fetch(`${base}/auth/nonce?address=${address}`)).json();
|
| 40 |
+
if (!n.ok) throw new Error(n.reason);
|
| 41 |
+
step("nonce", "done");
|
| 42 |
+
const message = siweMessage(address, n.nonce);
|
| 43 |
+
let signature;
|
| 44 |
+
if (manual) {
|
| 45 |
+
$("#dn-msg").value = message;
|
| 46 |
+
say("Sign this exact message with your wallet (for example `cast wallet sign`), paste the signature, then press Verify.");
|
| 47 |
+
$("#dn-verify").hidden = false;
|
| 48 |
+
$("#dn-verify").onclick = () => finish(base, message, $("#dn-sig").value.trim(), say);
|
| 49 |
+
return;
|
| 50 |
+
}
|
| 51 |
+
signature = await window.ethereum.request({ method: "personal_sign", params: [message, address] });
|
| 52 |
+
await finish(base, message, signature, say);
|
| 53 |
+
} catch (e) {
|
| 54 |
+
say(`Sign-in stopped: ${(e && e.message) || e}`);
|
| 55 |
+
}
|
| 56 |
+
}
|
| 57 |
+
async function finish(base, message, signature, say) {
|
| 58 |
+
step("sign", "done");
|
| 59 |
+
const v = await (await fetch(`${base}/auth/verify`, { method: "POST", headers: { "content-type": "application/json" },
|
| 60 |
+
body: JSON.stringify({ message, signature }) })).json();
|
| 61 |
+
if (!v.ok) { say(`Not signed in: ${v.reason}`); return; }
|
| 62 |
+
step("verify", "done");
|
| 63 |
+
const exp = Math.floor(Date.now() / 1000) + v.expires_days * 86400;
|
| 64 |
+
try { localStorage.setItem(LOGIN_KEY, JSON.stringify({ address: v.address, token: v.token, exp })); } catch {}
|
| 65 |
+
step("open", "done");
|
| 66 |
+
say("");
|
| 67 |
+
if (donor.running) { donor.stop(); donor.settings({ on: true }); } // rejoin, now paid to this wallet
|
| 68 |
+
render();
|
| 69 |
+
}
|
| 70 |
+
function signOut() {
|
| 71 |
+
try { localStorage.removeItem(LOGIN_KEY); } catch {}
|
| 72 |
+
document.querySelectorAll("#dn-seq li").forEach((li) => { li.dataset.state = ""; });
|
| 73 |
+
$("#dn-seq").hidden = true;
|
| 74 |
+
if (donor.running) { donor.stop(); donor.settings({ on: true }); }
|
| 75 |
+
render();
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
// ── the share and its confirmation ────────────────────────────────────────────────────────────────────────────────
|
| 79 |
+
function wanted() {
|
| 80 |
+
return { cpu: $("#dn-cpu-on").checked, pct: +$("#dn-cpu").value, ram: $("#dn-ram-on").checked, jobTokens: +$("#dn-ram").value,
|
| 81 |
+
gpu: $("#dn-gpu-on").checked, gpuPct: +$("#dn-gpu").value };
|
| 82 |
+
}
|
| 83 |
+
function describe(w) {
|
| 84 |
+
const threads = Math.max(1, Math.min(4, Math.floor((navigator.hardwareConcurrency || 2) / 2)));
|
| 85 |
+
return [
|
| 86 |
+
["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"],
|
| 87 |
+
["RAM", w.ram ? `Bonsai stays loaded (about 320 MB) · jobs up to ${w.jobTokens} tokens` : "not shared"],
|
| 88 |
+
["GPU", w.gpu ? `up to ${w.gpuPct}% of the graphics card's time (WebGPU, low-power), when this browser has a verified card` : "off"],
|
| 89 |
+
["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"],
|
| 90 |
+
["Pauses", "while you ask a question, when this tab is hidden, and on battery"],
|
| 91 |
+
];
|
| 92 |
+
}
|
| 93 |
+
function refreshLabels() {
|
| 94 |
+
const w = wanted();
|
| 95 |
+
$("#dn-cpu-val").textContent = `${w.pct}%`; $("#dn-gpu-val").textContent = `${w.gpuPct}%`;
|
| 96 |
+
$("#dn-cpu").disabled = !w.cpu; $("#dn-ram").disabled = !w.ram; $("#dn-gpu").disabled = !w.gpu;
|
| 97 |
+
const go = $("#dn-review");
|
| 98 |
+
go.disabled = !(w.cpu && w.ram);
|
| 99 |
+
go.textContent = donor.ledger.on ? "Review and update" : "Review and start donating";
|
| 100 |
+
$("#dn-need").hidden = w.cpu && w.ram;
|
| 101 |
+
}
|
| 102 |
+
function review() {
|
| 103 |
+
const w = wanted(), dlg = $("#dn-confirm");
|
| 104 |
+
$("#dn-confirm-list").replaceChildren(...describe(w).map(([k, v]) => {
|
| 105 |
+
const li = document.createElement("li"); const b = document.createElement("b"); b.textContent = k + " "; li.append(b, v); return li;
|
| 106 |
+
}));
|
| 107 |
+
dlg.showModal();
|
| 108 |
+
$("#dn-confirm-yes").onclick = async () => {
|
| 109 |
+
dlg.close();
|
| 110 |
+
const gpuChanged = w.gpu !== donor.ledger.gpu || (w.gpu && w.gpuPct !== donor.ledger.gpuPct);
|
| 111 |
+
donor.settings({ pct: w.pct, gpu: w.gpu, gpuPct: w.gpuPct, jobTokens: w.jobTokens });
|
| 112 |
+
const say = (t) => { $("#dn-state").textContent = t; };
|
| 113 |
+
const mod = await import("./browseml/browseml.js");
|
| 114 |
+
let ok;
|
| 115 |
+
if (gpuChanged && mod.isReady()) { say("Restarting Bonsai with the new GPU share…"); ok = await reloadEngine((t) => say(t)); }
|
| 116 |
+
else ok = await ensureEngine((t) => say(t));
|
| 117 |
+
if (!ok) { say("Donating needs Bonsai in this browser: accept the Agreement to start."); return; }
|
| 118 |
+
donor.settings({ on: true });
|
| 119 |
+
render();
|
| 120 |
+
};
|
| 121 |
+
$("#dn-confirm-no").onclick = () => dlg.close();
|
| 122 |
+
}
|
| 123 |
+
function stop() { donor.settings({ on: false }); render(); }
|
| 124 |
+
|
| 125 |
+
// ── measurement and earnings ──────────────────────────────────────────────────────────────────────────────────────
|
| 126 |
+
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; }
|
| 127 |
+
async function render() {
|
| 128 |
+
const s = login();
|
| 129 |
+
$("#dn-signed").hidden = !s; $("#dn-signin").hidden = !!s;
|
| 130 |
+
if (s) $("#dn-who").textContent = s.address;
|
| 131 |
+
$("#dn-stop").hidden = !donor.ledger.on;
|
| 132 |
+
refreshLabels();
|
| 133 |
+
|
| 134 |
+
const st = await donor.status(), m = await donor.measure();
|
| 135 |
+
const label = { sharing: "🟢 Lending", paused: "⏸️ Paused", waiting: "⏳ Pledged", retrying: "🔄 Reconnecting", stopped: "⛔ Stopped", off: "Off" }[st.state] || st.state;
|
| 136 |
+
$("#dn-state").textContent = st.on ? `${label}${st.note ? " · " + st.note : ""}` : "Not donating.";
|
| 137 |
+
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");
|
| 138 |
+
$("#dn-measure").replaceChildren(
|
| 139 |
+
row("Threads", m.threads ? `${m.threads} of ${m.cores} cores` : "engine not loaded"),
|
| 140 |
+
row("Engine memory", m.memoryMB ? `${m.memoryMB} MB${m.deviceMemoryGB ? ` of ~${m.deviceMemoryGB} GB` : ""}` : "—"),
|
| 141 |
+
row("GPU", gpu),
|
| 142 |
+
row("CPU given", m.lastMs
|
| 143 |
+
? `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` +
|
| 144 |
+
(m.wallMs > 300000 ? ` · ${m.dutyPct.toFixed(1)}% on average since you started` : " · the average settles over a few cycles")
|
| 145 |
+
: "no job yet"),
|
| 146 |
+
row("Jobs this visit", `${m.jobs} · ${m.tokens} tokens · ${(m.engineMs / 1000).toFixed(0)} s of thinking`),
|
| 147 |
+
row("Last job speed", m.genTps ? `reads ${m.promptTps.toFixed(1)} · writes ${m.genTps.toFixed(1)} tokens/s` : "—"),
|
| 148 |
+
);
|
| 149 |
+
|
| 150 |
+
// earnings: this browser's own count, the router's account, and their worth
|
| 151 |
+
const local = BigInt(st.luv_wei || "0");
|
| 152 |
+
let acct = null; try { acct = await donor.earnings(); } catch {}
|
| 153 |
+
const earned = acct ? BigInt(acct.luv_wei) : local;
|
| 154 |
+
const rows = [row("Earned (this browser)", `${format18(local)} LUV`)];
|
| 155 |
+
if (acct) {
|
| 156 |
+
rows.push(row("Earned (drAIML.dmind ledger)", `${format18(BigInt(acct.luv_wei))} LUV · ${acct.jobs} jobs`),
|
| 157 |
+
row("Claimed · paid", `${format18(BigInt(acct.claimed_wei))} · ${format18(BigInt(acct.paid_wei))} LUV`),
|
| 158 |
+
row("Available to claim", `${format18(BigInt(acct.available_wei))} LUV`));
|
| 159 |
+
}
|
| 160 |
+
try {
|
| 161 |
+
const p = await prices(), v = valuation(earned, p);
|
| 162 |
+
// 18 decimals round tiny amounts to zero: the approximation beside each keeps every significant digit
|
| 163 |
+
const usd = Number(earned) / 1e18 * Number(p.luvUsd18) / 1e18, btc = Number(p.btcUsd18) / 1e18, xau = Number(p.xauUsd18) / 1e18;
|
| 164 |
+
const ap = (x) => (x ? x.toExponential(3) : "0");
|
| 165 |
+
rows.push(row("Worth (18 decimals)", `${format18(v.PAI)} PAI · ${format18(v.SATPAY)} SATPAY · ${format18(v.BTC)} BTC · ${format18(v.GLDB)} GLDB`),
|
| 166 |
+
row("Worth (≈)", `${ap(usd)} PAI · ${btc ? ap(usd / btc * 1e8) : "?"} SATPAY · ${btc ? ap(usd / btc) : "?"} BTC · ${xau ? ap(usd / (xau * 0.000241833)) : "?"} GLDB`),
|
| 167 |
+
row("Price used", `1 LUV = ${ap(Number(p.luvUsd18) / 1e18)} USD (Uniswap reserves, block ${p.block}) · 1 BTC = ${btc.toFixed(0)} USD`));
|
| 168 |
+
} catch { rows.push(row("Worth", "prices unavailable right now")); }
|
| 169 |
+
$("#dn-earn").replaceChildren(...rows);
|
| 170 |
+
const pay = $("#dn-payout");
|
| 171 |
+
pay.disabled = !(acct && BigInt(acct.available_wei) > 0n);
|
| 172 |
+
pay.textContent = s ? `Request payout to ${short(s.address)}` : "Sign in to request a payout";
|
| 173 |
+
const list = $("#dn-claims");
|
| 174 |
+
list.replaceChildren(...((acct && acct.claims) || []).slice().reverse().map((c) => {
|
| 175 |
+
const li = document.createElement("li");
|
| 176 |
+
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"}`;
|
| 177 |
+
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); }
|
| 178 |
+
return li;
|
| 179 |
+
}));
|
| 180 |
+
}
|
| 181 |
+
async function payout() {
|
| 182 |
+
const s = login(); if (!s) return;
|
| 183 |
+
$("#dn-payout").disabled = true;
|
| 184 |
+
try {
|
| 185 |
+
const r = await donor.claim();
|
| 186 |
+
$("#dn-pay-status").textContent = r.ok ? `Requested ${format18(BigInt(r.claim.luv_wei))} LUV to ${short(s.address)}.` : `Not requested: ${r.reason}`;
|
| 187 |
+
} catch (e) { $("#dn-pay-status").textContent = `Not requested: ${e.message || e}`; }
|
| 188 |
+
render();
|
| 189 |
+
}
|
| 190 |
+
|
| 191 |
+
// ── the drawer ────────────────────────────────────────────────────────────────────────────────────────────────────
|
| 192 |
+
export function open() {
|
| 193 |
+
const d = $("#donate"); if (!d) return;
|
| 194 |
+
const l = donor.ledger;
|
| 195 |
+
$("#dn-cpu-on").checked = true; $("#dn-cpu").value = l.pct; $("#dn-ram-on").checked = true; $("#dn-ram").value = String(l.jobTokens);
|
| 196 |
+
$("#dn-gpu-on").checked = l.gpu; $("#dn-gpu").value = l.gpuPct;
|
| 197 |
+
d.showModal();
|
| 198 |
+
render();
|
| 199 |
+
clearInterval(timer); timer = setInterval(() => { if (d.open) render(); else clearInterval(timer); }, 5000);
|
| 200 |
+
}
|
| 201 |
+
export function init() {
|
| 202 |
+
$("#donate-open").addEventListener("click", open);
|
| 203 |
+
$("#dmind-chip").addEventListener("click", open);
|
| 204 |
+
window.addEventListener("draiml:donate", open);
|
| 205 |
+
$("#dn-close").onclick = () => $("#donate").close();
|
| 206 |
+
$("#dn-go").onclick = () => handshake(false);
|
| 207 |
+
$("#dn-manual-go").onclick = () => handshake(true);
|
| 208 |
+
$("#dn-signout").onclick = signOut;
|
| 209 |
+
["#dn-cpu-on", "#dn-cpu", "#dn-ram-on", "#dn-ram", "#dn-gpu-on", "#dn-gpu"].forEach((s) => $(s).addEventListener("input", refreshLabels));
|
| 210 |
+
$("#dn-review").onclick = review;
|
| 211 |
+
$("#dn-stop").onclick = stop;
|
| 212 |
+
$("#dn-payout").onclick = payout;
|
| 213 |
+
}
|
index.html
CHANGED
|
@@ -63,6 +63,39 @@
|
|
| 63 |
.agree .prog b { display: block; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; margin-top: 6px; }
|
| 64 |
.agree .prog i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .3s; }
|
| 65 |
button.hf:disabled { opacity: .55; cursor: default; }
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 66 |
</style>
|
| 67 |
</head>
|
| 68 |
<body>
|
|
@@ -74,6 +107,7 @@
|
|
| 74 |
<span class="spacer"></span>
|
| 75 |
<span class="sos">Emergency? Call your local emergency number.</span>
|
| 76 |
<span class="chip" id="bonsai-chip" hidden role="status"></span>
|
|
|
|
| 77 |
<span class="chip" id="dmind-chip" hidden role="status" title="Your donation to drAIML.dmind: LUV at 1 wei per token you generated"></span>
|
| 78 |
<span class="who" id="who"></span>
|
| 79 |
<button class="hf primary" id="signin" hidden>Sign in with Hugging Face</button>
|
|
@@ -81,6 +115,72 @@
|
|
| 81 |
</header>
|
| 82 |
<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>
|
| 83 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 84 |
<dialog id="bonsai-agreement" aria-labelledby="agree-title">
|
| 85 |
<div class="agree">
|
| 86 |
<h2 id="agree-title">drAIML Agreement · Bonsai in this browser</h2>
|
|
@@ -117,10 +217,12 @@
|
|
| 117 |
import { mount } from "https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.js";
|
| 118 |
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";
|
| 119 |
import { startBridge } from "./bonsai.js";
|
|
|
|
| 120 |
|
| 121 |
// this tab's id: Python (in its Web Worker) and this page find each other by it over a BroadcastChannel
|
| 122 |
const PAGE_ID = (crypto.randomUUID && crypto.randomUUID()) || String(Math.random()).slice(2);
|
| 123 |
startBridge(PAGE_ID, { signin: () => document.getElementById("signin").click() });
|
|
|
|
| 124 |
|
| 125 |
const KEY = "draiml-oauth";
|
| 126 |
const vars = (window.huggingface && window.huggingface.variables) || {};
|
|
|
|
| 63 |
.agree .prog b { display: block; height: 6px; background: var(--line); border-radius: 3px; overflow: hidden; margin-top: 6px; }
|
| 64 |
.agree .prog i { display: block; height: 100%; width: 0; background: var(--accent); transition: width .3s; }
|
| 65 |
button.hf:disabled { opacity: .55; cursor: default; }
|
| 66 |
+
#dmind-chip { cursor: pointer; }
|
| 67 |
+
button.heart { border-color: var(--warn); color: var(--warn); }
|
| 68 |
+
dialog.panel { max-width: min(620px, calc(100vw - 32px)); width: 100%; border: 1px solid var(--line); border-radius: 14px;
|
| 69 |
+
padding: 0; background: var(--surface); color: var(--ink); box-shadow: 0 20px 60px rgba(0,0,0,.25); }
|
| 70 |
+
dialog.panel::backdrop { background: rgba(6, 20, 19, .55); }
|
| 71 |
+
.dn { padding: 18px 22px 20px; max-height: calc(100vh - 64px); overflow-y: auto; box-sizing: border-box; }
|
| 72 |
+
.dn header.top { display: flex; align-items: center; gap: 10px; padding: 0; border: 0; min-height: 0; background: none; }
|
| 73 |
+
.dn h2 { margin: 0; font-size: 1.2rem; flex: 1; }
|
| 74 |
+
.dn h3 { margin: 18px 0 6px; font-size: 0.82rem; text-transform: uppercase; letter-spacing: .04em; color: var(--muted); }
|
| 75 |
+
.dn p, .dn li, .dn label, .dn dd, .dn dt { font-size: 0.93rem; line-height: 1.45; }
|
| 76 |
+
.dn .lede { margin: 4px 0 0; color: var(--muted); }
|
| 77 |
+
.dn .card { border: 1px solid var(--line); border-radius: 10px; padding: 12px 14px; margin-top: 6px; }
|
| 78 |
+
.dn .brand333 { font-weight: 700; letter-spacing: .02em; }
|
| 79 |
+
.dn .brand333 span { color: var(--accent); }
|
| 80 |
+
.dn ol.seq { margin: 8px 0 0; padding-left: 20px; color: var(--muted); }
|
| 81 |
+
.dn ol.seq li[data-state="done"] { color: var(--accent); }
|
| 82 |
+
.dn ol.seq li[data-state="done"]::after { content: " ✓"; }
|
| 83 |
+
.dn .row { display: flex; gap: 10px; align-items: center; flex-wrap: wrap; margin-top: 8px; }
|
| 84 |
+
.dn .share { display: grid; grid-template-columns: auto 1fr auto; gap: 8px 12px; align-items: center; }
|
| 85 |
+
.dn .share input[type=range] { width: 100%; accent-color: var(--accent); }
|
| 86 |
+
.dn .share select { font: inherit; padding: 3px 6px; border-radius: 6px; border: 1px solid var(--line); background: var(--surface); color: var(--ink); }
|
| 87 |
+
.dn .hint { color: var(--muted); font-size: 0.84rem; margin: 4px 0 0; }
|
| 88 |
+
.dn dl { margin: 0; display: grid; gap: 4px; }
|
| 89 |
+
.dn dl div { display: grid; grid-template-columns: 170px 1fr; gap: 10px; }
|
| 90 |
+
.dn dt { color: var(--muted); }
|
| 91 |
+
.dn dd { margin: 0; word-break: break-word; font-variant-numeric: tabular-nums; }
|
| 92 |
+
.dn textarea, .dn input[type=text] { width: 100%; box-sizing: border-box; font: 0.85rem ui-monospace, monospace; padding: 6px;
|
| 93 |
+
border: 1px solid var(--line); border-radius: 6px; background: var(--bg); color: var(--ink); }
|
| 94 |
+
.dn details summary { cursor: pointer; color: var(--muted); font-size: 0.88rem; margin-top: 8px; }
|
| 95 |
+
.dn .state { font-weight: 600; margin: 4px 0 0; }
|
| 96 |
+
.dn ul.claims { margin: 6px 0 0; padding-left: 18px; color: var(--muted); }
|
| 97 |
+
.dn ul.claims a { color: var(--accent); margin-left: 4px; }
|
| 98 |
+
@media (max-width: 560px) { .dn dl div { grid-template-columns: 1fr; gap: 0; } }
|
| 99 |
</style>
|
| 100 |
</head>
|
| 101 |
<body>
|
|
|
|
| 107 |
<span class="spacer"></span>
|
| 108 |
<span class="sos">Emergency? Call your local emergency number.</span>
|
| 109 |
<span class="chip" id="bonsai-chip" hidden role="status"></span>
|
| 110 |
+
<button class="hf heart" id="donate-open" title="Donate compute to drAIML.dmind and earn SHAMBA LUV">❤️ Donate</button>
|
| 111 |
<span class="chip" id="dmind-chip" hidden role="status" title="Your donation to drAIML.dmind: LUV at 1 wei per token you generated"></span>
|
| 112 |
<span class="who" id="who"></span>
|
| 113 |
<button class="hf primary" id="signin" hidden>Sign in with Hugging Face</button>
|
|
|
|
| 115 |
</header>
|
| 116 |
<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>
|
| 117 |
|
| 118 |
+
<dialog id="donate" class="panel" aria-labelledby="dn-title">
|
| 119 |
+
<div class="dn">
|
| 120 |
+
<header class="top"><h2 id="dn-title">❤️ Help save lives · drAIML.dmind</h2><button class="hf" id="dn-close" aria-label="Close">✕</button></header>
|
| 121 |
+
<p class="lede">Lend part of this computer to drAIML's distributed mind: it answers other people's health questions with
|
| 122 |
+
Bonsai, in this browser, and you earn SHAMBA LUV for every token it writes.</p>
|
| 123 |
+
|
| 124 |
+
<h3>1 · Sign in</h3>
|
| 125 |
+
<div class="card" id="dn-signin">
|
| 126 |
+
<div class="brand333">login333 · <span>drAIML</span></div>
|
| 127 |
+
<p class="hint">Sign one message with your wallet to prove the key is yours. No transaction, no gas, nothing moves.
|
| 128 |
+
Your payouts go to this wallet.</p>
|
| 129 |
+
<div class="row"><button class="hf primary" id="dn-go">Begin the HANDSHAKE</button></div>
|
| 130 |
+
<ol class="seq" id="dn-seq" hidden>
|
| 131 |
+
<li data-k="wallet">Wallet connected</li><li data-k="nonce">One-time code issued</li>
|
| 132 |
+
<li data-k="sign">HANDSHAKE signed</li><li data-k="verify">Signature checked by drAIML.dmind</li><li data-k="open">Signed in</li>
|
| 133 |
+
</ol>
|
| 134 |
+
<details id="dn-manual"><summary>No browser wallet? Sign elsewhere and paste the signature</summary>
|
| 135 |
+
<p class="hint">Your wallet address:</p><input type="text" id="dn-addr" placeholder="0x…" autocomplete="off" />
|
| 136 |
+
<div class="row"><button class="hf" id="dn-manual-go">Get the message to sign</button></div>
|
| 137 |
+
<textarea id="dn-msg" rows="7" readonly aria-label="Message to sign"></textarea>
|
| 138 |
+
<p class="hint">Signature (0x…):</p><input type="text" id="dn-sig" autocomplete="off" />
|
| 139 |
+
<div class="row"><button class="hf primary" id="dn-verify" hidden>Verify</button></div>
|
| 140 |
+
</details>
|
| 141 |
+
<p class="hint" id="dn-login-status" role="status"></p>
|
| 142 |
+
</div>
|
| 143 |
+
<div class="card" id="dn-signed" hidden>
|
| 144 |
+
<div class="brand333">login333 · <span>drAIML</span> ✓</div>
|
| 145 |
+
<p class="hint">Signed in as <code id="dn-who"></code></p>
|
| 146 |
+
<div class="row"><button class="hf" id="dn-signout">Sign out</button></div>
|
| 147 |
+
</div>
|
| 148 |
+
|
| 149 |
+
<h3>2 · What to share</h3>
|
| 150 |
+
<div class="card share">
|
| 151 |
+
<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>
|
| 152 |
+
<input type="checkbox" id="dn-ram-on" checked aria-label="Share RAM" /><label for="dn-ram">RAM · largest job
|
| 153 |
+
<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>
|
| 154 |
+
<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>
|
| 155 |
+
</div>
|
| 156 |
+
<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>
|
| 157 |
+
<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>
|
| 158 |
+
<p class="state" id="dn-state" role="status"></p>
|
| 159 |
+
|
| 160 |
+
<h3>3 · Measured</h3>
|
| 161 |
+
<div class="card"><dl id="dn-measure"></dl></div>
|
| 162 |
+
|
| 163 |
+
<h3>4 · Earnings and payout</h3>
|
| 164 |
+
<div class="card"><dl id="dn-earn"></dl>
|
| 165 |
+
<div class="row"><button class="hf primary" id="dn-payout" disabled>Request payout</button></div>
|
| 166 |
+
<p class="hint" id="dn-pay-status" role="status"></p>
|
| 167 |
+
<ul class="claims" id="dn-claims"></ul>
|
| 168 |
+
<p class="hint">1 wei of SHAMBA LUV (0x2711…8254, Ethereum) per generated token, counted to 18 decimals (SCIEN·TIFIC).
|
| 169 |
+
Payouts are sent by the drAIML operator from the ledger in batches. BANKON PAI (1 = 1 USDC), SATPAY (1 sat) and
|
| 170 |
+
GLDB are units of account only.</p>
|
| 171 |
+
</div>
|
| 172 |
+
</div>
|
| 173 |
+
</dialog>
|
| 174 |
+
|
| 175 |
+
<dialog id="dn-confirm" class="panel" aria-labelledby="dn-confirm-title">
|
| 176 |
+
<div class="dn">
|
| 177 |
+
<h2 id="dn-confirm-title">Confirm what this computer shares</h2>
|
| 178 |
+
<ul id="dn-confirm-list"></ul>
|
| 179 |
+
<p class="hint">You can change or stop this at any time from ❤️ Donate. Nothing runs when this tab is closed.</p>
|
| 180 |
+
<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>
|
| 181 |
+
</div>
|
| 182 |
+
</dialog>
|
| 183 |
+
|
| 184 |
<dialog id="bonsai-agreement" aria-labelledby="agree-title">
|
| 185 |
<div class="agree">
|
| 186 |
<h2 id="agree-title">drAIML Agreement · Bonsai in this browser</h2>
|
|
|
|
| 217 |
import { mount } from "https://cdn.jsdelivr.net/npm/@stlite/browser@1.12.1/build/stlite.js";
|
| 218 |
import { oauthLoginUrl, oauthHandleRedirectIfPresent } from "https://cdn.jsdelivr.net/npm/@huggingface/hub@2.17.10/+esm";
|
| 219 |
import { startBridge } from "./bonsai.js";
|
| 220 |
+
import { init as initDonate } from "./donate.js";
|
| 221 |
|
| 222 |
// this tab's id: Python (in its Web Worker) and this page find each other by it over a BroadcastChannel
|
| 223 |
const PAGE_ID = (crypto.randomUUID && crypto.randomUUID()) || String(Math.random()).slice(2);
|
| 224 |
startBridge(PAGE_ID, { signin: () => document.getElementById("signin").click() });
|
| 225 |
+
initDonate();
|
| 226 |
|
| 227 |
const KEY = "draiml-oauth";
|
| 228 |
const vars = (window.huggingface && window.huggingface.variables) || {};
|
router/README.md
CHANGED
|
@@ -42,6 +42,21 @@ a ledger, and hands every question to someone who lends compute.
|
|
| 42 |
- Queue cap 64, request body 64 KB.
|
| 43 |
- CORS only for drAIML's origins.
|
| 44 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 45 |
## Footprint
|
| 46 |
Python standard library only (asyncio), one process, about 14 MB of memory, idle between requests. It runs on
|
| 47 |
the busy one-core VPS as a sandboxed systemd service:
|
|
|
|
| 42 |
- Queue cap 64, request body 64 KB.
|
| 43 |
- CORS only for drAIML's origins.
|
| 44 |
|
| 45 |
+
## login333 · drAIML sign-in, earnings and payouts
|
| 46 |
+
- `GET /auth/nonce?address=0x…` issues a one-time code, valid for 5 minutes.
|
| 47 |
+
- `POST /auth/verify {message, signature}` checks the Sign-In with Ethereum message (EIP-4361) and its
|
| 48 |
+
personal_sign signature (EIP-191).
|
| 49 |
+
- Recovery runs offline in `siwe.py`: keccak-256 and secp256k1, standard library only, about 30 ms of CPU.
|
| 50 |
+
- The message must be for drAIML's domain and chain 1, and the code must be unused.
|
| 51 |
+
- It returns a 7-day token.
|
| 52 |
+
- A donor who joins with that token earns to that wallet; without one, its work is counted but no wallet earns it.
|
| 53 |
+
- `GET /sharedcpu/me` (token) shows LUV earned, claimed, paid and available.
|
| 54 |
+
- `POST /sharedcpu/claim` (token) records a payout claim for everything available.
|
| 55 |
+
- `payout.py` is the operator's side. It holds no key and sends nothing: the operator pays from their own wallet.
|
| 56 |
+
- `list` shows open claims.
|
| 57 |
+
- `batch` writes a CSV (address, amount in wei).
|
| 58 |
+
- `mark ID 0xTX` records a payment, which donors then see in the panel with its transaction link.
|
| 59 |
+
|
| 60 |
## Footprint
|
| 61 |
Python standard library only (asyncio), one process, about 14 MB of memory, idle between requests. It runs on
|
| 62 |
the busy one-core VPS as a sandboxed systemd service:
|
router/draiml_router.py
CHANGED
|
@@ -31,15 +31,19 @@ import argparse
|
|
| 31 |
import asyncio
|
| 32 |
import collections
|
| 33 |
import hashlib
|
|
|
|
| 34 |
import json
|
| 35 |
import os
|
| 36 |
import random
|
| 37 |
import secrets
|
| 38 |
import time
|
| 39 |
from dataclasses import dataclass, field
|
|
|
|
| 40 |
from urllib.parse import parse_qs, urlsplit
|
| 41 |
|
| 42 |
-
|
|
|
|
|
|
|
| 43 |
HOST_LABEL = "drAIML.dmind"
|
| 44 |
BONSAI_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"
|
| 45 |
MODELS = { # what workers may serve: name -> pinned sha256 and engine group (members must agree token for token)
|
|
@@ -57,6 +61,8 @@ CLIENT_WAIT_S = 600 # how long a client request may wait for a worker's
|
|
| 57 |
CROSS_CHECK = 0.05 # share of temperature-0 jobs also sent to a second worker
|
| 58 |
RATE = (6, 60) # client requests per IP: 6 per 60 s
|
| 59 |
WEI_PER_TOKEN = 1
|
|
|
|
|
|
|
| 60 |
|
| 61 |
|
| 62 |
def now() -> float:
|
|
@@ -99,6 +105,15 @@ class Job:
|
|
| 99 |
|
| 100 |
class Router:
|
| 101 |
def __init__(self, ledger_path: str, keys_path: str | None = None):
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 102 |
self.workers: dict[str, Worker] = {}
|
| 103 |
self.queue: collections.deque[Job] = collections.deque()
|
| 104 |
self.jobs: dict[str, Job] = {}
|
|
@@ -178,21 +193,18 @@ class Router:
|
|
| 178 |
self.jobs.pop(j.id, None)
|
| 179 |
|
| 180 |
# ── worker API (dmind) ───────────────────────────────────────────────────────────────────────────────────────
|
| 181 |
-
def join(self, b: dict, ip: str) -> dict:
|
| 182 |
sha = str(b.get("model_sha256", "")).lower()
|
| 183 |
model = next((m for m, v in MODELS.items() if v["sha256"] == sha), None)
|
| 184 |
if not model:
|
| 185 |
return {"ok": False, "reason": "this host serves only pinned models", "models": MODELS}
|
| 186 |
-
|
| 187 |
-
if wallet and not (wallet.startswith("0x") and len(wallet) == 42):
|
| 188 |
-
wallet = ""
|
| 189 |
-
s = secrets.token_hex(16)
|
| 190 |
self.workers[s] = Worker(s, model, str(b.get("engine", ""))[:40], max(1, min(100, int(b.get("share_pct") or 10))),
|
| 191 |
wallet, str(b.get("contributor", ""))[:20], ip)
|
| 192 |
self.stats["joins"] += 1
|
| 193 |
return {"ok": True, "session": s, "host": HOST_LABEL, "model": model, "engine_group": MODELS[model]["group"],
|
| 194 |
"ttl_s": SESSION_TTL_S, "pull_wait_s": PULL_WAIT_S, "lease_s": LEASE_S,
|
| 195 |
-
"trust": {"note": "receipts checked; occasional cross-checks between workers"}}
|
| 196 |
|
| 197 |
def _worker(self, b: dict) -> Worker | None:
|
| 198 |
w = self.workers.get(str(b.get("session", "")))
|
|
@@ -338,6 +350,91 @@ class Router:
|
|
| 338 |
"usage": u, "timings": r["timings"], "bankml_receipt": r["receipt"],
|
| 339 |
"draiml_dmind": {"host": HOST_LABEL, "worker": r["worker"]}}
|
| 340 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
def insight(self) -> dict:
|
| 342 |
return {"host": HOST_LABEL, "version": VERSION, "up_s": int(time.time() - self.started),
|
| 343 |
"workers": len(self.workers), "lending": sum(1 for w in self.workers.values() if not w.paused),
|
|
@@ -356,8 +453,11 @@ class Router:
|
|
| 356 |
tokens += int(e.get("tokens", 0))
|
| 357 |
jobs += 1
|
| 358 |
wei = tokens * WEI_PER_TOKEN
|
| 359 |
-
|
| 360 |
-
|
|
|
|
|
|
|
|
|
|
| 361 |
|
| 362 |
|
| 363 |
# ── a minimal HTTP/1.1 server (stdlib asyncio) ───────────────────────────────────────────────────────────────────
|
|
@@ -406,9 +506,16 @@ async def handle(router: Router, reader: asyncio.StreamReader, writer: asyncio.S
|
|
| 406 |
elif method == "GET" and path in ("/v1/models", "/models"):
|
| 407 |
out = {"object": "list", "data": [{"id": m, "object": "model", "owned_by": HOST_LABEL} for m in MODELS]}
|
| 408 |
elif method == "GET" and path == "/sharedcpu/me":
|
| 409 |
-
out = router.me(
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 410 |
elif method == "POST" and path == "/sharedcpu/join":
|
| 411 |
-
out = router.join(body, ip)
|
| 412 |
elif method == "POST" and path == "/sharedcpu/update":
|
| 413 |
out = router.update(body)
|
| 414 |
elif method == "POST" and path == "/sharedcpu/pull":
|
|
|
|
| 31 |
import asyncio
|
| 32 |
import collections
|
| 33 |
import hashlib
|
| 34 |
+
import hmac
|
| 35 |
import json
|
| 36 |
import os
|
| 37 |
import random
|
| 38 |
import secrets
|
| 39 |
import time
|
| 40 |
from dataclasses import dataclass, field
|
| 41 |
+
from datetime import datetime, timezone
|
| 42 |
from urllib.parse import parse_qs, urlsplit
|
| 43 |
|
| 44 |
+
import siwe
|
| 45 |
+
|
| 46 |
+
VERSION = "0.2.0"
|
| 47 |
HOST_LABEL = "drAIML.dmind"
|
| 48 |
BONSAI_SHA256 = "3d7c6c90dd98717a203adb22d5eacd2581850e40aa5327e144b97766cae5f7e3"
|
| 49 |
MODELS = { # what workers may serve: name -> pinned sha256 and engine group (members must agree token for token)
|
|
|
|
| 61 |
CROSS_CHECK = 0.05 # share of temperature-0 jobs also sent to a second worker
|
| 62 |
RATE = (6, 60) # client requests per IP: 6 per 60 s
|
| 63 |
WEI_PER_TOKEN = 1
|
| 64 |
+
SIWE_DOMAINS = ("pythai-draiml.static.hf.space", "127.0.0.1:8766", "localhost:8766")
|
| 65 |
+
TOKEN_DAYS = 7
|
| 66 |
|
| 67 |
|
| 68 |
def now() -> float:
|
|
|
|
| 105 |
|
| 106 |
class Router:
|
| 107 |
def __init__(self, ledger_path: str, keys_path: str | None = None):
|
| 108 |
+
state = os.path.dirname(os.path.abspath(ledger_path))
|
| 109 |
+
self.claims_path = os.path.join(state, "claims.jsonl")
|
| 110 |
+
secret = os.path.join(state, "secret.key")
|
| 111 |
+
if not os.path.exists(secret):
|
| 112 |
+
with open(os.open(secret, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), "wb") as f:
|
| 113 |
+
f.write(secrets.token_bytes(32))
|
| 114 |
+
with open(secret, "rb") as f:
|
| 115 |
+
self.secret = f.read()
|
| 116 |
+
self.nonces: dict[str, tuple[str, float]] = {}
|
| 117 |
self.workers: dict[str, Worker] = {}
|
| 118 |
self.queue: collections.deque[Job] = collections.deque()
|
| 119 |
self.jobs: dict[str, Job] = {}
|
|
|
|
| 193 |
self.jobs.pop(j.id, None)
|
| 194 |
|
| 195 |
# ── worker API (dmind) ───────────────────────────────────────────────────────────────────────────────────────
|
| 196 |
+
def join(self, b: dict, ip: str, wallet: str = "") -> dict:
|
| 197 |
sha = str(b.get("model_sha256", "")).lower()
|
| 198 |
model = next((m for m, v in MODELS.items() if v["sha256"] == sha), None)
|
| 199 |
if not model:
|
| 200 |
return {"ok": False, "reason": "this host serves only pinned models", "models": MODELS}
|
| 201 |
+
s = secrets.token_hex(16) # the wallet comes only from a login333 · drAIML sign-in
|
|
|
|
|
|
|
|
|
|
| 202 |
self.workers[s] = Worker(s, model, str(b.get("engine", ""))[:40], max(1, min(100, int(b.get("share_pct") or 10))),
|
| 203 |
wallet, str(b.get("contributor", ""))[:20], ip)
|
| 204 |
self.stats["joins"] += 1
|
| 205 |
return {"ok": True, "session": s, "host": HOST_LABEL, "model": model, "engine_group": MODELS[model]["group"],
|
| 206 |
"ttl_s": SESSION_TTL_S, "pull_wait_s": PULL_WAIT_S, "lease_s": LEASE_S,
|
| 207 |
+
"wallet": wallet, "trust": {"note": "receipts checked; occasional cross-checks between workers"}}
|
| 208 |
|
| 209 |
def _worker(self, b: dict) -> Worker | None:
|
| 210 |
w = self.workers.get(str(b.get("session", "")))
|
|
|
|
| 350 |
"usage": u, "timings": r["timings"], "bankml_receipt": r["receipt"],
|
| 351 |
"draiml_dmind": {"host": HOST_LABEL, "worker": r["worker"]}}
|
| 352 |
|
| 353 |
+
# ── login333 · drAIML: Sign-In with Ethereum ────────────────────────────────────────────────────────────────
|
| 354 |
+
def nonce(self, address: str) -> dict:
|
| 355 |
+
if not (address.startswith("0x") and len(address) == 42):
|
| 356 |
+
return {"ok": False, "reason": "an Ethereum address is required"}
|
| 357 |
+
t = now()
|
| 358 |
+
for k, (_, exp) in list(self.nonces.items()):
|
| 359 |
+
if exp < t:
|
| 360 |
+
self.nonces.pop(k, None)
|
| 361 |
+
if len(self.nonces) > 2000:
|
| 362 |
+
return {"ok": False, "reason": "too many sign-ins in progress; try again soon"}
|
| 363 |
+
n = secrets.token_hex(8)
|
| 364 |
+
self.nonces[n] = (address.lower(), t + 300)
|
| 365 |
+
return {"ok": True, "nonce": n, "expires_s": 300, "domains": SIWE_DOMAINS, "chain_id": 1}
|
| 366 |
+
|
| 367 |
+
def _token(self, address: str) -> str:
|
| 368 |
+
exp = int(time.time()) + TOKEN_DAYS * 86400
|
| 369 |
+
mac = hmac.new(self.secret, f"{address}|{exp}".encode(), "sha256").hexdigest()[:40]
|
| 370 |
+
return f"{address}.{exp}.{mac}"
|
| 371 |
+
|
| 372 |
+
def wallet_of(self, auth: str) -> str:
|
| 373 |
+
"""The signed-in wallet a bearer token names, or "" if it is missing, forged or expired."""
|
| 374 |
+
try:
|
| 375 |
+
address, exp, mac = auth.removeprefix("Bearer ").strip().split(".")
|
| 376 |
+
except ValueError:
|
| 377 |
+
return ""
|
| 378 |
+
good = hmac.new(self.secret, f"{address}|{exp}".encode(), "sha256").hexdigest()[:40]
|
| 379 |
+
return address if hmac.compare_digest(good, mac) and int(exp) > time.time() else ""
|
| 380 |
+
|
| 381 |
+
def verify(self, b: dict) -> dict:
|
| 382 |
+
msg, sig = str(b.get("message", "")), str(b.get("signature", ""))
|
| 383 |
+
try:
|
| 384 |
+
f = siwe.parse_siwe(msg)
|
| 385 |
+
except ValueError as e:
|
| 386 |
+
return {"ok": False, "reason": str(e)}
|
| 387 |
+
if f["domain"] not in SIWE_DOMAINS or f["chain"] != "1":
|
| 388 |
+
return {"ok": False, "reason": "this sign-in is for another site or chain"}
|
| 389 |
+
held = self.nonces.pop(f["nonce"], None)
|
| 390 |
+
if not held or held[0] != f["address"].lower() or held[1] < now():
|
| 391 |
+
return {"ok": False, "reason": "the one-time code is unknown or expired: sign in again"}
|
| 392 |
+
try:
|
| 393 |
+
issued = datetime.fromisoformat(f["issued"].replace("Z", "+00:00"))
|
| 394 |
+
if abs((datetime.now(timezone.utc) - issued).total_seconds()) > 600:
|
| 395 |
+
return {"ok": False, "reason": "the sign-in message is too old"}
|
| 396 |
+
signer = siwe.personal_signer(msg, sig)
|
| 397 |
+
except ValueError as e:
|
| 398 |
+
return {"ok": False, "reason": f"the signature does not check: {e}"}
|
| 399 |
+
if signer.lower() != f["address"].lower():
|
| 400 |
+
return {"ok": False, "reason": "the signature is from another wallet"}
|
| 401 |
+
self.stats["signins"] += 1
|
| 402 |
+
return {"ok": True, "address": signer, "token": self._token(signer), "expires_days": TOKEN_DAYS}
|
| 403 |
+
|
| 404 |
+
# ── earnings and payout claims ──────────────────────────────────────────────────────────────────────────────
|
| 405 |
+
def _claims(self, wallet: str) -> tuple[int, int, list]:
|
| 406 |
+
claimed = paid = 0
|
| 407 |
+
rows: dict[str, dict] = {}
|
| 408 |
+
if os.path.exists(self.claims_path):
|
| 409 |
+
with open(self.claims_path) as f:
|
| 410 |
+
for line in f:
|
| 411 |
+
try:
|
| 412 |
+
e = json.loads(line)
|
| 413 |
+
except ValueError:
|
| 414 |
+
continue
|
| 415 |
+
if e.get("wallet", "").lower() != wallet.lower():
|
| 416 |
+
continue
|
| 417 |
+
rows.setdefault(e["id"], {}).update(e)
|
| 418 |
+
for c in rows.values():
|
| 419 |
+
claimed += int(c.get("luv_wei", 0))
|
| 420 |
+
if c.get("status") == "paid":
|
| 421 |
+
paid += int(c.get("luv_wei", 0))
|
| 422 |
+
return claimed, paid, sorted(rows.values(), key=lambda c: c.get("t", 0))[-10:]
|
| 423 |
+
|
| 424 |
+
def claim(self, wallet: str) -> dict:
|
| 425 |
+
if not wallet:
|
| 426 |
+
return {"ok": False, "reason": "sign in with login333 · drAIML first"}
|
| 427 |
+
m = self.me(wallet)
|
| 428 |
+
avail = int(m["available_wei"])
|
| 429 |
+
if avail <= 0:
|
| 430 |
+
return {"ok": False, "reason": "nothing to claim yet", **m}
|
| 431 |
+
c = {"id": secrets.token_hex(6), "t": int(time.time()), "wallet": wallet, "luv_wei": str(avail),
|
| 432 |
+
"token": "SHAMBA LUV 0x2711111111683b8708cb9a48cbf36a51315f8254", "status": "requested"}
|
| 433 |
+
with open(self.claims_path, "a") as f:
|
| 434 |
+
f.write(json.dumps(c, separators=(",", ":")) + "\n")
|
| 435 |
+
self.stats["claims"] += 1
|
| 436 |
+
return {"ok": True, "claim": c, **self.me(wallet)}
|
| 437 |
+
|
| 438 |
def insight(self) -> dict:
|
| 439 |
return {"host": HOST_LABEL, "version": VERSION, "up_s": int(time.time() - self.started),
|
| 440 |
"workers": len(self.workers), "lending": sum(1 for w in self.workers.values() if not w.paused),
|
|
|
|
| 453 |
tokens += int(e.get("tokens", 0))
|
| 454 |
jobs += 1
|
| 455 |
wei = tokens * WEI_PER_TOKEN
|
| 456 |
+
claimed, paid, claims = self._claims(wallet) if wallet else (0, 0, [])
|
| 457 |
+
f18 = lambda x: f"{x // 10**18}.{x % 10**18:018d}" # noqa: E731
|
| 458 |
+
return {"wallet": wallet, "jobs": jobs, "tokens": tokens, "luv_wei": str(wei), "luv": f18(wei),
|
| 459 |
+
"claimed_wei": str(claimed), "paid_wei": str(paid), "available_wei": str(wei - claimed),
|
| 460 |
+
"available": f18(wei - claimed), "claims": claims, "rule": "1 wei of SHAMBA LUV per generated token"}
|
| 461 |
|
| 462 |
|
| 463 |
# ── a minimal HTTP/1.1 server (stdlib asyncio) ───────────────────────────────────────────────────────────────────
|
|
|
|
| 506 |
elif method == "GET" and path in ("/v1/models", "/models"):
|
| 507 |
out = {"object": "list", "data": [{"id": m, "object": "model", "owned_by": HOST_LABEL} for m in MODELS]}
|
| 508 |
elif method == "GET" and path == "/sharedcpu/me":
|
| 509 |
+
out = router.me(router.wallet_of(h.get("authorization", ""))
|
| 510 |
+
or parse_qs(urlsplit(target).query).get("wallet", [""])[0])
|
| 511 |
+
elif method == "GET" and path == "/auth/nonce":
|
| 512 |
+
out = router.nonce(parse_qs(urlsplit(target).query).get("address", [""])[0])
|
| 513 |
+
elif method == "POST" and path == "/auth/verify":
|
| 514 |
+
out = router.verify(body)
|
| 515 |
+
elif method == "POST" and path == "/sharedcpu/claim":
|
| 516 |
+
out = router.claim(router.wallet_of(h.get("authorization", "")))
|
| 517 |
elif method == "POST" and path == "/sharedcpu/join":
|
| 518 |
+
out = router.join(body, ip, router.wallet_of(h.get("authorization", "")))
|
| 519 |
elif method == "POST" and path == "/sharedcpu/update":
|
| 520 |
out = router.update(body)
|
| 521 |
elif method == "POST" and path == "/sharedcpu/pull":
|
router/payout.py
ADDED
|
@@ -0,0 +1,83 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python3
|
| 2 |
+
# SPDX-License-Identifier: MIT
|
| 3 |
+
"""drAIML.dmind payouts — the operator's side of a donor's claim.
|
| 4 |
+
|
| 5 |
+
Donors sign in with login333 · drAIML and press "Request payout"; the router appends a claim (wallet, LUV in wei)
|
| 6 |
+
to claims.jsonl. This tool lists the open claims, writes them as a batch a wallet or multisend app can pay, and
|
| 7 |
+
records each payment's transaction hash once the operator has made it. It holds no key and sends nothing: moving
|
| 8 |
+
LUV is a step the operator takes in their own wallet.
|
| 9 |
+
|
| 10 |
+
payout.py list --state /var/lib/draiml-dmind
|
| 11 |
+
payout.py batch --state /var/lib/draiml-dmind --out batch.csv # address,amount_wei (SHAMBA LUV, 18 decimals)
|
| 12 |
+
payout.py mark --state /var/lib/draiml-dmind CLAIM_ID 0xTXHASH # after paying it
|
| 13 |
+
"""
|
| 14 |
+
from __future__ import annotations
|
| 15 |
+
|
| 16 |
+
import argparse
|
| 17 |
+
import csv
|
| 18 |
+
import json
|
| 19 |
+
import os
|
| 20 |
+
import re
|
| 21 |
+
import sys
|
| 22 |
+
import time
|
| 23 |
+
|
| 24 |
+
LUV = "0x2711111111683b8708cb9a48cbf36a51315f8254"
|
| 25 |
+
|
| 26 |
+
|
| 27 |
+
def claims(state: str) -> dict[str, dict]:
|
| 28 |
+
rows: dict[str, dict] = {}
|
| 29 |
+
path = os.path.join(state, "claims.jsonl")
|
| 30 |
+
if os.path.exists(path):
|
| 31 |
+
with open(path) as f:
|
| 32 |
+
for line in f:
|
| 33 |
+
try:
|
| 34 |
+
e = json.loads(line)
|
| 35 |
+
except ValueError:
|
| 36 |
+
continue
|
| 37 |
+
rows.setdefault(e["id"], {}).update(e)
|
| 38 |
+
return rows
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def f18(wei: int) -> str:
|
| 42 |
+
return f"{wei // 10**18}.{wei % 10**18:018d}"
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def main() -> int:
|
| 46 |
+
ap = argparse.ArgumentParser(description=__doc__.split("\n")[0])
|
| 47 |
+
ap.add_argument("cmd", choices=["list", "batch", "mark"])
|
| 48 |
+
ap.add_argument("args", nargs="*")
|
| 49 |
+
ap.add_argument("--state", default="/var/lib/draiml-dmind")
|
| 50 |
+
ap.add_argument("--out", default="batch.csv")
|
| 51 |
+
a = ap.parse_args()
|
| 52 |
+
open_ = {k: c for k, c in claims(a.state).items() if c.get("status") == "requested"}
|
| 53 |
+
if a.cmd == "list":
|
| 54 |
+
total = 0
|
| 55 |
+
for c in sorted(open_.values(), key=lambda c: c["t"]):
|
| 56 |
+
total += int(c["luv_wei"])
|
| 57 |
+
print(f"{c['id']} {time.strftime('%Y-%m-%d %H:%M', time.gmtime(c['t']))} {c['wallet']} {f18(int(c['luv_wei']))} LUV")
|
| 58 |
+
print(f"{len(open_)} open claims · {f18(total)} LUV ({total} wei) · token {LUV}")
|
| 59 |
+
elif a.cmd == "batch":
|
| 60 |
+
by: dict[str, int] = {}
|
| 61 |
+
for c in open_.values():
|
| 62 |
+
by[c["wallet"]] = by.get(c["wallet"], 0) + int(c["luv_wei"])
|
| 63 |
+
with open(a.out, "w", newline="") as f:
|
| 64 |
+
w = csv.writer(f)
|
| 65 |
+
w.writerow(["address", "amount_wei", "amount_luv", "claims"])
|
| 66 |
+
for addr, wei in sorted(by.items()):
|
| 67 |
+
ids = " ".join(k for k, c in open_.items() if c["wallet"] == addr)
|
| 68 |
+
w.writerow([addr, wei, f18(wei), ids])
|
| 69 |
+
print(f"wrote {a.out}: {len(by)} wallets, {f18(sum(by.values()))} LUV — pay it from your own wallet, "
|
| 70 |
+
f"then `payout.py mark ID TX` for each claim")
|
| 71 |
+
elif a.cmd == "mark":
|
| 72 |
+
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]):
|
| 73 |
+
print("usage: payout.py mark CLAIM_ID 0xTXHASH (an open claim id, a 32-byte transaction hash)", file=sys.stderr)
|
| 74 |
+
return 2
|
| 75 |
+
with open(os.path.join(a.state, "claims.jsonl"), "a") as f:
|
| 76 |
+
f.write(json.dumps({"id": a.args[0], "wallet": open_[a.args[0]]["wallet"], "status": "paid",
|
| 77 |
+
"tx": a.args[1], "paid_t": int(time.time())}, separators=(",", ":")) + "\n")
|
| 78 |
+
print(f"claim {a.args[0]} marked paid by {a.args[1]}")
|
| 79 |
+
return 0
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
if __name__ == "__main__":
|
| 83 |
+
raise SystemExit(main())
|
router/siwe.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# SPDX-License-Identifier: MIT
|
| 2 |
+
"""Sign-In with Ethereum for the drAIML.dmind router, standard library only.
|
| 3 |
+
|
| 4 |
+
keccak-256 (Ethereum's, not SHA3-256), secp256k1 public-key recovery, EIP-191 personal_sign, EIP-55 addresses and
|
| 5 |
+
an EIP-4361 message parser — enough to learn which wallet signed a login, offline, with no dependencies. Recovery
|
| 6 |
+
costs a few tens of milliseconds of CPU, once per sign-in.
|
| 7 |
+
"""
|
| 8 |
+
from __future__ import annotations
|
| 9 |
+
|
| 10 |
+
import re
|
| 11 |
+
|
| 12 |
+
# ── keccak-256 ───────────────────────────────────────────────────────────────────────────────────────────────────
|
| 13 |
+
_RC = [0x0000000000000001, 0x0000000000008082, 0x800000000000808A, 0x8000000080008000, 0x000000000000808B,
|
| 14 |
+
0x0000000080000001, 0x8000000080008081, 0x8000000000008009, 0x000000000000008A, 0x0000000000000088,
|
| 15 |
+
0x0000000080008009, 0x000000008000000A, 0x000000008000808B, 0x800000000000008B, 0x8000000000008089,
|
| 16 |
+
0x8000000000008003, 0x8000000000008002, 0x8000000000000080, 0x000000000000800A, 0x800000008000000A,
|
| 17 |
+
0x8000000080008081, 0x8000000000008080, 0x0000000080000001, 0x8000000080008008]
|
| 18 |
+
_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]]
|
| 19 |
+
_M = (1 << 64) - 1
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
def _rol(x, n):
|
| 23 |
+
return ((x << n) | (x >> (64 - n))) & _M if n else x
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
def _f(a):
|
| 27 |
+
for rc in _RC:
|
| 28 |
+
c = [a[x][0] ^ a[x][1] ^ a[x][2] ^ a[x][3] ^ a[x][4] for x in range(5)]
|
| 29 |
+
d = [c[(x - 1) % 5] ^ _rol(c[(x + 1) % 5], 1) for x in range(5)]
|
| 30 |
+
a = [[a[x][y] ^ d[x] for y in range(5)] for x in range(5)]
|
| 31 |
+
b = [[0] * 5 for _ in range(5)]
|
| 32 |
+
for x in range(5):
|
| 33 |
+
for y in range(5):
|
| 34 |
+
b[y][(2 * x + 3 * y) % 5] = _rol(a[x][y], _ROT[x][y])
|
| 35 |
+
a = [[b[x][y] ^ ((~b[(x + 1) % 5][y]) & b[(x + 2) % 5][y]) for y in range(5)] for x in range(5)]
|
| 36 |
+
a[0][0] ^= rc
|
| 37 |
+
return a
|
| 38 |
+
|
| 39 |
+
|
| 40 |
+
def keccak256(data: bytes) -> bytes:
|
| 41 |
+
rate = 136
|
| 42 |
+
q = rate - len(data) % rate
|
| 43 |
+
p = bytearray(data) + (b"\x81" if q == 1 else b"\x01" + b"\x00" * (q - 2) + b"\x80")
|
| 44 |
+
a = [[0] * 5 for _ in range(5)]
|
| 45 |
+
for off in range(0, len(p), rate):
|
| 46 |
+
blk = p[off:off + rate]
|
| 47 |
+
for i in range(rate // 8):
|
| 48 |
+
x, y = i % 5, i // 5
|
| 49 |
+
a[x][y] ^= int.from_bytes(blk[8 * i:8 * i + 8], "little")
|
| 50 |
+
a = _f(a)
|
| 51 |
+
out = b""
|
| 52 |
+
for i in range(4):
|
| 53 |
+
out += a[i % 5][i // 5].to_bytes(8, "little")
|
| 54 |
+
return out
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
# ── secp256k1 recovery ───────────────────────────────────────────────────────────────────────────────────────────
|
| 58 |
+
_P = 2**256 - 2**32 - 977
|
| 59 |
+
_N = 0xFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFEBAAEDCE6AF48A03BBFD25E8CD0364141
|
| 60 |
+
_G = (0x79BE667EF9DCBBAC55A06295CE870B07029BFCDB2DCE28D959F2815B16F81798,
|
| 61 |
+
0x483ADA7726A3C4655DA4FBFC0E1108A8FD17B448A68554199C47D08FFB10D4B8)
|
| 62 |
+
|
| 63 |
+
|
| 64 |
+
def _add(p, q):
|
| 65 |
+
if p is None:
|
| 66 |
+
return q
|
| 67 |
+
if q is None:
|
| 68 |
+
return p
|
| 69 |
+
if p[0] == q[0] and (p[1] + q[1]) % _P == 0:
|
| 70 |
+
return None
|
| 71 |
+
if p == q:
|
| 72 |
+
lam = 3 * p[0] * p[0] * pow(2 * p[1], -1, _P) % _P
|
| 73 |
+
else:
|
| 74 |
+
lam = (q[1] - p[1]) * pow(q[0] - p[0], -1, _P) % _P
|
| 75 |
+
x = (lam * lam - p[0] - q[0]) % _P
|
| 76 |
+
return x, (lam * (p[0] - x) - p[1]) % _P
|
| 77 |
+
|
| 78 |
+
|
| 79 |
+
def _mul(k, p):
|
| 80 |
+
r = None
|
| 81 |
+
while k:
|
| 82 |
+
if k & 1:
|
| 83 |
+
r = _add(r, p)
|
| 84 |
+
p = _add(p, p)
|
| 85 |
+
k >>= 1
|
| 86 |
+
return r
|
| 87 |
+
|
| 88 |
+
|
| 89 |
+
def recover(msg_hash: bytes, sig: bytes) -> bytes:
|
| 90 |
+
"""The 64-byte public key (x‖y) that signed msg_hash, from a 65-byte r‖s‖v signature."""
|
| 91 |
+
if len(sig) != 65:
|
| 92 |
+
raise ValueError("a signature is 65 bytes")
|
| 93 |
+
r, s, v = int.from_bytes(sig[:32], "big"), int.from_bytes(sig[32:64], "big"), sig[64]
|
| 94 |
+
if v >= 27:
|
| 95 |
+
v -= 27
|
| 96 |
+
if v not in (0, 1) or not (0 < r < _N and 0 < s < _N) or s > _N // 2:
|
| 97 |
+
raise ValueError("not a valid signature")
|
| 98 |
+
y2 = (pow(r, 3, _P) + 7) % _P
|
| 99 |
+
y = pow(y2, (_P + 1) // 4, _P)
|
| 100 |
+
if y * y % _P != y2:
|
| 101 |
+
raise ValueError("r is not on the curve")
|
| 102 |
+
if y % 2 != v:
|
| 103 |
+
y = _P - y
|
| 104 |
+
z = int.from_bytes(msg_hash, "big")
|
| 105 |
+
rinv = pow(r, -1, _N)
|
| 106 |
+
q = _add(_mul(s * rinv % _N, (r, y)), _mul((-z * rinv) % _N, _G))
|
| 107 |
+
if q is None:
|
| 108 |
+
raise ValueError("no key")
|
| 109 |
+
return q[0].to_bytes(32, "big") + q[1].to_bytes(32, "big")
|
| 110 |
+
|
| 111 |
+
|
| 112 |
+
def checksum(addr: str) -> str:
|
| 113 |
+
a = addr.lower().removeprefix("0x")
|
| 114 |
+
h = keccak256(a.encode()).hex()
|
| 115 |
+
return "0x" + "".join(c.upper() if int(h[i], 16) >= 8 else c for i, c in enumerate(a))
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def personal_signer(message: str, signature: str) -> str:
|
| 119 |
+
"""The EIP-55 address that signed `message` with personal_sign (EIP-191)."""
|
| 120 |
+
m = message.encode()
|
| 121 |
+
digest = keccak256(b"\x19Ethereum Signed Message:\n" + str(len(m)).encode() + m)
|
| 122 |
+
pub = recover(digest, bytes.fromhex(signature.removeprefix("0x")))
|
| 123 |
+
return checksum("0x" + keccak256(pub)[-20:].hex())
|
| 124 |
+
|
| 125 |
+
|
| 126 |
+
# ── EIP-4361 ─────────────────────────────────────────────────────────────────────────────────────────────────────
|
| 127 |
+
_SIWE = re.compile(
|
| 128 |
+
r"^(?P<domain>[^\s]+) wants you to sign in with your Ethereum account:\n(?P<address>0x[0-9a-fA-F]{40})\n\n"
|
| 129 |
+
r"(?:(?P<statement>[^\n]*)\n\n)?URI: (?P<uri>[^\n]+)\nVersion: (?P<version>1)\nChain ID: (?P<chain>\d+)\n"
|
| 130 |
+
r"Nonce: (?P<nonce>[A-Za-z0-9]{8,})\nIssued At: (?P<issued>[^\n]+)(?:\nExpiration Time: (?P<expires>[^\n]+))?"
|
| 131 |
+
r"(?:\n[^\n]*)*$")
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def parse_siwe(message: str) -> dict:
|
| 135 |
+
m = _SIWE.match(message)
|
| 136 |
+
if not m:
|
| 137 |
+
raise ValueError("not a Sign-In with Ethereum message")
|
| 138 |
+
return m.groupdict()
|
tests/test_router.py
CHANGED
|
@@ -2,19 +2,24 @@
|
|
| 2 |
import asyncio
|
| 3 |
import hashlib
|
| 4 |
import json
|
|
|
|
|
|
|
| 5 |
import sys
|
|
|
|
| 6 |
from pathlib import Path
|
| 7 |
|
| 8 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "router"))
|
| 9 |
import draiml_router as R # noqa: E402
|
| 10 |
|
| 11 |
|
| 12 |
-
async def http(port, method, path, body=None, origin=""):
|
| 13 |
r, w = await asyncio.open_connection("127.0.0.1", port)
|
| 14 |
data = json.dumps(body).encode() if body is not None else b""
|
| 15 |
hdr = f"{method} {path} HTTP/1.1\r\nHost: x\r\nContent-Length: {len(data)}\r\n"
|
| 16 |
if origin:
|
| 17 |
hdr += f"Origin: {origin}\r\n"
|
|
|
|
|
|
|
| 18 |
w.write((hdr + "\r\n").encode() + data)
|
| 19 |
await w.drain()
|
| 20 |
raw = await r.read()
|
|
@@ -26,6 +31,17 @@ async def http(port, method, path, body=None, origin=""):
|
|
| 26 |
return status, headers, (json.loads(payload) if payload and headers.get("content-type", "").startswith("application/json") else payload)
|
| 27 |
|
| 28 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 29 |
def receipt(text, sha=R.BONSAI_SHA256):
|
| 30 |
return {"response_sha256": hashlib.sha256(text.encode()).hexdigest(), "model_sha256": sha, "bankml": "0.4.2"}
|
| 31 |
|
|
@@ -40,12 +56,30 @@ async def scenario(tmp_path):
|
|
| 40 |
s, h, j = await http(port, "POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]})
|
| 41 |
out["no_worker"] = (s, h.get("retry-after"))
|
| 42 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 43 |
# a worker joins with the wrong model, then the pinned one
|
| 44 |
s, _, j = await http(port, "POST", "/sharedcpu/join", {"model_sha256": "00" * 32})
|
| 45 |
out["wrong_model"] = j["ok"]
|
| 46 |
s, h, j = await http(port, "POST", "/draiml-dmind/sharedcpu/join",
|
| 47 |
-
{"model_sha256": R.BONSAI_SHA256, "share_pct": 10,
|
| 48 |
-
"engine": "browseml/draiml", "contributor": "browser"},
|
|
|
|
|
|
|
| 49 |
out["cors"] = h.get("access-control-allow-origin")
|
| 50 |
session = j["session"]
|
| 51 |
|
|
@@ -74,8 +108,14 @@ async def scenario(tmp_path):
|
|
| 74 |
s, _, comp = await c
|
| 75 |
out["client"] = (s, comp["choices"][0]["message"]["content"], comp["bankml_receipt"]["model_sha256"] == R.BONSAI_SHA256)
|
| 76 |
|
| 77 |
-
s, _, me = await http(port, "GET", "/sharedcpu/me
|
| 78 |
-
out["me"] = (me["tokens"], me["luv"])
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 79 |
s, _, ins = await http(port, "GET", "/insight/sharedcpu")
|
| 80 |
out["insight"] = (ins["workers"], ins["stats"].get("jobs_done"), ins["stats"].get("receipts_bad"))
|
| 81 |
await http(port, "POST", "/sharedcpu/leave", {"session": session})
|
|
@@ -85,6 +125,7 @@ async def scenario(tmp_path):
|
|
| 85 |
return out
|
| 86 |
|
| 87 |
|
|
|
|
| 88 |
def test_router_delegates_and_maintains(tmp_path):
|
| 89 |
out = asyncio.run(scenario(tmp_path))
|
| 90 |
assert out["no_worker"] == (503, "30")
|
|
@@ -94,6 +135,10 @@ def test_router_delegates_and_maintains(tmp_path):
|
|
| 94 |
assert out["max_tokens_capped"] == R.MAX_TOKENS
|
| 95 |
assert out["credited"] == "7"
|
| 96 |
assert out["client"] == (200, "Rest, ice and gentle movement.", True)
|
| 97 |
-
assert out["
|
|
|
|
|
|
|
|
|
|
|
|
|
| 98 |
assert out["insight"] == (1, 1, 1)
|
| 99 |
assert out["after_leave"] == 0
|
|
|
|
| 2 |
import asyncio
|
| 3 |
import hashlib
|
| 4 |
import json
|
| 5 |
+
import shutil
|
| 6 |
+
import subprocess
|
| 7 |
import sys
|
| 8 |
+
from datetime import datetime, timezone
|
| 9 |
from pathlib import Path
|
| 10 |
|
| 11 |
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "router"))
|
| 12 |
import draiml_router as R # noqa: E402
|
| 13 |
|
| 14 |
|
| 15 |
+
async def http(port, method, path, body=None, origin="", token=""):
|
| 16 |
r, w = await asyncio.open_connection("127.0.0.1", port)
|
| 17 |
data = json.dumps(body).encode() if body is not None else b""
|
| 18 |
hdr = f"{method} {path} HTTP/1.1\r\nHost: x\r\nContent-Length: {len(data)}\r\n"
|
| 19 |
if origin:
|
| 20 |
hdr += f"Origin: {origin}\r\n"
|
| 21 |
+
if token:
|
| 22 |
+
hdr += f"Authorization: Bearer {token}\r\n"
|
| 23 |
w.write((hdr + "\r\n").encode() + data)
|
| 24 |
await w.drain()
|
| 25 |
raw = await r.read()
|
|
|
|
| 31 |
return status, headers, (json.loads(payload) if payload and headers.get("content-type", "").startswith("application/json") else payload)
|
| 32 |
|
| 33 |
|
| 34 |
+
import pytest # noqa: E402
|
| 35 |
+
|
| 36 |
+
CAST = shutil.which("cast") or str(Path.home() / ".foundry/bin/cast")
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
def cast_sign(msg):
|
| 40 |
+
key = "0xac0974bec39a17e36ba4a6b4d238ff944bacb478cbed5efcae784d7bf4f2ff80" # anvil's public test key 0
|
| 41 |
+
return subprocess.run([CAST, "wallet", "sign", "--private-key", key, msg], capture_output=True, text=True,
|
| 42 |
+
check=True).stdout.strip()
|
| 43 |
+
|
| 44 |
+
|
| 45 |
def receipt(text, sha=R.BONSAI_SHA256):
|
| 46 |
return {"response_sha256": hashlib.sha256(text.encode()).hexdigest(), "model_sha256": sha, "bankml": "0.4.2"}
|
| 47 |
|
|
|
|
| 56 |
s, h, j = await http(port, "POST", "/v1/chat/completions", {"messages": [{"role": "user", "content": "hi"}]})
|
| 57 |
out["no_worker"] = (s, h.get("retry-after"))
|
| 58 |
|
| 59 |
+
# login333 · drAIML: sign in with a wallet (anvil's public test key 0, signed by Foundry's cast)
|
| 60 |
+
addr = "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266"
|
| 61 |
+
_, _, n = await http(port, "GET", f"/auth/nonce?address={addr}")
|
| 62 |
+
issued = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
|
| 63 |
+
msg = (f"pythai-draiml.static.hf.space wants you to sign in with your Ethereum account:\n{addr}\n\n"
|
| 64 |
+
f"Sign in to drAIML.dmind.\n\nURI: https://pythai-draiml.static.hf.space\nVersion: 1\nChain ID: 1\n"
|
| 65 |
+
f"Nonce: {n['nonce']}\nIssued At: {issued}")
|
| 66 |
+
sig = cast_sign(msg)
|
| 67 |
+
_, _, bad = await http(port, "POST", "/auth/verify", {"message": msg.replace("Chain ID: 1", "Chain ID: 5"), "signature": sig})
|
| 68 |
+
out["wrong_chain"] = bad["ok"]
|
| 69 |
+
_, _, v = await http(port, "POST", "/auth/verify", {"message": msg, "signature": sig})
|
| 70 |
+
out["signin"] = v.get("address")
|
| 71 |
+
token = v["token"]
|
| 72 |
+
_, _, replay = await http(port, "POST", "/auth/verify", {"message": msg, "signature": sig})
|
| 73 |
+
out["replay"] = replay["ok"]
|
| 74 |
+
|
| 75 |
# a worker joins with the wrong model, then the pinned one
|
| 76 |
s, _, j = await http(port, "POST", "/sharedcpu/join", {"model_sha256": "00" * 32})
|
| 77 |
out["wrong_model"] = j["ok"]
|
| 78 |
s, h, j = await http(port, "POST", "/draiml-dmind/sharedcpu/join",
|
| 79 |
+
{"model_sha256": R.BONSAI_SHA256, "share_pct": 10,
|
| 80 |
+
"engine": "browseml/draiml", "contributor": "browser"},
|
| 81 |
+
origin="https://pythai-draiml.static.hf.space", token=token)
|
| 82 |
+
out["join_wallet"] = j["wallet"]
|
| 83 |
out["cors"] = h.get("access-control-allow-origin")
|
| 84 |
session = j["session"]
|
| 85 |
|
|
|
|
| 108 |
s, _, comp = await c
|
| 109 |
out["client"] = (s, comp["choices"][0]["message"]["content"], comp["bankml_receipt"]["model_sha256"] == R.BONSAI_SHA256)
|
| 110 |
|
| 111 |
+
s, _, me = await http(port, "GET", "/sharedcpu/me", token=token)
|
| 112 |
+
out["me"] = (me["tokens"], me["luv"], me["available_wei"])
|
| 113 |
+
_, _, c = await http(port, "POST", "/sharedcpu/claim", token=token)
|
| 114 |
+
out["claim"] = (c["ok"], c["claim"]["luv_wei"], c["available_wei"], c["claimed_wei"])
|
| 115 |
+
_, _, c2 = await http(port, "POST", "/sharedcpu/claim", token=token)
|
| 116 |
+
out["claim_again"] = c2["ok"]
|
| 117 |
+
_, _, anon = await http(port, "POST", "/sharedcpu/claim")
|
| 118 |
+
out["claim_anon"] = anon["ok"]
|
| 119 |
s, _, ins = await http(port, "GET", "/insight/sharedcpu")
|
| 120 |
out["insight"] = (ins["workers"], ins["stats"].get("jobs_done"), ins["stats"].get("receipts_bad"))
|
| 121 |
await http(port, "POST", "/sharedcpu/leave", {"session": session})
|
|
|
|
| 125 |
return out
|
| 126 |
|
| 127 |
|
| 128 |
+
@pytest.mark.skipif(not Path(CAST).exists(), reason="needs Foundry's cast to sign the test login")
|
| 129 |
def test_router_delegates_and_maintains(tmp_path):
|
| 130 |
out = asyncio.run(scenario(tmp_path))
|
| 131 |
assert out["no_worker"] == (503, "30")
|
|
|
|
| 135 |
assert out["max_tokens_capped"] == R.MAX_TOKENS
|
| 136 |
assert out["credited"] == "7"
|
| 137 |
assert out["client"] == (200, "Rest, ice and gentle movement.", True)
|
| 138 |
+
assert out["wrong_chain"] is False and out["replay"] is False
|
| 139 |
+
assert out["signin"] == "0xf39Fd6e51aad88F6F4ce6aB8827279cffFb92266" == out["join_wallet"]
|
| 140 |
+
assert out["me"] == (7, "0.000000000000000007", "7")
|
| 141 |
+
assert out["claim"] == (True, "7", "0", "7")
|
| 142 |
+
assert out["claim_again"] is False and out["claim_anon"] is False
|
| 143 |
assert out["insight"] == (1, 1, 1)
|
| 144 |
assert out["after_leave"] == 0
|