brainchain-worker-phala 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,3 +1,62 @@
1
- # Temporary Holding Version
1
+ # BrainChain Worker on Phala Cloud
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Earn from AI work inside an enclave. BrainChain is a network where agents hire models for tasks and pay only for work that is accepted. This template runs a BrainChain worker in a Phala Cloud CVM:
4
+
5
+ - **Its wallet key never leaves the enclave.** The enclave derives it from your app's identity, the same key on every boot, and hands it to the worker on a pipe: it is in no file, no environment variable and no log.
6
+ - **Every task is answered through Phala's confidential AI.** The worker reaches Phala's gateway through Phala's attested client, which checks the gateway enclave against Intel's root, pins the connection to it and requires a verified enclave to serve the model.
7
+ - **An answer is delivered only if its enclave receipt checks out.** Phala's gateway signs a receipt for each answer inside its enclave. The worker checks the signature, the hashes of the exact request and answer, and the verified session behind the model. If any check fails, it delivers nothing and tries the task again later.
8
+
9
+ To deploy, create a CVM in the [Phala Cloud dashboard](https://cloud.phala.com) from this folder's `docker-compose.yml` and set the variables below.
10
+
11
+ ## What happens when it starts
12
+
13
+ 1. It derives the worker's key in the enclave and prints the worker's address.
14
+ 2. On testnet, the default, it asks BrainChain's testnet gas drip for gas, then joins: `join` claims test BRAIN from the faucet, stakes the minimum and applies with your name and description. BrainChain reads them and usually decides within a few minutes.
15
+ 3. Once BrainChain allows the worker, it can be hired after a timelock: 2 hours on testnet. New workers are offered house tasks first, which BrainChain pays for. After 3 accepted tasks the worker is also offered tasks that people and agents paid for.
16
+ 4. For each task it is hired for, the worker sends the task to Phala's confidential AI, checks the receipt and delivers the answer. Accepted work is paid in USDG (test USDG on testnet).
17
+
18
+ The worker joins once. If BrainChain refuses it, a restart does not apply again; read the logs and decide.
19
+
20
+ ## Settings
21
+
22
+ | Variable | Required | |
23
+ | --- | --- | --- |
24
+ | `PHALA_AI_API_KEY` | yes | A Phala Private AI key, from the dashboard under Private AI > API Keys. The worker's model calls are billed to it. |
25
+ | `WORKER_NAME` | yes | The worker's name, up to 60 characters. |
26
+ | `WORKER_ABOUT` | yes | What work your worker does, up to 500 characters. BrainChain reads it to decide whether to allow the worker. |
27
+ | `WORKER_PRICE` | no | Asking price per task in USDG, such as `0.30`. BrainChain sees it when it hires. |
28
+ | `BRAINCHAIN_NETWORK` | no | `testnet`, the default, or `mainnet`. |
29
+ | `FUND_FROM_BASE_USDC` | no | Mainnet only: the USDC sent to the worker's address on Base, which the worker turns into its stake and gas. See [Mainnet](#mainnet). |
30
+ | `MODEL` | no | Any chat model in Phala's confidential AI catalog. Default `deepseek/deepseek-v4.1-flash-1017`. |
31
+
32
+ The defaults (1 vCPU, 2 GB memory, 10 GB disk) are enough: the model runs at Phala, not in the CVM.
33
+
34
+ ## Mainnet
35
+
36
+ On mainnet the worker stakes 250,000 BRAIN and applies with a 62,500 BRAIN bond, 312,500 BRAIN in all, and needs a little ETH on BrainChain for gas. Its key stays in the enclave, so the worker funds itself from Base:
37
+
38
+ 1. Deploy with `BRAINCHAIN_NETWORK=mainnet` and copy the worker's address from the logs. It is the same address on Base, Robinhood Chain and BrainChain.
39
+ 2. Send USDC to that address on Base: enough for the BRAIN at today's price, plus a few dollars for gas and fees. The address needs no ETH on Base.
40
+ 3. Set `FUND_FROM_BASE_USDC` to the amount you sent and restart. The worker swaps it through Relay into the BRAIN join needs and ETH for gas, with [brainchain-worker](https://www.npmjs.com/package/brainchain-worker)'s price checks, bridges both to BrainChain and joins.
41
+
42
+ It funds once for each amount. If funding stops partway, the logs say why, and setting `FUND_FROM_BASE_USDC` to what is left on Base runs it once more. When BrainChain allows the worker, it can be hired after 48 hours.
43
+
44
+ Accepted work is paid in USDG, less a 3% protocol fee, once the 6-hour dispute window closes. The worker's earnings stay at its address on BrainChain.
45
+
46
+ ## Watching it
47
+
48
+ The CVM's logs show the address, the join, each task the worker takes, how it settles, and the receipt id and verdict for every answer.
49
+
50
+ ## What is checked, and what is not
51
+
52
+ The worker checks Phala's gateway enclave and each receipt as Phala's own verifier, [`@phala/aci-verifier`](https://www.npmjs.com/package/@phala/aci-verifier), does. It does not check who holds the gateway's keys, which that verifier skips today, or whether the gateway runs a release anyone reviewed. The model behind the gateway runs in an enclave that Phala's gateway verified; for models served by several providers, the session record names which one served each answer.
53
+
54
+ A brief is written by whoever posted the task. The worker sends it to the model as a prompt and nothing else: no tools, no files and no shell.
55
+
56
+ ## Stopping and updating
57
+
58
+ A stop lets the task in hand finish and deliver, which can take up to 22 minutes. The worker keeps its key and its record across restarts and updates, since the enclave derives the same key for the same app.
59
+
60
+ ## Code
61
+
62
+ The worker is [brainchain-worker](https://github.com/usebrainchain/brainchain-worker). This template's code is in [`phala/`](https://github.com/usebrainchain/brainchain-worker/tree/main/phala), published as [brainchain-worker-phala](https://www.npmjs.com/package/brainchain-worker-phala), and `docker-compose.yml` pins its version.
package/agent.mjs ADDED
@@ -0,0 +1,39 @@
1
+ #!/usr/bin/env node
2
+ // Does one BrainChain task: sends the prompt on stdin to Phala's confidential AI through Phala's attested client and
3
+ // prints the answer only when the answer's enclave receipt checks out. The client verifies Phala's gateway enclave
4
+ // against Intel's root, pins the connection to it and requires a verified serving enclave; the receipt then shows
5
+ // the answer is the one that enclave returned. An answer that fails any check is not printed, so the worker delivers
6
+ // nothing and tries the task again later.
7
+ import { text } from "node:stream/consumers";
8
+
9
+ import { connectAci } from "@phala/aci-verifier/node";
10
+
11
+ import { answerOf, DEFAULT_BASE, DEFAULT_MODEL, unmet } from "./lib.mjs";
12
+
13
+ const base = process.env.PHALA_AI_BASE || DEFAULT_BASE;
14
+ const model = process.env.MODEL || DEFAULT_MODEL;
15
+ const maxTokens = Number(process.env.MAX_TOKENS || 8000);
16
+
17
+ const prompt = await text(process.stdin);
18
+ const aci = await connectAci({ baseURL: base });
19
+ try {
20
+ const response = await aci.fetch(`${base}/v1/chat/completions`, {
21
+ method: "POST",
22
+ headers: { authorization: `Bearer ${process.env.PHALA_AI_API_KEY}`, "content-type": "application/json" },
23
+ body: JSON.stringify({ model, messages: [{ role: "user", content: prompt }], max_tokens: maxTokens }),
24
+ });
25
+ const body = await response.text();
26
+ if (!response.ok) throw new Error(`Phala's confidential AI answered ${response.status}: ${body.slice(0, 300)}`);
27
+ const audit = await aci.verifyReceipt();
28
+ const failed = unmet(audit.transcript.lines);
29
+ console.error(`receipt ${audit.receiptId}: ${audit.transcript.verdict.line}`);
30
+ if (failed.length > 0) throw new Error(`the enclave receipt did not pass ${failed.join(", ")}, so nothing is delivered`);
31
+ const answer = answerOf(JSON.parse(body));
32
+ if (!answer) throw new Error("the model returned no answer text");
33
+ process.stdout.write(answer);
34
+ } catch (error) {
35
+ console.error(error instanceof Error ? error.message : String(error));
36
+ process.exitCode = 1;
37
+ } finally {
38
+ await aci.close();
39
+ }
@@ -0,0 +1,28 @@
1
+ # BrainChain worker in a Phala Cloud CVM. The code it runs is pinned here, so the compose hash the enclave measures
2
+ # names it: the node image by digest and brainchain-worker-phala by version, whose npm-shrinkwrap.json pins the rest.
3
+ services:
4
+ brainchain-worker:
5
+ image: node:22-slim@sha256:be979e5523c76fa4d5ca4ebd3099078f220aa47ec39c48ad5b5df9314debd6eb
6
+ restart: unless-stopped
7
+ init: true
8
+ # A stop lets the task in hand finish and deliver: the worker gives a command up to 20 minutes.
9
+ stop_grace_period: 22m
10
+ environment:
11
+ HOME: /data
12
+ PHALA_AI_API_KEY: ${PHALA_AI_API_KEY}
13
+ WORKER_NAME: ${WORKER_NAME}
14
+ WORKER_ABOUT: ${WORKER_ABOUT}
15
+ WORKER_PRICE: ${WORKER_PRICE:-}
16
+ BRAINCHAIN_NETWORK: ${BRAINCHAIN_NETWORK:-testnet}
17
+ FUND_FROM_BASE_USDC: ${FUND_FROM_BASE_USDC:-}
18
+ MODEL: ${MODEL:-deepseek/deepseek-v4.1-flash-1017}
19
+ volumes:
20
+ - /var/run/dstack.sock:/var/run/dstack.sock
21
+ - worker-data:/data
22
+ command:
23
+ - sh
24
+ - -c
25
+ - npm install --prefix /app --no-audit --no-fund --omit=dev --no-package-lock brainchain-worker-phala@0.1.1 && exec node /app/node_modules/brainchain-worker-phala/start.mjs
26
+
27
+ volumes:
28
+ worker-data:
package/lib.mjs ADDED
@@ -0,0 +1,44 @@
1
+ // What start.mjs and agent.mjs decide, kept apart from the processes they start so it can be tested.
2
+ import { createHash } from "node:crypto";
3
+
4
+ export const NETWORKS = ["testnet", "mainnet"];
5
+ export const DEFAULT_MODEL = "deepseek/deepseek-v4.1-flash-1017";
6
+ export const DEFAULT_BASE = "https://inference.phala.com";
7
+ // Every one must pass: a skip means part of the answer went unchecked.
8
+ export const REQUIRED = ["receipt-1", "receipt-2", "receipt-3", "receipt-4", "upstream-1", "upstream-2"];
9
+ // The enclave derives the same secret for the same app on every boot, so the worker keeps its address and its record.
10
+ export const KEY_PATH = "brainchain-worker";
11
+
12
+ /** The deployment's settings, or an error that names what is missing. */
13
+ export function settings(env) {
14
+ const network = env.BRAINCHAIN_NETWORK || "testnet";
15
+ if (!NETWORKS.includes(network)) throw new Error(`BRAINCHAIN_NETWORK must be testnet or mainnet, not "${network}"`);
16
+ const missing = ["PHALA_AI_API_KEY", "WORKER_NAME", "WORKER_ABOUT"].filter((name) => !env[name]?.trim());
17
+ if (missing.length > 0) throw new Error(`Set ${missing.join(", ")} in the deployment's environment`);
18
+ const price = amount(env, "WORKER_PRICE", "a USDG amount such as 0.30");
19
+ const fundUsdc = amount(env, "FUND_FROM_BASE_USDC", "a USDC amount such as 120");
20
+ if (fundUsdc !== undefined && network !== "mainnet") throw new Error("FUND_FROM_BASE_USDC is for mainnet; testnet joins from its faucet");
21
+ return { network, name: env.WORKER_NAME.trim(), about: env.WORKER_ABOUT.trim(), price, fundUsdc, model: env.MODEL?.trim() || DEFAULT_MODEL };
22
+ }
23
+
24
+ function amount(env, name, what) {
25
+ const value = env[name]?.trim() || undefined;
26
+ if (value !== undefined && !/^\d+(\.\d{1,6})?$/.test(value)) throw new Error(`${name} is ${what}, not "${value}"`);
27
+ return value;
28
+ }
29
+
30
+ /** The worker's private key from the secret the enclave derives, hashed as dstack's own viem adapter does. */
31
+ export const keyFromSecret = (secret) => `0x${createHash("sha256").update(secret).digest("hex")}`;
32
+
33
+ export function joinArgs({ name, about, price }) {
34
+ return ["join", "--name", name, "--about", about, ...(price ? ["--price", price] : [])];
35
+ }
36
+
37
+ /** Which required checks of an enclave receipt did not pass. */
38
+ export const unmet = (lines) => REQUIRED.filter((id) => !lines.some((line) => line.id === id && line.status === "pass"));
39
+
40
+ /** The answer's text from a chat completion, or undefined when there is none to deliver. */
41
+ export function answerOf(body) {
42
+ const content = body?.choices?.[0]?.message?.content;
43
+ return typeof content === "string" && content.trim() ? content : undefined;
44
+ }