// Web server: static site, the contract sources, and two live read-only endpoints (chain status, exposure scan). // node server.mjs (PORT, default 5870) import http from "node:http"; import { readFile } from "node:fs/promises"; import { extname, join, normalize } from "node:path"; import { createHash, timingSafeEqual } from "node:crypto"; import * as T from "./burn.mjs"; import * as R from "./relayer.mjs"; import * as S from "./services.mjs"; import * as A from "./agents.mjs"; import * as AI from "./ai.mjs"; import * as X from "./exposure.mjs"; import { ethers } from "ethers"; import { fileURLToPath } from "node:url"; const ROOT = fileURLToPath(new URL(".", import.meta.url)); const PORT = Number(process.env.PORT || 5870); const NETS = { robinhood: { name: "Robinhood Chain", id: 4663, rpcs: [process.env.RH_RPC || "https://rpc.mainnet.chain.robinhood.com", "https://robinhood.drpc.org"], explorer: "https://explorer.mainnet.chain.robinhood.com" }, base: { name: "Base", id: 8453, rpcs: ["https://mainnet.base.org", "https://base-rpc.publicnode.com"], explorer: "https://basescan.org", scan: false }, arbitrum: { name: "Arbitrum One", id: 42161, rpcs: ["https://arb1.arbitrum.io/rpc", "https://arbitrum.drpc.org"], explorer: "https://arbiscan.io", scan: false }, optimism: { name: "OP Mainnet", id: 10, rpcs: ["https://mainnet.optimism.io", "https://optimism.drpc.org"], explorer: "https://optimistic.etherscan.io", scan: false }, bsc: { name: "BNB Smart Chain", id: 56, rpcs: ["https://bsc-dataseed.bnbchain.org", "https://bsc.drpc.org"], explorer: "https://bscscan.com", scan: false }, polygon: { name: "Polygon PoS", id: 137, rpcs: ["https://polygon.drpc.org", "https://polygon-bor-rpc.publicnode.com"], explorer: "https://polygonscan.com", scan: false }, ethereum: { name: "Ethereum", id: 1, rpcs: [process.env.ETH_RPC || "https://ethereum-rpc.publicnode.com", "https://eth.drpc.org"], explorer: "https://etherscan.io" }, }; if (process.env.HF_LOCAL) NETS.local = { name: "Local Hardhat", id: 31337, rpcs: [process.env.HF_LOCAL], explorer: "http://localhost", scan: false }; const TYPES = { ".html": "text/html; charset=utf-8", ".css": "text/css", ".js": "text/javascript", ".mjs": "text/javascript", ".svg": "image/svg+xml", ".png": "image/png", ".webp": "image/webp", ".sol": "text/plain; charset=utf-8", ".json": "application/json", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".mp4": "video/mp4", ".webm": "video/webm", ".ico": "image/x-icon" }; async function rpc(net, method, params = []) { let last; for (const url of NETS[net].rpcs) { // first endpoint, then the fallback try { const r = await fetch(url, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ jsonrpc: "2.0", id: 1, method, params }), signal: AbortSignal.timeout(10_000) }); const j = await r.json(); if (j.error) throw new Error(j.error.message); return j.result; } catch (e) { last = e; } } throw last; } let chainCache = { at: 0, data: null }; async function chain() { if (Date.now() - chainCache.at < 10_000) return chainCache.data; const [block, gasPrice] = await Promise.all([rpc("robinhood", "eth_blockNumber"), rpc("robinhood", "eth_gasPrice")]); chainCache = { at: Date.now(), data: { chainId: 4663, block: parseInt(block, 16), gasPriceWei: BigInt(gasPrice).toString(), at: new Date().toISOString() } }; return chainCache.data; } // What a quantum computer would need: the public key. An EVM address only reveals a hash of it; the key itself // becomes public the first time the address signs a transaction (nonce > 0). async function scanEvm(address, all = false) { const out = []; for (const net of Object.keys(NETS).filter((n) => n !== "local" && (all || NETS[n].scan !== false))) { try { const [nonce, bal, code] = await Promise.all([rpc(net, "eth_getTransactionCount", [address, "latest"]), rpc(net, "eth_getBalance", [address, "latest"]), rpc(net, "eth_getCode", [address, "latest"])]); const sent = parseInt(nonce, 16), isContract = code && code !== "0x"; out.push({ network: NETS[net].name, chainId: NETS[net].id, explorer: `${NETS[net].explorer}/address/${address}`, sent, balanceWei: BigInt(bal).toString(), contract: isContract, status: isContract ? "contract" : sent > 0 ? "exposed" : "hidden", }); } catch (e) { out.push({ network: NETS[net].name, chainId: NETS[net].id, error: "network did not answer" }); } } return out; } // Bitcoin: the address type decides when the key goes public. Taproot (bc1p) puts the key in the address itself; // key-hash and script-hash addresses (1…, 3…, bc1q…) reveal their keys when they spend. const BTC_APIS = ["https://mempool.space/api", "https://blockstream.info/api"]; function btcType(a) { if (/^bc1p[02-9ac-hj-np-z]{58}$/.test(a)) return { type: "Taproot (P2TR)", keyInAddress: true }; if (/^bc1q[02-9ac-hj-np-z]{38}$/.test(a)) return { type: "SegWit key hash (P2WPKH)", keyInAddress: false }; if (/^bc1q[02-9ac-hj-np-z]{58}$/.test(a)) return { type: "SegWit script hash (P2WSH)", keyInAddress: false, script: true }; if (/^1[1-9A-HJ-NP-Za-km-z]{25,34}$/.test(a)) return { type: "Legacy key hash (P2PKH)", keyInAddress: false }; if (/^3[1-9A-HJ-NP-Za-km-z]{25,34}$/.test(a)) return { type: "Script hash (P2SH)", keyInAddress: false, script: true }; return null; } async function scanBtc(address) { const t = btcType(address); let j, last; for (const api of BTC_APIS) { try { const r = await fetch(`${api}/address/${address}`, { signal: AbortSignal.timeout(10_000), headers: { "user-agent": "hashfort-scan" } }); if (r.ok) { j = await r.json(); break; } last = new Error("HTTP " + r.status); } catch (e) { last = e; } } if (!j) return [{ network: "Bitcoin", error: "Bitcoin data source did not answer" }]; const c = j.chain_stats, m = j.mempool_stats; const spent = c.spent_txo_count + m.spent_txo_count; const balanceSats = c.funded_txo_sum - c.spent_txo_sum + m.funded_txo_sum - m.spent_txo_sum; const status = t.keyInAddress ? "exposed" : spent > 0 ? "exposed" : "hidden"; let note; if (t.keyInAddress) note = "Taproot addresses carry the public key in the address itself, so it is public from the first deposit."; else if (spent > 0) note = `It has spent ${spent} output${spent === 1 ? "" : "s"}, which put its ${t.script ? "script and keys" : "public key"} on chain.`; else note = "It has never spent, so only a hash of the key is public." + (t.type.startsWith("Legacy") ? " Coins paid to the raw public key (P2PK, used by early miners) are exposed anyway; this scan checks the address form." : ""); return [{ network: "Bitcoin", addressType: t.type, explorer: `https://mempool.space/address/${address}`, sent: c.tx_count + m.tx_count, spentOutputs: spent, balanceSats: String(balanceSats), status, note }]; } async function scan(address) { address = String(address).trim(); if (/^0x[0-9a-fA-F]{40}$/.test(address)) return { address, kind: "evm", at: new Date().toISOString(), results: await scanEvm(address) }; if (btcType(address)) return { address, kind: "bitcoin", at: new Date().toISOString(), results: await scanBtc(address) }; throw Object.assign(new Error("not an EVM (0x…) or Bitcoin mainnet address"), { status: 400 }); } // The project token: set by the owner in /studio. Empty until launch, so the page says so instead of showing an address. // The chart pair is looked up on Dexscreener; burn totals come from the studio's history. let tokenCache = { at: 0, data: null }; async function token() { if (Date.now() - tokenCache.at < 60_000) return tokenCache.data; const pv = await T.publicView().catch(() => ({ live: false, symbol: T.tokenConfig().symbol })); const address = pv.live ? pv.ca : null; const xs = S.x402Status(); let data = { symbol: pv.symbol || null, address, chainId: 4663, network: "Robinhood Chain", utility: { holderThreshold: xs.holders.threshold, holderBenefit: xs.holders.benefit, buybacks: "Revenue from paid services (x402, USDG) funds buybacks; every bought token is burned on chain and listed here." } }; if (address) { data.explorer = `${NETS.robinhood.explorer}/token/${address}`; data.buy = pv.buy; data.deadBalance = pv.deadBalance; data.totals = pv.totals; data.burns = pv.burns; try { const j = await (await fetch(`https://api.dexscreener.com/latest/dex/tokens/${address}`, { signal: AbortSignal.timeout(10_000) })).json(); const pair = (j.pairs || []).filter((p) => p.chainId === "robinhood").sort((a, b) => (b.liquidity?.usd || 0) - (a.liquidity?.usd || 0))[0]; if (pair && /^0x[0-9a-fA-F]+$/.test(pair.pairAddress)) { data.pair = pair.pairAddress; data.dex = pair.dexId; data.chartPage = `https://dexscreener.com/robinhood/${pair.pairAddress}`; data.chartEmbed = `${data.chartPage}?embed=1&theme=dark&trades=0&info=0`; } } catch { /* chart stays hidden until Dexscreener answers */ } } tokenCache = { at: Date.now(), data }; return data; } // ---------- /studio: owner only (x-studio-key). Wrong keys lock an address out for 10 minutes after 10 tries. ---------- const digest = (x) => createHash("sha256").update(String(x)).digest(), misses = new Map(); const ipOf = (req) => String(req.headers["x-forwarded-for"] || req.socket.remoteAddress || "").split(",")[0].trim(); function studioOk(req) { const ip = ipOf(req), now = Date.now(), m = (misses.get(ip) || []).filter((t) => now - t < 10 * 60_000); if (m.length >= 10) return "locked"; if (timingSafeEqual(digest(req.headers["x-studio-key"] || ""), digest(T.STUDIO_KEY))) return "ok"; misses.set(ip, [...m, now]); if (misses.size > 5000) misses.clear(); return "bad"; } const jsonBody = (req) => new Promise((ok, bad) => { let n = 0; const parts = []; req.on("data", (b) => { n += b.length; if (n > 65_536) { bad(Object.assign(new Error("Body too large."), { status: 413 })); req.destroy(); } else parts.push(b); }); req.on("end", () => { try { ok(parts.length ? JSON.parse(Buffer.concat(parts).toString("utf8")) : {}); } catch { bad(Object.assign(new Error("Body must be JSON."), { status: 400 })); } }); }); async function studio(req, p) { const a = studioOk(req); if (a !== "ok") throw Object.assign(new Error(a === "locked" ? "Too many wrong keys. Wait 10 minutes." : "Wrong studio key."), { status: a === "locked" ? 429 : 401 }); const k = `${req.method} ${p.slice("/api/studio".length)}`; if (k === "GET /status") return T.status(); if (k === "POST /token") { tokenCache.at = 0; return T.saveToken(await jsonBody(req)); } if (k === "POST /wallet") return T.saveKey((await jsonBody(req)).privateKey || ""); if (k === "DELETE /wallet") return T.removeKey(); if (k === "POST /buyback") { tokenCache.at = 0; return T.buyback((await jsonBody(req)).usd); } if (k === "POST /supply") { tokenCache.at = 0; return T.burnSupply((await jsonBody(req)).usd); } if (k === "POST /burn-held") { tokenCache.at = 0; return T.burnHeld(); } if (k === "GET /relayer") { await deployments(); return R.ownerStatus(); } if (k === "POST /relayer/wallet") return R.saveKey((await jsonBody(req)).privateKey || ""); if (k === "DELETE /relayer/wallet") return R.removeKey(); if (k === "POST /relayer/settings") return R.settings(await jsonBody(req)); if (k === "GET /ai") return AI.status(); if (k === "POST /ai/key") return AI.saveKey((await jsonBody(req)).key); if (k === "DELETE /ai/key") return AI.removeKey(); if (k === "POST /ai/cap") return AI.setCap((await jsonBody(req)).dailyCap); if (k === "GET /x402") return S.x402Status(); if (k === "POST /x402") return S.x402Config(await jsonBody(req)); if (k === "GET /sentinel") { await deployments(); return A.sentinelOwnerStatus(); } if (k === "POST /sentinel/key") return A.makeSentinelKey(); if (k === "DELETE /sentinel/key") return A.removeSentinelKey(); throw Object.assign(new Error("Not found."), { status: 404 }); } // Read-only JSON-RPC for the app (no keys here, nothing that writes). Writes always go through the user's own wallet. const READ_ONLY = new Set(["eth_chainId", "eth_blockNumber", "eth_call", "eth_getBalance", "eth_getCode", "eth_getTransactionCount", "eth_getTransactionReceipt", "eth_getTransactionByHash", "eth_gasPrice", "eth_estimateGas", "eth_getBlockByNumber", "eth_getLogs", "eth_getStorageAt"]); const CHAIN_NET = { 1: "ethereum", 4663: "robinhood", 8453: "base", 42161: "arbitrum", 10: "optimism", 56: "bsc", 137: "polygon" }; if (process.env.HF_LOCAL) CHAIN_NET[31337] = "local"; const providers = {}; const provider = (chainId) => { const net = CHAIN_NET[chainId]; if (!net) return null; return (providers[chainId] ||= new ethers.JsonRpcProvider(NETS[net].rpcs[0], Number(chainId), { staticNetwork: true, batchMaxCount: 1 })); }; async function rpcProxy(req, chainId) { const net = CHAIN_NET[chainId || 4663]; if (!net) throw Object.assign(new Error("unsupported chain"), { status: 400 }); let raw = ""; for await (const c of req) { raw += c; if (raw.length > 256_000) throw Object.assign(new Error("too large"), { status: 413 }); } const one = async (m) => { if (!m || !READ_ONLY.has(m.method)) return { jsonrpc: "2.0", id: m?.id ?? null, error: { code: -32601, message: "method not allowed here" } }; try { return { jsonrpc: "2.0", id: m.id, result: await rpc(net, m.method, m.params || []) }; } catch (e) { return { jsonrpc: "2.0", id: m.id, error: { code: -32000, message: String(e.message || e) } }; } }; const body = JSON.parse(raw || "null"); return Array.isArray(body) ? Promise.all(body.slice(0, 20).map(one)) : one(body); } // /code/: every source file the site runs on, with its SHA-256, and the deployed addresses. Stands in for a public repo. const CODE = [ ["contracts/HashSig.sol", "Hash-based signature verifier (WOTS+ one-time keys in a Merkle tree, keccak256 only)"], ["contracts/QuantumVault.sol", "The vault (v1): daily key with limits, vault key for everything else, guardians, no admin"], ["contracts/QuantumVaultV2.sol", "The vault (v2, Robinhood Chain): v1 plus scoped agent keys (limits, allowed addresses, expiry) and Sentinel keys that can only freeze"], ["contracts/QuantumVaultFactoryV2.sol", "Factory for v2 vaults"], ["contracts/plans/HashfortPlans.sol", "Free / Pro / Team plans in USDG, admin-free; HASHFORT holders get Pro on chain (planOf reads the token balance)"], ["contracts/v3/QuantumVaultV3.sol", "The vault (v3): ML-DSA-65 primary key, SLH-DSA-SHA2-128s recovery key with a 2-day delay, plus every v2 feature"], ["contracts/v3/QuantumVaultFactoryV3.sol", "Factory for v3 vaults; stores each primary key's verification data as contract code"], ["contracts/mldsa/MLDSA65Verifier.sol", "ML-DSA-65 (FIPS 204) verification on chain, plus checkExpansion to audit a vault's stored key data"], ["contracts/mldsa/SLHDSA128sVerifier.sol", "SLH-DSA-SHA2-128s (FIPS 205) verification on chain, using the SHA-256 precompile"], ["contracts/mldsa/Shake.sol", "SHAKE128/256 (FIPS 202) in Yul, generated by scripts/gen/keccak_yul.py"], ["sdk/mldsa65.mjs", "What the app computes from an ML-DSA-65 public key before storing it on chain"], ["test/vault-v3.test.js", "v3 tests: browser-made ML-DSA-65 and SLH-DSA signatures, replay, rotation, recovery delay, guardians"], ["test/mldsa65.test.js", "ML-DSA-65 verifier tests against signatures from the browser library"], ["test/slhdsa.test.js", "SLH-DSA-SHA2-128s verifier tests against signatures from the browser library"], ["contracts/QuantumVaultFactory.sol", "Deterministic vault addresses (CREATE2 + EIP-1167 clones of one immutable implementation)"], ["sdk/hashsig.mjs", "Key trees, signing and the operation digest, the same code the app runs in your browser"], ["web/app/app.js", "The vault app: key generation, Recovery Kit, signing, transactions through your wallet"], ["server.mjs", "This web server: static files, read-only chain proxy, exposure scan (EVM and Bitcoin)"], ["services.mjs", "Transaction auditor (simulation and rules) and x402 payments in USDG on Robinhood Chain"], ["agents.mjs", "Agent keys, agent runtime (pays x402 through agentSpend), MEMORY.md, and the Sentinel watcher"], ["ai.mjs", "Optional language model for summaries and the agent's reasoning (key sealed on the server)"], ["relayer.mjs", "Gasless relayer for vault-key operations (only Hashfort vaults, simulated first)"], ["test/vault-v2.test.js", "Tests for agent keys, Sentinel freeze, and the vault key during a freeze"], ]; const esc = (t) => String(t).replace(/[&<>"]/g, (c) => ({ "&": "&", "<": "<", ">": ">", '"': """ })[c]); async function deployments() { const out = []; for (const f of ["deploy.json", "deploy-1.json", "deploy-8453.json", "deploy-42161.json", "deploy-10.json", "deploy-56.json", "deploy-137.json", ...(process.env.HF_LOCAL ? ["deploy-31337.json"] : [])]) { try { out.push(JSON.parse(await readFile(join(ROOT, "web/app", f), "utf8"))); } catch {} } // Where a v2 factory exists (Robinhood Chain), new vaults use it; v1 vaults there keep working and stay listed as legacy. for (const f of ["deploy-v2-4663.json", ...(process.env.HF_LOCAL ? ["deploy-v2-31337.json"] : [])]) { try { const v2 = JSON.parse(await readFile(join(ROOT, "web/app", f), "utf8")), i = out.findIndex((d) => d.chainId === v2.chainId); if (i >= 0) out[i] = { ...v2, legacy: { factory: out[i].factory, implementation: out[i].implementation, deployTx: out[i].deployTx, block: out[i].block } }; else out.push(v2); } catch {} } // Post-quantum v3 (ML-DSA-65 primary key, SLH-DSA recovery key) sits beside the chain's standard factory. for (const f of ["deploy-v3-4663.json", ...(process.env.HF_LOCAL ? ["deploy-v3-31337.json"] : [])]) { try { const v3 = JSON.parse(await readFile(join(ROOT, "web/app", f), "utf8")), i = out.findIndex((d) => d.chainId === v3.chainId); if (i >= 0) out[i] = { ...out[i], v3 }; else out.push({ chainId: v3.chainId, chainName: v3.chainName, explorer: v3.explorer, rpcUrls: v3.rpcUrls, v3 }); } catch {} } // Live on Robinhood Chain (v3, token, plans); Standard vaults also work on the other six chains. const list = out.filter((d) => (d.factory || d.v3) && CHAIN_NET[d.chainId]); const impls = (d) => [d.implementation, d.legacy?.implementation].filter(Boolean); const allImpls = (d) => [...impls(d), d.v3?.implementation].filter(Boolean); R.configure(list.map((d) => ({ chainId: d.chainId, name: d.chainName, implementations: impls(d), explorer: d.explorer, rpc: NETS[CHAIN_NET[d.chainId]].rpcs[0] }))); const byId = Object.fromEntries(list.map((d) => [d.chainId, d])); let plans = null; for (const f of ["deploy-plans-4663.json", ...(process.env.HF_LOCAL ? ["deploy-plans-31337.json"] : [])]) { try { plans = JSON.parse(await readFile(join(ROOT, "web/app", f), "utf8")); } catch {} } S.configure({ provider, plans: () => plans, implementations: (id) => (byId[id] ? allImpls(byId[id]) : []), tokenAddress: () => { const ca = T.tokenConfig().ca; return ca && ethers.isAddress(ca) ? ethers.getAddress(ca) : null; } }); A.configure({ provider, implementations: (id) => (byId[id] ? allImpls(byId[id]) : []), v2Implementation: (id) => [byId[id]?.version === 2 ? byId[id].implementation : null, byId[id]?.v3?.implementation].filter(Boolean), selfUrl: `http://127.0.0.1:${PORT}` }); return list; } // Vaults made by the Robinhood Chain factories (v1 legacy and v2) and their vault-key executions, read from the chain. const CREATED = ethers.id("VaultCreated(address,address,bytes32,uint8)"), EXECUTED = ethers.id("Executed(uint32,uint32,bytes32)"); const CREATED3 = ethers.id("VaultCreated(address,address,bytes32,bytes32)"), EXECUTED3 = ethers.id("Executed(uint64,bytes32)"); let live = { to: 0, vaults: {}, at: 0, busy: null }; async function liveVaults() { if (Date.now() - live.at < 60_000 || live.busy) return live.busy ? (await live.busy, live) : live; live.busy = (async () => { const deps = await deployments(), d = deps.find((x) => x.chainId === 4663); if (!d) return; const facs = [...(d.factory ? [[d.factory, d.version || 1]] : []), ...(d.legacy ? [[d.legacy.factory, 1]] : []), ...(d.v3 ? [[d.v3.factory, 3]] : [])], p = provider(4663); const head = await p.getBlockNumber(); let from = live.to ? live.to + 1 : Math.min(...[d.block, d.legacy?.block, d.v3?.block].filter(Boolean)); for (; from <= head; from += 50_000) { const to = Math.min(head, from + 49_999); for (const [f, version] of facs) for (const l of await p.getLogs({ address: f, topics: [version === 3 ? CREATED3 : CREATED], fromBlock: from, toBlock: to })) live.vaults[ethers.getAddress("0x" + l.topics[1].slice(26))] = { version, owner: ethers.getAddress("0x" + l.topics[2].slice(26)), created: l.transactionHash, block: l.blockNumber, executes: 0, last: null }; const addrs = Object.keys(live.vaults); if (addrs.length) for (const l of await p.getLogs({ address: addrs, topics: [[EXECUTED, EXECUTED3]], fromBlock: from, toBlock: to })) { const v = live.vaults[ethers.getAddress(l.address)]; if (v) { v.executes++; v.last = l.transactionHash; } } live.to = to; } live.at = Date.now(); })().catch(() => {}).finally(() => { live.busy = null; }); await live.busy; return live; } async function codePage() { const deps = await deployments(); const rows = []; for (const [f, what] of CODE) { const b = await readFile(join(ROOT, f)).catch(() => null); if (!b) continue; const name = f.split("/").pop(); rows.push(`${esc(f)}

${esc(what)}

${b.toString().split("\n").length}${createHash("sha256").update(b).digest("hex")}`); } const lv = await liveVaults().catch(() => ({ vaults: {} })), ex = deps.find((x) => x.chainId === 4663)?.explorer || ""; const vrows = Object.entries(lv.vaults).sort((a, b) => b[1].block - a[1].block).slice(0, 50).map(([a, v]) => `${a}

v${v.version}

${v.created.slice(0, 18)}…${v.executes}${v.last ? ` · latest` : ""}`).join("") || `No vaults yet.`; let plansRow = ""; try { const pl = JSON.parse(await readFile(join(ROOT, "web/app/deploy-plans-4663.json"), "utf8")), ex = "https://explorer.mainnet.chain.robinhood.com"; plansRow = `

Token utility

Plans and HASHFORT

ContractAddressVerified source
Robinhood Chain · HashfortPlans

Pro ${Number(pl.proPrice) / 1e6} USDG and Team ${Number(pl.teamPrice) / 1e6} USDG per 30 days, paid straight to the treasury. planOf() gives Pro to any account holding ${(BigInt(pl.holderThreshold) / 10n ** 18n).toLocaleString("en-US")} HASHFORT.

${pl.address}Sourcify
Robinhood Chain · HASHFORT token${pl.hashfort}ERC-20
`; } catch {} const sourcify = (d, a) => `Sourcify`; const legacyRows = (d) => d.legacy ? ` ${esc(d.chainName)} · QuantumVaultFactory (v1, legacy)${d.legacy.factory}${sourcify(d, d.legacy.factory)} ${esc(d.chainName)} · QuantumVault (v1 implementation)${d.legacy.implementation}${sourcify(d, d.legacy.implementation)}` : ""; const V = (d) => (d.version === 2 ? "V2" : ""); const v3Rows = (d) => !d.v3 ? "" : [["QuantumVaultFactoryV3", d.v3.factory, d.v3.deployTx], ["QuantumVaultV3 (implementation)", d.v3.implementation, d.v3.deployTx], ["MLDSA65Verifier (FIPS 204)", d.v3.mldsa, d.v3.txs?.MLDSA65Verifier?.hash], ["SLHDSA128sVerifier (FIPS 205)", d.v3.slhdsa, d.v3.txs?.SLHDSA128sVerifier?.hash]] .map(([n, a]) => `${esc(d.chainName)} · ${n}${a}${sourcify(d, a)}`).join(""); const deployed = deps.length ? deps.map((d) => !d.factory ? v3Rows(d) : ` ${esc(d.chainName)} · QuantumVaultFactory${V(d)}${d.factory}${sourcify(d, d.factory)} ${esc(d.chainName)} · QuantumVault${V(d)} (implementation)${d.implementation}${sourcify(d, d.implementation)} ${esc(d.chainName)} · deployment${d.deployTx}block ${d.block}${legacyRows(d)}${v3Rows(d)}`).join("") : `Not deployed yet.`; return `Hashfort · Code

Code

Everything this site runs on.

The contracts, the signing code and the app, as served right now, with their SHA-256 so anyone can compare what runs on chain and in the browser.

On chain

Deployed contracts

${deployed}
ContractAddressVerified source
${plansRow}

In use

Vaults on Robinhood Chain

Every vault the factories created, read from the chain now (VaultCreated), and how many vault-key operations each has run (Executed: a hash-based signature the contract verified).

${vrows}
VaultCreated inVault-key operations

Source

Files

${rows.join("")}
FileLinesSHA-256

Build

Compile it yourself

solc 0.8.24, optimizer on, 10,000 runs, evmVersion shanghai
v3 primary key   ML-DSA-65 (FIPS 204): q = 8380417, (k, l) = (6, 5), signature 3,309 B, public key 1,952 B; SHAKE128/256 in Yul
v3 recovery key  SLH-DSA-SHA2-128s (FIPS 205): n = 16, h = 63, d = 7, a = 12, k = 14; signature 7,856 B; SHA-256 precompile
Standard key     HashSig: WOTS+ n = 32 bytes, w = 16, 67 chains, Merkle height 10 (1,024 one-time keys); keccak256 with tweaks
Test suite: 40 tests (Hardhat): signatures, replay, forgery, expiry, limits, rotation, guardians, factory, agent keys, Sentinel freeze,\nML-DSA-65 and SLH-DSA-SHA2-128s verifiers against browser-made signatures, v3 vaults (primary key, recovery delay, guardians)
`; } // Free audit for the app: 30 an hour per address; the plain-language summary (if the AI is on) 15 a day per address. const hits = new Map(); const allow = (key, n, ms) => { const now = Date.now(), xs = (hits.get(key) || []).filter((t) => now - t < ms); if (xs.length >= n) return false; xs.push(now); hits.set(key, xs); if (hits.size > 20000) hits.clear(); return true; }; async function freeAudit(req) { const ip = ipOf(req), body = await jsonBody(req); if (!allow("audit:" + ip, 30, 3600_000)) throw Object.assign(new Error("Too many audits from this address. Try again later."), { status: 429 }); const report = await S.audit(body); let paidTier = 0; if (body.explain && AI.configured() && ethers.isAddress(body.vault || "")) { const own = await new ethers.Contract(body.vault, ["function owner() view returns (address)"], provider(Number(body.chainId) || 4663)).owner().catch(() => null); paidTier = (await S.tierOf([body.vault, own])).tier; } if (body.explain && AI.configured() && paidTier < 1) report.explanation = null, report.explainNote = "The plain-language AI summary is a Pro feature (buy Pro, or hold HASHFORT). The checks above are complete on every plan."; else if (body.explain && AI.configured()) { if (allow("explain:" + ip, 15, 86400_000)) report.explanation = await AI.explainAudit(report).catch((e) => "(summary unavailable: " + e.message + ")"); else report.explanation = "(daily summary limit reached; the checks above are complete)"; } report.ai = AI.configured(); return report; } async function agentRoute(req, url) { const k = `${req.method} ${url.pathname}`; if (k === "GET /api/sentinel/public") return { address: A.sentinelAddress(), x402: S.x402Status(), ai: AI.configured(), usdg: S.usdgOf(Number(url.searchParams.get("chain")) || 4663) }; if (k === "GET /api/agents/session") { const chainId = Number(url.searchParams.get("chain")), vault = ethers.getAddress(url.searchParams.get("vault") || ""), issued = Math.floor(Date.now() / 1000); return { issued, message: A.sessionMessage(chainId, vault, issued) }; } if (req.method !== "POST") throw Object.assign(new Error("Not found."), { status: 404 }); const body = await jsonBody(req); const route = { "/api/agents/create": A.createAgent, "/api/agents/list": A.listAgents, "/api/agents/memory": A.setMemory, "/api/agents/forget": A.forgetAgent, "/api/agents/run": A.runAgent, "/api/sentinel/get": A.sentinelGet, "/api/sentinel/set": A.sentinelSet, "/api/sentinel/subscribe": A.pushSubscribe, "/api/team/vaults": (r, b) => A.teamVaults(r, b, async () => Object.entries((await liveVaults()).vaults).map(([vault, v]) => ({ vault, ...v }))), }[url.pathname]; if (!route) throw Object.assign(new Error("Not found."), { status: 404 }); return route(req, body); } const send = (res, code, body, type = "application/json") => { const cache = type.startsWith("application/json") ? "no-store" : type.startsWith("text/html") ? "no-cache" : "public, max-age=300"; const h = { "content-type": type, "cache-control": cache, "x-content-type-options": "nosniff", "referrer-policy": "strict-origin-when-cross-origin" }; if (type.startsWith("image/")) { h["access-control-allow-origin"] = "*"; h["cross-origin-resource-policy"] = "cross-origin"; if (Buffer.isBuffer(body)) h["content-length"] = body.length; } res.writeHead(code, h); res.end(typeof body === "string" || Buffer.isBuffer(body) ? body : JSON.stringify(body)); }; http.createServer(async (req, res) => { const url = new URL(req.url, "http://x"); try { if (url.pathname === "/api/chain") return send(res, 200, await chain()); if (url.pathname === "/api/rpc" && req.method === "POST") return send(res, 200, await rpcProxy(req, Number(url.searchParams.get("chain")) || 4663)); if (url.pathname === "/api/deployments") return send(res, 200, await deployments()); if (url.pathname === "/api/token") return send(res, 200, await token()); if (url.pathname.startsWith("/api/studio/")) return send(res, 200, await studio(req, url.pathname)); if (url.pathname === "/api/relay/status") { await deployments(); return send(res, 200, await R.publicStatus(Number(url.searchParams.get("chain")))); } if (url.pathname === "/api/relay" && req.method === "POST") { await deployments(); return send(res, 200, await R.relay(await jsonBody(req), ipOf(req))); } if (url.pathname === "/studio") { res.writeHead(200, { "content-type": "text/html; charset=utf-8", "cache-control": "no-cache", "x-robots-tag": "noindex", "x-frame-options": "DENY", "referrer-policy": "no-referrer", "x-content-type-options": "nosniff" }); return res.end(await readFile(join(ROOT, "web", "studio.html"))); } if (url.pathname === "/api/scan") return send(res, 200, await scan(url.searchParams.get("address") || "")); if (url.pathname === "/api/audit" && req.method === "POST") { await deployments(); return send(res, 200, await freeAudit(req)); } if (url.pathname === "/api/live") { // proof of use: vaults the factories made and the vault-key operations the contracts verified const lv = await liveVaults(), list = Object.entries(lv.vaults); const withExec = list.filter(([, v]) => v.last).sort((a, b) => b[1].block - a[1].block); return send(res, 200, { chainId: 4663, vaults: list.length, vaultKeyOperations: list.reduce((n, [, v]) => n + v.executes, 0), scannedTo: lv.to, latest: withExec[0] ? { vault: withExec[0][0], createdTx: withExec[0][1].created, executeTx: withExec[0][1].last, version: withExec[0][1].version } : null }); } if (url.pathname === "/x402" || url.pathname === "/.well-known/x402") { await deployments(); return send(res, 200, S.x402Status()); } if (url.pathname.startsWith("/api/proof/tx/")) { await deployments(); return send(res, 200, await S.proofTx(url.pathname.slice(14))); } if (url.pathname === "/api/proof/demo") { const list = await deployments(), d = list.find((x) => x.chainId === 4663 && x.v3); if (!d) return send(res, 503, { error: "v3 is not deployed" }); if (!allow("proof:" + ipOf(req), 12, 600_000)) return send(res, 429, { error: "Too many proofs from this address; try again in a few minutes." }); return send(res, 200, await S.proofDemo({ verifierMl: d.v3.mldsa, verifierSlh: d.v3.slhdsa })); } if (url.pathname === "/api/exposure") return send(res, 200, X.view()); if (url.pathname === "/api/plans") { await deployments(); return send(res, 200, S.plansInfo()); } if (url.pathname === "/api/plan") { await deployments(); const a = (url.searchParams.get("address") || "").split(",").filter(Boolean); return send(res, 200, { ...(await S.tierOf(a)), checked: a }); } if (url.pathname === "/api/holder") { await deployments(); return send(res, 200, await S.holderStatus(url.searchParams.get("address") || "")); } if (url.pathname === "/api/holder/message") { const a = url.searchParams.get("address") || ""; if (!ethers.isAddress(a)) return send(res, 400, { error: "address required" }); const issued = Math.floor(Date.now() / 1000); return send(res, 200, { issued, message: S.holderMessage(ethers.getAddress(a), issued) }); } if (url.pathname === "/x402/exposure" && req.method === "POST") { const body = await jsonBody(req), list = (body.addresses || []).map((x) => String(x).trim()).filter(Boolean); if (!list.length || list.length > 20) return send(res, 400, { error: "Send 1 to 20 addresses." }); for (const a of list) if (!/^0x[0-9a-fA-F]{40}$/.test(a) && !btcType(a)) return send(res, 400, { error: `Not an EVM or Bitcoin address: ${a}` }); const paid = await S.gate(req, res, "exposure", url.href); if (!paid) return; const results = []; for (const a of list) results.push(/^0x/.test(a) ? { address: a, kind: "evm", results: await scanEvm(a, true) } : { address: a, kind: "bitcoin", results: await scanBtc(a) }); const exposed = results.filter((r) => r.results.some((x) => x.status === "exposed")).length; return send(res, 200, { service: "exposure", at: new Date().toISOString(), paidBy: paid.from, paymentTx: paid.txHash, holderAccess: !!paid.holder, summary: { addresses: list.length, exposed, hidden: list.length - exposed }, results }); } if (url.pathname === "/x402/audit" && req.method === "POST") { await deployments(); const body = await jsonBody(req); const report = await S.audit(body); // validate before taking payment const paid = await S.gate(req, res, "audit", url.href); if (!paid) return; if (AI.configured()) report.explanation = await AI.explainAudit(report).catch((e) => "(summary unavailable: " + e.message + ")"); return send(res, 200, { ...report, paidBy: paid.from, paymentTx: paid.txHash }); } if (url.pathname.startsWith("/api/agents/") || url.pathname.startsWith("/api/sentinel/")) { await deployments(); return send(res, 200, await agentRoute(req, url)); } if (url.pathname === "/code" || url.pathname === "/code/") return send(res, 200, await codePage(), "text/html; charset=utf-8"); let file; if (url.pathname.startsWith("/code/")) { const name = url.pathname.slice(6); const known = CODE.map(([f]) => f).find((f) => f.split("/").pop() === name); if (!known) return send(res, 404, { error: "not found" }); file = join(ROOT, known); return send(res, 200, await readFile(file), "text/plain; charset=utf-8"); } else { const p = normalize(decodeURIComponent(url.pathname)).replace(/^(\.\.[/\\])+/, ""); file = join(ROOT, "web", p.endsWith("/") ? p + "index.html" : p); if (!file.startsWith(join(ROOT, "web"))) return send(res, 403, { error: "forbidden" }); } const body = await readFile(file), type = TYPES[extname(file)] || "application/octet-stream"; const range = /^bytes=(\d*)-(\d*)$/.exec(req.headers.range || ""); if (range && type.startsWith("video/")) { // Safari only plays video served with byte ranges const size = body.length; let start = range[1] === "" ? size - Number(range[2]) : Number(range[1]); let end = range[1] === "" || range[2] === "" ? size - 1 : Math.min(Number(range[2]), size - 1); if (!(start >= 0 && start <= end && end < size)) { res.writeHead(416, { "content-range": `bytes */${size}` }); return res.end(); } res.writeHead(206, { "content-type": type, "content-length": end - start + 1, "content-range": `bytes ${start}-${end}/${size}`, "accept-ranges": "bytes", "cache-control": "public, max-age=86400" }); return res.end(body.subarray(start, end + 1)); } if (type.startsWith("video/")) res.setHeader("accept-ranges", "bytes"); send(res, 200, body, type); } catch (e) { if (e.code === "ENOENT" || e.code === "EISDIR") return send(res, 404, { error: "not found" }); send(res, e.status || 502, { error: e.message }); } }).listen(PORT, process.env.HOST || "127.0.0.1", () => { console.log(`http://${process.env.HOST || "127.0.0.1"}:${PORT}`); deployments().then(() => A.startWatcher(Number(process.env.SENTINEL_MS) || 20_000)).catch((e) => console.error(e)); if (!process.env.HF_LOCAL) T.publicView().then((pv) => X.start(pv.live && pv.ca ? [{ address: pv.ca, symbol: pv.symbol || "HASHFORT", name: "Hashfort Vault" }] : [])).catch(() => X.start()); });