forked from smilewithkhushi/simple-zk-app
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
86 lines (72 loc) · 2.52 KB
/
server.js
File metadata and controls
86 lines (72 loc) · 2.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
const http = require("http");
const fs = require("fs");
const path = require("path");
const { execSync } = require("child_process");
const PORT = 3000;
const ROOT = __dirname;
function updateProverToml(x, y) {
const content = `x = "${x}"\ny = "${y}"\n`;
fs.writeFileSync(path.join(ROOT, "Prover.toml"), content);
}
function runProof(x, y) {
updateProverToml(x, y);
const steps = [];
try {
execSync("nargo execute", { cwd: ROOT, stdio: "pipe" });
steps.push({ name: "nargo execute", status: "ok", msg: "Witness generated" });
} catch (e) {
steps.push({ name: "nargo execute", status: "fail", msg: e.stderr?.toString() || e.message });
return { success: false, steps };
}
try {
execSync(
"bb prove -b ./target/simple_circuit.json -w ./target/simple_circuit.gz -o ./target",
{ cwd: ROOT, stdio: "pipe" }
);
steps.push({ name: "bb prove", status: "ok", msg: "Proof generated" });
} catch (e) {
steps.push({ name: "bb prove", status: "fail", msg: e.stderr?.toString() || e.message });
return { success: false, steps };
}
try {
execSync("bb verify -k ./target/vk -p ./target/proof", { cwd: ROOT, stdio: "pipe" });
steps.push({ name: "bb verify", status: "ok", msg: "Proof verified!" });
} catch (e) {
steps.push({ name: "bb verify", status: "fail", msg: e.stderr?.toString() || e.message });
return { success: false, steps };
}
return { success: true, steps };
}
const server = http.createServer((req, res) => {
if (req.method === "GET" && req.url === "/") {
const html = fs.readFileSync(path.join(ROOT, "index.html"));
res.writeHead(200, { "Content-Type": "text/html" });
return res.end(html);
}
if (req.method === "POST" && req.url === "/prove") {
let body = "";
req.on("data", (chunk) => (body += chunk));
req.on("end", () => {
let x, y;
try {
({ x, y } = JSON.parse(body));
} catch {
res.writeHead(400, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "Invalid JSON" }));
}
if (!x || !y) {
res.writeHead(400, { "Content-Type": "application/json" });
return res.end(JSON.stringify({ error: "x and y are required" }));
}
const result = runProof(x, y);
res.writeHead(200, { "Content-Type": "application/json" });
res.end(JSON.stringify(result));
});
return;
}
res.writeHead(404);
res.end("Not found");
});
server.listen(PORT, () => {
console.log(`ZK Proof demo running at http://localhost:${PORT}`);
});