import { curves, groth16 } from "snarkjs"; import manifest from "@/public/hidden-path/v1/manifest.json"; import { commitment } from "@/lib/hidden-path/commit"; import { keyId, parseArtifact, type Artifact, } from "@/lib/hidden-path/artifact"; import { validRoute } from "@/lib/hidden-path/statement"; import type { Job, Reply } from "@/lib/hidden-path/job"; const send = (reply: Reply) => self.postMessage(reply); async function load( file: "circuit.wasm" | "proving.zkey" | "verification-key.json", ) { const response = await fetch("/hidden-path/v1/" + file, { credentials: "omit", redirect: "error", }); if (!response.ok) throw Error( "Could not load " + file + ". Check your connection and retry.", ); const bytes = new Uint8Array(await response.arrayBuffer()); const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes)); const hex = Array.from(digest, (n) => n.toString(16).padStart(2, "0")).join( "", ); if ( bytes.length !== manifest.files[file].bytes || hex !== manifest.files[file].sha256 ) throw Error("The local " + file + " failed its integrity check."); return bytes; } self.onmessage = async ({ data }: MessageEvent) => { try { send({ kind: "progress", message: "Checking the pinned verification key…", }); const vk = JSON.parse( new TextDecoder().decode(await load("verification-key.json")), ); // snarkjs 0.7.6 verification uses the ffjavascript BN128 cache. Install a // single-threaded engine in this disposable worker to bound mobile memory. Object.assign(globalThis, { curve_bn128: await curves.getCurveFromName("bn128", { singleThread: true, }), }); let artifact: Artifact; let proveMs: number | undefined; if (data.kind === "prove") { if (!validRoute(data.route)) throw Error("Choose four connected steps from 0 to 8."); send({ kind: "progress", message: "Checking the circuit and proving key…", }); const [wasm, zkey] = await Promise.all([ load("circuit.wasm"), load("proving.zkey"), ]); const random = crypto.getRandomValues(new Uint8Array(16)); const salt = random.reduce( (v, b) => v * BigInt(256) + BigInt(b), BigInt(0), ); const digest = commitment(data.route, salt); send({ kind: "progress", message: "Generating the private witness and Groth16 proof…", }); const start = performance.now(); const result = await groth16.fullProve( { route: data.route, salt: salt.toString(), commitment: digest }, wasm, zkey, undefined, { memorySize: 64 }, ); proveMs = Math.round(performance.now() - start); artifact = parseArtifact( JSON.stringify({ schemaVersion: 1, experimentId: "hidden-path", circuitVersion: "v1", verificationKeyId: keyId, ...result, }), ); if (artifact.publicSignals[0] !== digest) throw Error( "The compiled circuit returned an unexpected public signal.", ); } else { artifact = parseArtifact(JSON.stringify(data.artifact)); } send({ kind: "progress", message: "Verifying the proof against the public commitment…", }); const start = performance.now(); const valid = await groth16.verify( vk, artifact.publicSignals, artifact.proof, ); send({ kind: "result", artifact, valid, proveMs, verifyMs: Math.round(performance.now() - start), }); } catch (error) { // Only display messages about public assets or the stage. Library exceptions // during witness generation can contain private inputs. const safe = error instanceof Error && /^(Could not load |The local |Choose four |The compiled circuit |Expected a Hidden Path)/.test( error.message, ); send({ kind: "error", message: safe ? error.message : "The proof engine could not finish. Retry or use a browser with more available memory.", }); } };