Source code
Hidden Path source
The files used to compile the circuit, generate and verify receipts, and test the published release.
pragma circom 2.2.0;
include "circomlib/circuits/comparators.circom";
include "circomlib/circuits/poseidon.circom";
template HiddenPath() {
signal input route[5];
signal input salt;
signal input commitment;
route[0] === 0;
route[4] === 8;
component matches[5][9];
for (var t = 0; t < 5; t++) {
var count = 0;
for (var v = 0; v < 9; v++) {
matches[t][v] = IsEqual();
matches[t][v].in[0] <== route[t];
matches[t][v].in[1] <== v;
count += matches[t][v].out;
}
count === 1;
}
for (var t = 0; t < 4; t++) {
for (var v = 0; v < 9; v++) {
var allowed = 0;
if (v % 3 < 2) allowed += matches[t+1][v+1].out;
if (v < 6) allowed += matches[t+1][v+3].out;
matches[t][v].out * (1 - allowed) === 0;
}
}
component saltBits = Num2Bits(128);
saltBits.in <== salt;
var packed = 0;
for (var t = 0; t < 5; t++) packed = packed * 16 + route[t];
component digest = Poseidon(4);
digest.inputs[0] <== 1178879025;
digest.inputs[1] <== 1;
digest.inputs[2] <== packed;
digest.inputs[3] <== salt;
digest.out === commitment;
}
component main {public [commitment]} = HiddenPath();
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<Job>) => {
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.",
});
}
};
import { WASI } from "node:wasi";
import {
mkdir,
mkdtemp,
readFile,
writeFile,
copyFile,
} from "node:fs/promises";
import { createHash, randomBytes, randomInt } from "node:crypto";
import assert from "node:assert/strict";
import { curves, powersOfTau, groth16, r1cs, zKey } from "snarkjs";
import { commitment } from "../lib/hidden-path/commit.ts";
import { neighbors } from "../lib/hidden-path/statement.ts";
const base = ".hidden-path-build";
await mkdir(base, { recursive: true });
const build = await mkdtemp(base + "/build-");
const release = build + "/release";
await mkdir(release);
const wasi = new WASI({
version: "preview1",
args: [
"circom",
"public/hidden-path/circuit.circom",
"--r1cs",
"--wasm",
"--O2",
"-l",
"node_modules",
"-o",
build,
],
preopens: { ".": process.cwd() },
returnOnExit: true,
});
const compiler = await WebAssembly.compile(
await readFile("node_modules/circom2/circom.wasm"),
);
assert.equal(
wasi.start(await WebAssembly.instantiate(compiler, wasi.getImportObject())),
0,
);
const circuit = release + "/circuit.r1cs";
const wasm = release + "/circuit.wasm";
await copyFile(build + "/circuit.r1cs", circuit);
await copyFile(build + "/circuit_js/circuit.wasm", wasm);
const curve = await curves.getCurveFromName("bn128");
const writeJson = (file, data) =>
writeFile(file, JSON.stringify(data, null, 2) + "\n");
try {
const info = await r1cs.info(circuit);
assert.equal(info.nPubInputs, 1);
assert.equal(info.nOutputs, 0);
assert.ok(info.nConstraints + info.nPubInputs + 1 < 1024);
if (process.argv.includes("--check")) {
const pinned = "public/hidden-path/v1/";
assert.deepEqual(
await readFile(wasm),
await readFile(pinned + "circuit.wasm"),
);
assert.deepEqual(
await readFile(circuit),
await readFile(pinned + "circuit.r1cs"),
);
assert.ok(await powersOfTau.verify(pinned + "setup.ptau"));
assert.ok(
await zKey.verifyFromR1cs(
circuit,
pinned + "setup.ptau",
pinned + "proving.zkey",
),
);
assert.deepEqual(
await zKey.exportVerificationKey(pinned + "proving.zkey"),
JSON.parse(await readFile(pinned + "verification-key.json", "utf8")),
);
console.log(
"Reproduced v1 WASM and R1CS. Verified the ceremony transcript, proving key and verification key.",
);
} else {
const initial = build + "/initial.ptau";
const contributed = build + "/contributed.ptau";
const setup = release + "/setup.ptau";
const initKey = build + "/initial.zkey";
const proving = release + "/proving.zkey";
await powersOfTau.newAccumulator(curve, 10, initial);
await powersOfTau.contribute(
initial,
contributed,
"Development phase one",
randomBytes(64).toString("hex"),
);
await powersOfTau.preparePhase2(contributed, setup);
assert.ok(await powersOfTau.verify(setup));
await zKey.newZKey(circuit, setup, initKey);
await zKey.contribute(
initKey,
proving,
"Development phase two",
randomBytes(64).toString("hex"),
);
assert.ok(await zKey.verifyFromR1cs(circuit, setup, proving));
const vk = await zKey.exportVerificationKey(proving);
await writeJson(release + "/verification-key.json", vk);
const files = {};
for (const file of [
"circuit.r1cs",
"circuit.wasm",
"setup.ptau",
"proving.zkey",
"verification-key.json",
]) {
const bytes = await readFile(release + "/" + file);
files[file] = {
bytes: bytes.length,
sha256: createHash("sha256").update(bytes).digest("hex"),
};
}
const route = [0];
while (route.at(-1) !== 8) {
const choices = neighbors(route.at(-1));
route.push(choices[randomInt(choices.length)]);
}
const salt = BigInt("0x" + randomBytes(16).toString("hex"));
const input = {
route,
salt: salt.toString(),
commitment: commitment(route, salt),
};
const { proof, publicSignals } = await groth16.fullProve(
input,
wasm,
proving,
);
assert.deepEqual(publicSignals, [input.commitment]);
assert.ok(await groth16.verify(vk, publicSignals, proof));
assert.equal(
await groth16.verify(
await zKey.exportVerificationKey(initKey),
publicSignals,
proof,
),
false,
);
await writeJson(release + "/example.json", {
schemaVersion: 1,
experimentId: "hidden-path",
circuitVersion: "v1",
verificationKeyId: "sha256:" + files["verification-key.json"].sha256,
publicSignals,
proof,
});
await writeJson(release + "/manifest.json", {
constraints: info.nConstraints,
publicInputs: info.nPubInputs,
files,
});
console.log("Validated candidate at " + release);
}
} finally {
await curve.terminate();
}
import { after, test } from "node:test";
import assert from "node:assert/strict";
import { createHash } from "node:crypto";
import { readFile } from "node:fs/promises";
import { groth16, wtns } from "snarkjs";
import { commitment } from "../lib/hidden-path/commit.ts";
import { validRoute } from "../lib/hidden-path/statement.ts";
import {
parseArtifact,
shareFragment,
readFragment,
tamperedCopy,
scalarField,
} from "../lib/hidden-path/artifact.ts";
import manifest from "../public/hidden-path/v1/manifest.json" with { type: "json" };
import vector from "../public/hidden-path/v1/example.json" with { type: "json" };
import vk from "../public/hidden-path/v1/verification-key.json" with { type: "json" };
const dir = "public/hidden-path/v1/";
const wasm = dir + "circuit.wasm";
const route = [0, 3, 4, 5, 8];
const input = (r, salt = 23n) => ({
route: r,
salt: salt.toString(),
commitment: commitment(r, salt),
});
after(async () => {
await globalThis.curve_bn128?.terminate();
});
test("the installed artifacts match their manifest and published proof", async () => {
for (const [file, entry] of Object.entries(manifest.files)) {
const bytes = await readFile(dir + file);
assert.equal(bytes.length, entry.bytes);
assert.equal(
createHash("sha256").update(bytes).digest("hex"),
entry.sha256,
);
}
assert.equal(vk.nPublic, 1);
const artifact = readFragment(
shareFragment(parseArtifact(JSON.stringify(vector))),
);
assert.deepEqual(artifact, vector);
assert.ok(await groth16.verify(vk, artifact.publicSignals, artifact.proof));
assert.equal(
await groth16.verify(
vk,
tamperedCopy(artifact).publicSignals,
artifact.proof,
),
false,
);
});
test("a fresh proof opens one commitment, with a different digest for a different salt", async () => {
const witness = input(route);
assert.notEqual(witness.commitment, input(route, 24n).commitment);
const { proof, publicSignals } = await groth16.fullProve(
witness,
wasm,
dir + "proving.zkey",
);
assert.deepEqual(publicSignals, [witness.commitment]);
assert.ok(await groth16.verify(vk, publicSignals, proof));
});
test("compiled witness rejects invalid edge, row wrap, endpoints, vertex, salt and opening", async () => {
for (const invalid of [
[0, 2, 4, 5, 8],
[0, 1, 2, 3, 8],
[1, 2, 5, 7, 8],
[0, 3, 4, 5, 7],
[0, 3, 9, 5, 8],
]) {
assert.equal(validRoute(invalid), false);
await assert.rejects(wtns.calculate(input(invalid), wasm, { type: "mem" }));
}
for (const invalid of [
input(route, 1n << 128n),
{ ...input(route), commitment: "1" },
])
await assert.rejects(wtns.calculate(invalid, wasm, { type: "mem" }));
for (const good of [
[0, 1, 2, 5, 8],
[0, 1, 4, 5, 8],
[0, 1, 4, 7, 8],
[0, 3, 4, 5, 8],
[0, 3, 4, 7, 8],
[0, 3, 6, 7, 8],
]) {
assert.ok(validRoute(good));
const witness = { type: "mem" };
await wtns.calculate(input(good), wasm, witness, { memorySize: 64 });
assert.ok(await wtns.check(dir + "circuit.r1cs", witness));
}
});
test("untrusted envelopes have bounded, canonical, versioned public inputs", () => {
for (const change of [
{ route },
{ verificationKeyId: "foreign" },
{ circuitVersion: "v2" },
{ schemaVersion: 2 },
{ publicSignals: [42] },
{ publicSignals: ["01"] },
{ publicSignals: [scalarField.toString()] },
{ publicSignals: [] },
{ proof: { ...vector.proof, pi_a: ["1", "-1", "1"] } },
{ proof: { ...vector.proof, pi_b: [] } },
{ proof: { ...vector.proof, extra: 1 } },
])
assert.throws(() =>
parseArtifact(JSON.stringify({ ...vector, ...change })),
);
for (const bad of ["{", "x".repeat(4097)])
assert.throws(() => parseArtifact(bad));
for (const bad of ["#x=y", "#p=!", "#p=" + "A".repeat(6000)])
assert.throws(() => readFragment(bad));
});