UNPKG

nano-pow

Version:

Proof-of-work generation and validation with WebGPU/WebGL/WASM for Nano cryptocurrency.

323 lines (317 loc) 10.4 kB
#!/usr/bin/env node //! SPDX-FileCopyrightText: 2025 Chris Duncan <chris@codecow.com> //! SPDX-License-Identifier: GPL-3.0-or-later import { Logger, isHex32, isHex8 } from "nano-pow/utils"; import { hash } from "node:crypto"; import { readFile, writeFile } from "node:fs/promises"; import * as http from "node:http"; import { homedir } from "node:os"; import { join } from "node:path"; import { launch } from "puppeteer"; process.title = "NanoPow Server"; await writeFile(`${homedir()}/.nano-pow/server.pid`, `${process.pid} `); const logger = new Logger(); const MAX_CONNECTIONS = 1024; const MAX_HEADER_COUNT = 32; const MAX_IDLE_TIME = 3e4; const MAX_REQUEST_COUNT = 10; const MAX_REQUEST_SIZE = 256; const MAX_REQUEST_TIME = 6e4; const CONFIG = { DEBUG: false, EFFORT: 4, PORT: 5040 }; const configPatterns = { DEBUG: { r: /^[ \t]*debug[ \t]*(true|false)[ \t]*(#.*)?$/i, v: (b) => ["1", "true", "yes"].includes(b) }, EFFORT: { r: /^[ \t]*effort[ \t]*(\d{1,2})[ \t]*(#.*)?$/i, v: (n) => +n }, PORT: { r: /^[ \t]*port[ \t]*(\d{1,5})[ \t]*(#.*)?$/i, v: (n) => +n } }; async function loadConfig() { let configFile = ""; try { configFile = await readFile(join(homedir(), ".nano-pow", "config"), "utf-8"); } catch { } if (configFile.length > 0) { for (const line of configFile.split("\n")) { for (const [k, { r, v }] of Object.entries(configPatterns)) { const m = r.exec(line); if (m) CONFIG[k] = v(m[1]); } } } CONFIG.DEBUG = ["1", "true", "yes"].includes(process.env.NANO_POW_DEBUG ?? "") || CONFIG.DEBUG; CONFIG.EFFORT = +(process.env.NANO_POW_EFFORT ?? "") || CONFIG.EFFORT; CONFIG.PORT = process.send ? 0 : +(process.env.NANO_POW_PORT ?? "") || CONFIG.PORT; logger.isEnabled = CONFIG.DEBUG; if (configFile.length === 0) ; } await loadConfig(); const NanoPow = await readFile(new URL("../index.js", import.meta.url), "utf-8"); const browser = await launch({ handleSIGHUP: false, handleSIGINT: false, handleSIGTERM: false, headless: true, args: [ "--disable-vulkan-surface", "--enable-features=Vulkan,DefaultANGLEVulkan,VulkanFromANGLE", "--enable-gpu", "--enable-unsafe-webgpu" ] }); const page = await browser.newPage(); const src = `${NanoPow};window.NanoPow=NanoPow;`; const enc = `sha256-${hash("sha256", src, "base64")}`; const body = ` <!DOCTYPE html> <link rel="icon" href="data:,"> <meta http-equiv="Content-Security-Policy" content="default-src 'none'; base-uri 'none'; form-action 'none'; script-src '${enc}' 'wasm-unsafe-eval'; worker-src blob: https://nanopow.invalid;"> <script type="module">${src}</script> `; await page.setRequestInterception(true); page.on("request", (req) => { if (req.isInterceptResolutionHandled()) return; if (req.url() === "https://nanopow.invalid/") { req.respond({ status: 200, contentType: "text/html", body }); } else { req.continue(); } }); page.on("console", (msg) => logger.log(msg.text())); await page.goto("https://nanopow.invalid/"); let NanoPowHandle = await page.waitForFunction(async () => { await window.navigator.gpu.requestAdapter(); return window.NanoPow; }); const requests = /* @__PURE__ */ new Map(); setInterval(() => { const now = Date.now(); for (const [ip, { time }] of requests) { if (time < now - MAX_REQUEST_TIME) { requests.delete(ip); } } }, MAX_REQUEST_TIME); async function work(data) { let resBody = "request failed"; if (data == null || typeof data !== "object") { throw new Error(resBody); } if (Object.getPrototypeOf(data) !== Object.prototype) { throw new Error(resBody); } const dataParsed = data; let { action, hash: hash2, work: work2, difficulty } = dataParsed; if (action !== "work_generate" && action !== "work_validate") { throw new Error(resBody); } resBody = `${action} failed`; if (!isHex32(hash2)) { throw new Error(resBody); } if (difficulty !== void 0 && !isHex8(difficulty)) { throw new Error(resBody); } if (action === "work_validate") { if (!isHex8(work2)) { throw new Error(resBody); } } else { let f2 = function(n) { if (false) throw new Error(); }; var f = f2; f2(work2); } const options = { api: "webgpu", debug: CONFIG.DEBUG, effort: CONFIG.EFFORT, difficulty }; try { const result = action === "work_validate" ? await page.evaluate((n, w, h, o) => { if (n == null) throw new Error("NanoPow not found"); return n.work_validate(w, h, o); }, NanoPowHandle, work2, hash2, options) : await page.evaluate((n, h, o) => { if (n == null) throw new Error("NanoPow not found"); return n.work_generate(h, o); }, NanoPowHandle, hash2, options); resBody = JSON.stringify(result); return resBody; } catch (err) { throw new Error(resBody); } } function get(res) { res.writeHead(200, { "Content-Type": "text/plain" }).end(`Usage: Send POST request to server URL to generate or validate Nano proof-of-work Generate work for a HASH with an optional DIFFICULTY: curl -d '{ "action": "work_generate", "hash": HASH, "difficulty": DIFFICULTY }' nanopow.example.com Validate WORK previously calculated for a HASH with an optional DIFFICULTY: curl -d '{ "action": "work_validate", "work": WORK, "hash": HASH, "difficulty": DIFFICULTY }' nanopow.example.com HASH is a big-endian 64-character hexadecimal string. WORK is little-endian 16-character hexadecimal string. DIFFICULTY is an optional 16-character hexadecimal string (default: FFFFFFF800000000) String variables must be enclosed in double-quotes to be valid JSON. Report bugs: <bug-nano-pow@codecow.com> Full documentation: <https://www.npmjs.com/package/nano-pow> `); } async function post(res, reqData) { const resHeaders = { "Content-Type": "application/json" }; let resStatusCode = 500; let resBody = "request failed"; try { resBody = await work(JSON.parse(Buffer.concat(reqData).toString())); resStatusCode = 200; } catch (err) { resBody = err.message; resStatusCode = 400; } finally { res.writeHead(resStatusCode, resHeaders).end(resBody); } } function getIp(req) { const xff = req.headers["x-forwarded-for"]; const ip = typeof xff === "string" ? xff.split(",")[0].trim().replace(/^::ffff:/, "") : req.socket.remoteAddress; return ip; } function isRateLimited(ip) { if (ip === "127.0.0.1" || ip === "::1" || process.send) { return false; } const client = requests.get(ip); if (client && client.tokens-- <= 0) { return true; } if (Date.now() - MAX_REQUEST_TIME > (client?.time ?? 0)) { requests.set(ip, { tokens: MAX_REQUEST_COUNT, time: Date.now() }); } return false; } function listen() { if (process.channel) { process.on("message", async (msg) => { if (typeof msg === "object" && msg != null && "type" in msg && typeof msg.type === "string" && "data" in msg && typeof msg.data === "string") { if (msg.type === "ipc") { const data = JSON.parse(msg.data); try { const result = await work(data); process.send?.({ type: "ipc", data: result }); } catch (err) { process.send?.({ type: "ipc", data: err.stack }); } } } }); process.send?.({ type: "listening", data: "ipc" }); } else { server.listen(CONFIG.PORT, "127.0.0.1", () => { const address = server.address(); if (address == null) { } else if (typeof address === "string") { process.send?.({ type: "listening", data: address }); } else { CONFIG.PORT = address.port; process.send?.({ type: "listening", data: address.port }); } }); } } async function readIncomingMessage(req) { return new Promise((resolve, reject) => { const contentLength = +(req.headers["content-length"] ?? 0); if (contentLength === 0 || contentLength > MAX_REQUEST_SIZE) { reject(new Error("Content Too Large", { cause: { code: 413 } })); } const kill = setTimeout(() => { reject(new Error("Request Timeout", { cause: { code: 408 } })); }, MAX_IDLE_TIME); const reqData = []; let reqSize = 0; req.on("data", (chunk) => { reqSize += chunk.byteLength; if (reqSize > MAX_REQUEST_SIZE) { reject(new Error("Content Too Large", { cause: { code: 413 } })); } reqData.push(chunk); }); req.on("end", () => { clearTimeout(kill); resolve(reqData); }); req.once("error", reject); }); } const server = http.createServer(async (req, res) => { const ip = getIp(req); if (!ip) return res.writeHead(401).end("Unauthorized"); if (isRateLimited(ip)) return res.writeHead(429).end("Too Many Requests"); if (req.method === "POST") { try { const reqData = await readIncomingMessage(req); post(res, reqData); } catch (err) { req.socket.destroy(); return res.writeHead(err.cause?.code ?? 500).end(err.message ?? "Internal Server Error"); } } else if (req.method === "GET") { get(res); } else if (req.method === "HEAD") { return res.writeHead(200, { "Content-Type": "text/plain" }).end(); } else if (["CONNECT", "DELETE", "OPTIONS", "PATCH", "PUT", "TRACE"].includes(req.method ?? "")) { return res.writeHead(405, { "Allow": "GET, HEAD, POST" }).end("Method Not Allowed"); } else { return res.writeHead(501).end("Not Implemented"); } }); server.headersTimeout = MAX_IDLE_TIME; server.keepAliveTimeout = MAX_IDLE_TIME; server.maxConnections = MAX_CONNECTIONS; server.maxHeadersCount = MAX_HEADER_COUNT; server.on("connection", (s) => { s.setTimeout(MAX_IDLE_TIME, () => s.destroy()); }); server.on("error", (serverErr) => { try { shutdown(); } catch (shutdownErr) { process.exit(1); } }); function shutdown() { const kill = setTimeout(() => { process.exit(1); }, 1e4); server.close(async () => { await browser.close(); clearTimeout(kill); process.exit(0); }); } process.on("SIGINT", shutdown); process.on("SIGTERM", shutdown); process.on("SIGHUP", async () => { server.close(async () => { await loadConfig(); await page.reload(); NanoPowHandle = await page.waitForFunction(() => { return window.NanoPow; }); listen(); }); }); listen(); //# sourceMappingURL=server.js.map