Skip to content

Commit

Permalink
feat(circuits): update semaphore circuits
Browse files Browse the repository at this point in the history
re #357
  • Loading branch information
cedoor committed Dec 5, 2023
1 parent 9e84c93 commit 96403b7
Show file tree
Hide file tree
Showing 16 changed files with 591 additions and 146 deletions.
5 changes: 1 addition & 4 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,6 @@ packages/contracts/deployed-contracts/undefined.json
packages/contracts/deployed-contracts/hardhat.json
packages/contracts/deployed-contracts/localhost.json

# circuits
circuits

# contracts
Verifier*.sol

Expand All @@ -44,4 +41,4 @@ snark-artifacts

# Next.js
.next/
public
public
3 changes: 3 additions & 0 deletions jest.config.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,12 @@
import fs from "fs"
import type { Config } from "@jest/types"

const exclude = ["circuits", "contracts"]

const projects: any = fs
.readdirSync("./packages", { withFileTypes: true })
.filter((directory) => directory.isDirectory())
.filter((directory) => !exclude.includes(directory.name))
.map(({ name }) => ({
rootDir: `packages/${name}`,
displayName: name,
Expand Down
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
"test": "yarn test:libraries && yarn test:contracts",
"test:libraries": "jest --coverage",
"test:contracts": "yarn workspace contracts test:coverage",
"test:circuits": "yarn workspace @semaphore-protocol/circuits test",
"lint": "eslint . --ext .js,.ts && yarn workspace contracts lint",
"prettier": "prettier -c .",
"prettier:write": "prettier -w .",
Expand Down
3 changes: 3 additions & 0 deletions packages/circuits/.gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
ptau
main
test
7 changes: 7 additions & 0 deletions packages/circuits/.mocharc.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"extension": ["ts"],
"require": "ts-node/register",
"spec": "./tests/*.test.ts",
"timeout": 100000,
"exit": true
}
21 changes: 21 additions & 0 deletions packages/circuits/LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2023 Ethereum Foundation

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
10 changes: 8 additions & 2 deletions packages/circuits/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,14 @@
<a href="https://github.com/semaphore-protocol">
<img src="https://img.shields.io/badge/project-Semaphore-blue.svg?style=flat-square">
</a>
<a href="https://github.com/semaphore-protocol/semaphore/blob/main/LICENSE">
<img alt="Github license" src="https://img.shields.io/github/license/semaphore-protocol/semaphore.svg?style=flat-square">
<a href="https://github.com/semaphore-protocol/semaphore/tree/main/packages/circuits/LICENSE">
<img alt="NPM license" src="https://img.shields.io/npm/l/%40semaphore-protocol%2Fcircuits?style=flat-square">
</a>
<a href="https://www.npmjs.com/package/@semaphore-protocol/circuits">
<img alt="NPM version" src="https://img.shields.io/npm/v/@semaphore-protocol/circuits?style=flat-square" />
</a>
<a href="https://npmjs.org/package/@semaphore-protocol/circuits">
<img alt="Downloads" src="https://img.shields.io/npm/dm/@semaphore-protocol/circuits.svg?style=flat-square" />
</a>
</p>

Expand Down
17 changes: 17 additions & 0 deletions packages/circuits/circomkit.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
{
"protocol": "groth16",
"prime": "bn128",
"version": "2.1.5",
"circuits": "./circuits.json",
"dirPtau": "./ptau",
"dirCircuits": "./",
"dirInputs": "./inputs",
"dirBuild": "./build",
"optimization": 1,
"inspect": true,
"include": ["../../node_modules/circomlib/circuits", "../../node_modules/@zk-kit/circuits/circom"],
"groth16numContributions": 1,
"groth16askForEntropy": false,
"logLevel": "INFO",
"verbose": true
}
7 changes: 7 additions & 0 deletions packages/circuits/circuits.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
{
"semaphore": {
"file": "semaphore",
"template": "Semaphore",
"params": [4]
}
}
37 changes: 34 additions & 3 deletions packages/circuits/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,38 @@
{
"name": "circuits",
"private": true,
"name": "@semaphore-protocol/circuits",
"version": "3.15.1",
"description": "Semaphore Circom circuits to generate zero-knowledge proofs.",
"license": "MIT",
"files": [
"**/*.circom",
"!main",
"!test",
"LICENSE",
"README.md"
],
"repository": "https://github.com/semaphore-protocol/semaphore",
"homepage": "https://github.com/semaphore-protocol/semaphore/tree/main/packages/data",
"bugs": {
"url": "https://github.com/semaphore-protocol/semaphore.git/issues"
},
"scripts": {
"compile": "circomkit compile semaphore",
"setup": "circomkit setup semaphore",
"test": "mocha"
},
"publishConfig": {
"access": "public"
},
"dependencies": {
"circomlib": "^2.0.2"
"@zk-kit/circuits": "0.2.3",
"circomlib": "2.0.5"
},
"devDependencies": {
"@types/mocha": "^10.0.6",
"@zk-kit/eddsa-poseidon": "0.3.1",
"@zk-kit/imt": "^2.0.0-beta",
"circomkit": "^0.0.19",
"mocha": "^10.2.0",
"poseidon-lite": "^0.2.0"
}
}
Binary file removed packages/circuits/scheme.png
Binary file not shown.
99 changes: 17 additions & 82 deletions packages/circuits/semaphore.circom
Original file line number Diff line number Diff line change
@@ -1,90 +1,25 @@
pragma circom 2.0.0;
pragma circom 2.1.5;

include "../node_modules/circomlib/circuits/poseidon.circom";
include "./tree.circom";
include "babyjub.circom";
include "poseidon.circom";
include "binary-merkle-root.circom";

template CalculateSecret() {
signal input identityNullifier;
signal input identityTrapdoor;
template Semaphore(MAX_DEPTH) {
signal input privateKey;
signal input treeDepth, treeIndices[MAX_DEPTH], treeSiblings[MAX_DEPTH];
signal input message;
signal input scope;

signal output out;
signal output treeRoot, nullifier;

component poseidon = Poseidon(2);
var Ax, Ay;
(Ax, Ay) = BabyPbk()(privateKey);

poseidon.inputs[0] <== identityNullifier;
poseidon.inputs[1] <== identityTrapdoor;
var treeLeaf = Poseidon(2)([Ax, Ay]);

out <== poseidon.out;
}

template CalculateIdentityCommitment() {
signal input secret;

signal output out;

component poseidon = Poseidon(1);
treeRoot <== BinaryMerkleRoot(MAX_DEPTH)(treeLeaf, treeDepth, treeIndices, treeSiblings);
nullifier <== Poseidon(2)([scope, privateKey]);

poseidon.inputs[0] <== secret;

out <== poseidon.out;
// Dummy constraint to prevent compiler from optimizing it.
signal dummySquare <== message * message;
}

template CalculateNullifierHash() {
signal input externalNullifier;
signal input identityNullifier;

signal output out;

component poseidon = Poseidon(2);

poseidon.inputs[0] <== externalNullifier;
poseidon.inputs[1] <== identityNullifier;

out <== poseidon.out;
}

// The current Semaphore smart contracts require nLevels <= 32 and nLevels >= 16.
template Semaphore(nLevels) {
signal input identityNullifier;
signal input identityTrapdoor;
signal input treePathIndices[nLevels];
signal input treeSiblings[nLevels];

signal input signalHash;
signal input externalNullifier;

signal output root;
signal output nullifierHash;

component calculateSecret = CalculateSecret();
calculateSecret.identityNullifier <== identityNullifier;
calculateSecret.identityTrapdoor <== identityTrapdoor;

signal secret;
secret <== calculateSecret.out;

component calculateIdentityCommitment = CalculateIdentityCommitment();
calculateIdentityCommitment.secret <== secret;

component calculateNullifierHash = CalculateNullifierHash();
calculateNullifierHash.externalNullifier <== externalNullifier;
calculateNullifierHash.identityNullifier <== identityNullifier;

component inclusionProof = MerkleTreeInclusionProof(nLevels);
inclusionProof.leaf <== calculateIdentityCommitment.out;

for (var i = 0; i < nLevels; i++) {
inclusionProof.siblings[i] <== treeSiblings[i];
inclusionProof.pathIndices[i] <== treePathIndices[i];
}

root <== inclusionProof.root;

// Dummy square to prevent tampering signalHash.
signal signalHashSquared;
signalHashSquared <== signalHash * signalHash;

nullifierHash <== calculateNullifierHash.out;
}

component main {public [signalHash, externalNullifier]} = Semaphore(20);
12 changes: 12 additions & 0 deletions packages/circuits/tests/common.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
import { Circomkit } from "circomkit"
import { readFileSync } from "fs"
import path from "path"

const configFilePath = path.join(__dirname, "../circomkit.json")
const config = JSON.parse(readFileSync(configFilePath, "utf-8"))

// eslint-disable-next-line import/prefer-default-export
export const circomkit = new Circomkit({
...config,
verbose: false
})
72 changes: 72 additions & 0 deletions packages/circuits/tests/semaphore.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
import { derivePublicKey, deriveSecretScalar } from "@zk-kit/eddsa-poseidon"
import { LeanIMT } from "@zk-kit/imt"
import { WitnessTester } from "circomkit"
import { poseidon2 } from "poseidon-lite"
import { circomkit } from "./common"

describe("semaphore", () => {
let circuit: WitnessTester<
["privateKey", "treeDepth", "treeIndices", "treeSiblings", "scope", "message"],
["nullifier", "treeRoot"]
>

const MAX_DEPTH = 20

const scope = 32
const message = 43

const privateKey = 1
const publicKey = derivePublicKey(privateKey)

const leaf = poseidon2(publicKey)

const tree = new LeanIMT((a, b) => poseidon2([a, b]))

tree.insert(leaf)

for (let i = 1; i < 4; i += 1) {
tree.insert(BigInt(i))
}

const { siblings: treeSiblings, index } = tree.generateProof(0)

// The index must be converted to a list of indices, 1 for each tree level.
// The circuit tree depth is 20, so the number of siblings must be 20, even if
// the tree depth is actually 3. The missing siblings can be set to 0, as they
// won't be used to calculate the root in the circuit.
const treeIndices: number[] = []

for (let i = 0; i < MAX_DEPTH; i += 1) {
treeIndices.push((index >> i) & 1)

if (treeSiblings[i] === undefined) {
treeSiblings[i] = BigInt(0)
}
}

const INPUT = {
privateKey: deriveSecretScalar(privateKey),
treeDepth: tree.depth,
treeIndices,
treeSiblings,
scope,
message
}

const OUTPUT = {
nullifier: poseidon2([scope, deriveSecretScalar(privateKey)]),
treeRoot: tree.root
}

before(async () => {
circuit = await circomkit.WitnessTester("semaphore", {
file: "semaphore",
template: "Semaphore",
params: [MAX_DEPTH]
})
})

it("Should calculate the root and the nullifier correctly", async () => {
await circuit.expectPass(INPUT, OUTPUT)
})
})
40 changes: 0 additions & 40 deletions packages/circuits/tree.circom

This file was deleted.

Loading

0 comments on commit 96403b7

Please sign in to comment.