brainchain-worker-phala 0.1.0 → 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "brainchain-worker-phala",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Run a BrainChain worker in a Phala Cloud enclave: a key that never leaves the enclave, and every task answered through Phala's confidential AI with its enclave receipt checked.",
5
5
  "license": "MIT",
6
6
  "author": "BrainChain",
@@ -11,11 +11,29 @@
11
11
  "directory": "phala"
12
12
  },
13
13
  "bugs": "https://github.com/usebrainchain/brainchain-worker/issues",
14
- "keywords": ["brainchain", "phala", "tee", "dstack", "agent", "worker"],
14
+ "keywords": [
15
+ "brainchain",
16
+ "phala",
17
+ "tee",
18
+ "dstack",
19
+ "agent",
20
+ "worker"
21
+ ],
15
22
  "type": "module",
16
- "files": ["start.mjs", "agent.mjs", "lib.mjs", "README.md", "docker-compose.yml"],
17
- "engines": { "node": ">=22.12" },
18
- "scripts": { "test": "node --test" },
23
+ "files": [
24
+ "start.mjs",
25
+ "agent.mjs",
26
+ "lib.mjs",
27
+ "README.md",
28
+ "docker-compose.yml",
29
+ "npm-shrinkwrap.json"
30
+ ],
31
+ "engines": {
32
+ "node": ">=22.12"
33
+ },
34
+ "scripts": {
35
+ "test": "node --test"
36
+ },
19
37
  "dependencies": {
20
38
  "@phala/aci-verifier": "0.11.1",
21
39
  "@phala/dstack-sdk": "0.6.0",
package/start.mjs CHANGED
@@ -1,9 +1,10 @@
1
1
  #!/usr/bin/env node
2
2
  // Runs a BrainChain worker inside a Phala Cloud CVM. The wallet key is derived by the enclave and handed to the worker
3
- // on a pipe, so it is in no file, no environment and no log. On first start it asks the testnet gas drip for gas
4
- // (testnet only) and joins once; then it runs, doing each task it is hired for with agent.mjs.
5
- import { spawn } from "node:child_process";
6
- import { existsSync, mkdirSync, writeFileSync } from "node:fs";
3
+ // through a named pipe, so it is in no file, no environment and no log. On testnet it asks the gas drip for gas until
4
+ // it has had some, and it joins once; then it runs, doing each task it is hired for with agent.mjs.
5
+ import { execFileSync, spawn } from "node:child_process";
6
+ import { constants, existsSync, mkdirSync, openSync, closeSync, unlinkSync, writeFileSync } from "node:fs";
7
+ import { open } from "node:fs/promises";
7
8
  import { createRequire } from "node:module";
8
9
  import { homedir } from "node:os";
9
10
  import { dirname, join } from "node:path";
@@ -44,32 +45,53 @@ const state = join(homedir(), ".brainchain-worker-phala");
44
45
  mkdirSync(state, { recursive: true, mode: 0o700 });
45
46
  const marker = (name) => join(state, `${name}-${s.network}-${address.toLowerCase()}`);
46
47
 
47
- // The worker reads the key from its stdin and keeps it out of the command it runs.
48
+ // The worker reads the key from a named pipe and keeps it out of the command it runs. Node gives a child a socket, not
49
+ // a pipe, for its stdin, and a socket cannot be opened by path, so the key goes through a FIFO only the worker reads.
50
+ let pipes = 0;
48
51
  function run(args) {
52
+ const fifo = join(existsSync("/dev/shm") ? "/dev/shm" : state, `key-${process.pid}-${(pipes += 1)}`);
53
+ execFileSync("mkfifo", ["-m", "600", fifo]);
49
54
  const child = spawn(process.execPath, [worker, ...args], {
50
- stdio: ["pipe", "inherit", "inherit"],
51
- env: { ...process.env, BRAINCHAIN_NETWORK: s.network, BRAINCHAIN_WORKER_KEY_FILE: "/dev/stdin" },
55
+ stdio: ["ignore", "inherit", "inherit"],
56
+ env: { ...process.env, BRAINCHAIN_NETWORK: s.network, BRAINCHAIN_WORKER_KEY_FILE: fifo },
57
+ });
58
+ const exited = new Promise((resolve) => child.on("exit", (code, signal) => resolve(code ?? (signal ? 1 : 0))));
59
+ // Opening the write end waits for the worker to open the read end. A worker that exits first never will, so the
60
+ // read end is opened here, which lets the write go into a pipe nobody reads, and the FIFO is removed either way.
61
+ const handed = open(fifo, "w").then(async (fd) => {
62
+ await fd.writeFile(`${key}\n`).catch(() => {});
63
+ await fd.close();
64
+ });
65
+ exited.then(() => {
66
+ try {
67
+ closeSync(openSync(fifo, constants.O_RDONLY | constants.O_NONBLOCK));
68
+ } catch {
69
+ // Gone already: the key was handed over and the FIFO removed.
70
+ }
71
+ });
72
+ handed.finally(() => {
73
+ try {
74
+ unlinkSync(fifo);
75
+ } catch {
76
+ // Removed by the other path.
77
+ }
52
78
  });
53
- child.stdin.end(`${key}\n`);
54
79
  const forward = (signal) => child.kill(signal);
55
80
  process.on("SIGTERM", forward).on("SIGINT", forward);
56
- return new Promise((resolve) => {
57
- child.on("exit", (code, signal) => {
58
- process.off("SIGTERM", forward).off("SIGINT", forward);
59
- resolve(code ?? (signal ? 1 : 0));
60
- });
61
- });
81
+ return exited.finally(() => process.off("SIGTERM", forward).off("SIGINT", forward));
62
82
  }
63
83
 
64
- // The drip serves each address once, so it is asked once.
65
- if (s.network === "testnet" && !existsSync(marker("drip"))) {
84
+ // The drip serves each address once: a 200 sent it, a 409 says it was sent before or the address holds enough. Anything
85
+ // else, such as a paused drip, is asked again before the next try at joining.
86
+ async function drip() {
87
+ if (s.network !== "testnet" || existsSync(marker("drip"))) return;
66
88
  const response = await fetch("https://brain.testnet.usebrainchain.com/testnet/gas", {
67
89
  method: "POST",
68
90
  headers: { "content-type": "application/json" },
69
91
  body: JSON.stringify({ address }),
70
- }).catch((error) => ({ status: error.message, text: async () => "" }));
92
+ }).catch((error) => ({ status: 0, text: async () => error.message }));
71
93
  console.log(`Testnet gas drip: ${response.status} ${(await response.text()).slice(0, 200)}`);
72
- writeFileSync(marker("drip"), new Date().toISOString());
94
+ if (response.status === 200 || response.status === 409) writeFileSync(marker("drip"), new Date().toISOString());
73
95
  }
74
96
 
75
97
  // At most once per amount: running it again after a partial move could buy the stake twice.
@@ -82,6 +104,7 @@ if (s.fundUsdc && !existsSync(marker(`fund-${s.fundUsdc}`))) {
82
104
 
83
105
  // Joined once. A worker BrainChain refused is not sent in again by a restart: on mainnet that would forfeit another bond.
84
106
  while (!existsSync(marker("joined"))) {
107
+ await drip();
85
108
  const code = await run(joinArgs(s));
86
109
  if (code === 0) {
87
110
  writeFileSync(marker("joined"), new Date().toISOString());