Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

New package for general-purpose zero-knowledge circuits #76

Merged
merged 17 commits into from
Nov 29, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions .eslintrc.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,14 @@
"env": {
"es6": true
},
"extends": ["airbnb-base", "airbnb-typescript/base", "plugin:jest/recommended", "plugin:jest/style", "prettier"],
"extends": ["airbnb-base", "airbnb-typescript/base", "prettier"],
"parser": "@typescript-eslint/parser",
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"project": ["./tsconfig.json", "./packages/**/tsconfig.json"]
},
"plugins": ["@typescript-eslint", "jest"],
"plugins": ["@typescript-eslint"],
"rules": {
"no-console": ["warn", { "allow": ["info", "warn", "error"] }],
"no-restricted-syntax": "off",
Expand Down
7 changes: 4 additions & 3 deletions .github/workflows/production.yml
Original file line number Diff line number Diff line change
Expand Up @@ -51,8 +51,9 @@ jobs:
strategy:
matrix:
type:
- js
- sol
- circuits
- contracts
- libraries

steps:
- name: Checkout
Expand Down Expand Up @@ -86,7 +87,7 @@ jobs:
- name: Install dependencies
run: yarn

- name: Test contracts or libraries
- name: Test libraries, contracts and circuits
run: yarn test:${{ matrix.type }}

- name: Coveralls
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/pull-requests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -79,5 +79,5 @@ jobs:
- name: Install dependencies
run: yarn

- name: Test contracts and libraries
- name: Test libraries, contracts and circuits
cedoor marked this conversation as resolved.
Show resolved Hide resolved
run: yarn test
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,8 @@

♚ [Yarn workspaces](https://yarnpkg.com/features/workspaces): minimal monorepo package management (`yarn`, `yarn build`, `yarn docs`)\
♛ [Conventional Commits](https://www.conventionalcommits.org): human and machine readable meaning to commit messages (`yarn commit`)\
♜ [Jest](https://jestjs.io/): tests and test coverage for all packages (`yarn test`, `yarn test:all`)\
♜ [Jest](https://jestjs.io/): tests and test coverage for all libraries (`yarn test:libraries`)\
♜ [Mocha](https://mochajs.org/): tests for circuits and contracts (`yarn test:circuits`, `yarn test:contracts`)\
♞ [ESLint](https://eslint.org/), [Prettier](https://prettier.io/): code quality and formatting (`yarn prettier` & `yarn lint`)\
♝ [Typedocs](https://typedoc.org/): documentation generator for TypeScript (`yarn docs`)\
♟ [Benny](https://github.com/caderek/benny): simple benchmarking framework for JavaScript/TypeScript (`yarn benchmarks`)\
Expand Down Expand Up @@ -277,7 +278,7 @@ It will also automatically check that the modified files comply with ESLint and

### Testing

Test the code with coverage:
Test the code:

```bash
yarn test
Expand Down
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", "imt.sol", "rollup-plugin-rust", "lazytower.sol", "lazytower.circom"]

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
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,10 @@
"build": "yarn build:js && yarn compile:sol",
"build:js": "yarn workspaces foreach --no-private run build",
"compile:sol": "yarn workspaces foreach run compile",
"test": "yarn test:js && yarn test:sol",
"test:js": "jest --coverage",
"test:sol": "yarn workspace imt.sol test:coverage",
"test": "yarn test:libraries && yarn test:contracts && yarn test:circuits",
cedoor marked this conversation as resolved.
Show resolved Hide resolved
"test:libraries": "jest --coverage",
"test:circuits": "yarn workspace @zk-kit/circuits test",
"test:contracts": "yarn workspace imt.sol test:coverage",
"lint": "eslint . --ext .js,.ts && yarn workspace imt.sol lint",
"prettier": "prettier -c .",
"prettier:write": "prettier -w .",
Expand Down Expand Up @@ -57,7 +58,6 @@
"eslint-config-airbnb-typescript": "^16.1.0",
"eslint-config-prettier": "^8.3.0",
"eslint-plugin-import": "^2.25.2",
"eslint-plugin-jest": "^25.7.0",
"husky": "^8.0.3",
"jest": "^27.4.1",
"jest-config": "^27.4.7",
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
circom/main
circom/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": "./**/*.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.
54 changes: 54 additions & 0 deletions packages/circuits/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
<p align="center">
<h1 align="center">
ZK-kit circuits
</h1>
<p align="center">A comprehensive library of general-purpose zero-knowledge circuits.</p>
</p>

<p align="center">
<a href="https://github.com/privacy-scaling-explorations/zk-kit">
<img src="https://img.shields.io/badge/project-zk--kit-blue.svg?style=flat-square">
</a>
<a href="https://github.com/privacy-scaling-explorations/zk-kit/tree/main/packages/circuits.sol/LICENSE">
<img alt="Github license" src="https://img.shields.io/github/license/privacy-scaling-explorations/zk-kit.svg?style=flat-square">
</a>
<a href="https://www.npmjs.com/package/@zk-kit/circuits">
<img alt="NPM version" src="https://img.shields.io/npm/v/@zk-kit/circuits?style=flat-square" />
</a>
<a href="https://npmjs.org/package/@zk-kit/circuits">
<img alt="Downloads" src="https://img.shields.io/npm/dm/@zk-kit/circuits.svg?style=flat-square" />
</a>
</p>

<div align="center">
<h4>
<a href="https://appliedzkp.org/discord">
🗣️ Chat &amp; Support
</a>
</h4>
</div>

| This package offers a collection of reusable circuits designed for integration into other projects or protocols, promoting code modularization within the zero-knowledge ecosystem. |
| ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |

## Circuits

- Circom:
- [PoseidonProof](./circom/poseidon-proof.circom): It proves the possession of a Poseidon pre-image without revealing the pre-image itself.
- [BinaryMerkleRoot](./circom/binary-merkle-root.circom): It calculates the root of a binary Merkle tree using a provided proof-of-membership.

## 🛠 Install

### npm or yarn

Install the `@zk-kit/circuits` package with npm:

```bash
npm i @zk-kit/circuits --save
```

or yarn:

```bash
yarn add @zk-kit/circuits
cedoor marked this conversation as resolved.
Show resolved Hide resolved
```
41 changes: 41 additions & 0 deletions packages/circuits/circom/binary-merkle-root.circom
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
pragma circom 2.1.5;

include "poseidon.circom";
include "mux1.circom";
include "comparators.circom";

// This circuit is designed to calculate the root of a binary Merkle
// tree given a leaf, its depth, and the necessary sibling
// information (aka proof of membership).
// A circuit is designed without the capability to iterate through
// a dynamic array. To address this, a parameter with the static maximum
// tree depth is defined (i.e. 'MAX_DEPTH'). And additionally, the circuit
// receives a dynamic depth as an input, which is utilized in calculating the
// true root of the Merkle tree. The actual depth of the Merkle tree
// may be equal to or less than the static maximum depth.
template BinaryMerkleRoot(MAX_DEPTH) {
signal input leaf, depth, indices[MAX_DEPTH], siblings[MAX_DEPTH];

signal output out;

signal nodes[MAX_DEPTH + 1];
nodes[0] <== leaf;

signal roots[MAX_DEPTH];
var root = 0;

for (var i = 0; i < MAX_DEPTH; i++) {
var a = IsEqual()([depth, i]);

roots[i] <== a * nodes[i];

root += roots[i];

var c[2][2] = [ [nodes[i], siblings[i]], [siblings[i], nodes[i]] ];
var childNodes[2] = MultiMux1(2)(c, indices[i]);

nodes[i + 1] <== Poseidon(2)(childNodes);
}

out <== root;
}
11 changes: 11 additions & 0 deletions packages/circuits/circom/circuits.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
{
"poseidon-proof": {
"file": "poseidon-proof",
"template": "PoseidonProof"
},
"binary-merkle-root": {
"file": "binary-merkle-root",
"template": "BinaryMerkleRoot",
"params": [4]
}
}
24 changes: 24 additions & 0 deletions packages/circuits/circom/poseidon-proof.circom
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
pragma circom 2.1.5;

include "poseidon.circom";

// This circuit can be used to prove the possession of a pre-image of a
// hash without revealing the pre-image itself. It utilizes the Poseidon
// hash function, a highly efficient and secure hash function suited
// for zero-knowledge proof contexts.
// A scope value can be used to define a nullifier to prevent the same
// proof from being re-used twice.
template PoseidonProof() {
// The circuit takes two inputs: the pre-image and an additional scope parameter.
signal input preimage;
signal input scope;

// It applies the Poseidon hash function to the pre-image to produce a hash digest.
signal output digest;
digest <== Poseidon(1)([preimage]);

// A nullifier is also computed using both the pre-image and the scope, providing a value
// to prevent the same proof from being reused twice.
signal output nullifier;
nullifier <== Poseidon(2)([scope, preimage]);
}
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": "./circom/circuits.json",
"dirPtau": "./ptau",
"dirCircuits": "./circom",
"dirInputs": "./inputs",
"dirBuild": "./build",
"optimization": 1,
"inspect": true,
"include": ["../../node_modules/circomlib/circuits"],
"groth16numContributions": 1,
"groth16askForEntropy": false,
"logLevel": "INFO",
"verbose": true
}
Empty file.
32 changes: 32 additions & 0 deletions packages/circuits/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
{
"name": "@zk-kit/circuits",
"version": "0.2.0",
"description": "A comprehensive library of general-purpose zero-knowledge circuits.",
"license": "MIT",
"files": [
"circom",
"noir",
"LICENSE",
"README.md"
],
"repository": "[email protected]:privacy-scaling-explorations/zk-kit.git",
"homepage": "https://github.com/privacy-scaling-explorations/zk-kit/tree/main/packages/circuits.sol",
"scripts": {
"circom:compile": "circomkit compile",
"circom:setup": "circomkit setup",
"test": "mocha"
},
"dependencies": {
"circomlib": "^2.0.5"
},
"devDependencies": {
"@types/mocha": "^10.0.6",
"@zk-kit/smt": "workspace:^",
"circomkit": "0.0.19",
"mocha": "^10.2.0",
"poseidon-lite": "^0.2.0"
},
"publishConfig": {
"access": "public"
}
}
58 changes: 58 additions & 0 deletions packages/circuits/tests/binary-merkle-root.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { LeanIMT } from "@zk-kit/imt"
cedoor marked this conversation as resolved.
Show resolved Hide resolved
import { WitnessTester } from "circomkit"
import { poseidon2 } from "poseidon-lite"
import { circomkit } from "./common"

describe("binary-merkle-root", () => {
let circuit: WitnessTester<["leaf", "depth", "indices", "siblings"], ["out"]>

const MAX_DEPTH = 20

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

tree.insert(leaf)

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

const { siblings, 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 indices: number[] = []

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

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

const INPUT = {
leaf,
depth: tree.depth,
indices,
siblings
}

const OUTPUT = {
out: tree.root
}

before(async () => {
circuit = await circomkit.WitnessTester("binary-merkle-root", {
file: "binary-merkle-root",
template: "BinaryMerkleRoot",
params: [MAX_DEPTH]
})
})

it("Should calculate the root correctly", async () => {
await circuit.expectPass(INPUT, OUTPUT)
})
})
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
})
Loading
Loading