@semaphore-protocol/proof 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2022 Ethereum Foundation
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,87 @@
1
+ <p align="center">
2
+ <h1 align="center">
3
+ Semaphore proof
4
+ </h1>
5
+ <p align="center">A library for generating and verifying Semaphore proofs.</p>
6
+ </p>
7
+
8
+ <p align="center">
9
+ <a href="https://github.com/semaphore-protocol/semaphore.js">
10
+ <img src="https://img.shields.io/badge/project-semaphore.js-blue.svg?style=flat-square">
11
+ </a>
12
+ <a href="https://github.com/semaphore-protocol/semaphore.js/blob/main/packages/proof/LICENSE">
13
+ <img alt="Github license" src="https://img.shields.io/github/license/semaphore-protocol/semaphore.js.svg?style=flat-square">
14
+ </a>
15
+ <a href="https://www.npmjs.com/package/@semaphore-protocol/proof">
16
+ <img alt="NPM version" src="https://img.shields.io/npm/v/@semaphore-protocol/proof?style=flat-square" />
17
+ </a>
18
+ <a href="https://npmjs.org/package/@semaphore-protocol/proof">
19
+ <img alt="Downloads" src="https://img.shields.io/npm/dm/@semaphore-protocol/proof.svg?style=flat-square" />
20
+ </a>
21
+ <a href="https://eslint.org/">
22
+ <img alt="Linter eslint" src="https://img.shields.io/badge/linter-eslint-8080f2?style=flat-square&logo=eslint" />
23
+ </a>
24
+ <a href="https://prettier.io/">
25
+ <img alt="Code style prettier" src="https://img.shields.io/badge/code%20style-prettier-f8bc45?style=flat-square&logo=prettier" />
26
+ </a>
27
+ </p>
28
+
29
+ <div align="center">
30
+ <h4>
31
+ <a href="https://t.me/joinchat/B-PQx1U3GtAh--Z4Fwo56A">
32
+ 🗣️ Chat &amp; Support
33
+ </a>
34
+ <span>&nbsp;&nbsp;|&nbsp;&nbsp;</span>
35
+ <a href="https://semaphore-protocol.github.io/semaphore.js/proof">
36
+ 📘 Docs
37
+ </a>
38
+ </h4>
39
+ </div>
40
+
41
+ ---
42
+
43
+ ## 🛠 Install
44
+
45
+ ### npm or yarn
46
+
47
+ Install the `@semaphore-protocol/proof` package with npm:
48
+
49
+ ```bash
50
+ npm i @semaphore-protocol/proof
51
+ ```
52
+
53
+ or yarn:
54
+
55
+ ```bash
56
+ yarn add @semaphore-protocol/proof
57
+ ```
58
+
59
+ ## 📜 Usage
60
+
61
+ ### Generating Merkle proofs
62
+
63
+ ```typescript
64
+ import { Identity } from "@semaphore-protocol/identity"
65
+ import { generateMerkleProof } from "@semaphore-protocol/proof"
66
+
67
+ const depth = 20
68
+ const zeroValue = BigInt(0)
69
+ const identity = new Identity()
70
+ const identityCommitment = identity.genIdentityCommitment()
71
+ const identityCommitments = [BigInt(1), identityCommitment, BigInt(2)]
72
+
73
+ const merkleProof = generateMerkleProof(depth, zeroValue, identityCommitments, 1)
74
+ ```
75
+
76
+ ### Creating Semaphore proofs
77
+
78
+ ```typescript
79
+ import { Semaphore } from "@semaphore-protocol/protocols"
80
+
81
+ const signal = "Hello world"
82
+ const externalNullifier = BigInt(1)
83
+ const witness = Semaphore.genWitness(identity, merkleProof, externalNullifier, signal)
84
+
85
+ const { proof, publicSignals } = await Semaphore.genProof(witness, "./semaphore.wasm", "./semaphore.zkey")
86
+ const solidityProof = Semaphore.packToSolidityProof(proof)
87
+ ```
package/dist/index.mjs ADDED
@@ -0,0 +1,218 @@
1
+ /**
2
+ * @module @semaphore-protocol/proof
3
+ * @version 0.1.0
4
+ * @file A library for generating and verifying Semaphore proofs.
5
+ * @copyright Ethereum Foundation 2022
6
+ * @license MIT
7
+ * @see [Github]{@link https://github.com/semaphore-protocol/semaphore.js/tree/main/packages/proof}
8
+ */
9
+ import { keccak256 } from '@ethersproject/solidity';
10
+ import { formatBytes32String } from '@ethersproject/strings';
11
+ import { poseidon } from 'circomlibjs';
12
+ import { groth16 } from 'snarkjs';
13
+ import { IncrementalMerkleTree } from '@zk-kit/incremental-merkle-tree';
14
+
15
+ /*! *****************************************************************************
16
+ Copyright (c) Microsoft Corporation.
17
+
18
+ Permission to use, copy, modify, and/or distribute this software for any
19
+ purpose with or without fee is hereby granted.
20
+
21
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
22
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
23
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
24
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
25
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
26
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
27
+ PERFORMANCE OF THIS SOFTWARE.
28
+ ***************************************************************************** */
29
+
30
+ function __awaiter(thisArg, _arguments, P, generator) {
31
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
32
+ return new (P || (P = Promise))(function (resolve, reject) {
33
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
34
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
35
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
36
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
37
+ });
38
+ }
39
+
40
+ function __generator(thisArg, body) {
41
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
42
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
43
+ function verb(n) { return function (v) { return step([n, v]); }; }
44
+ function step(op) {
45
+ if (f) throw new TypeError("Generator is already executing.");
46
+ while (_) try {
47
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
48
+ if (y = 0, t) op = [op[0] & 2, t.value];
49
+ switch (op[0]) {
50
+ case 0: case 1: t = op; break;
51
+ case 4: _.label++; return { value: op[1], done: false };
52
+ case 5: _.label++; y = op[1]; op = [0]; continue;
53
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
54
+ default:
55
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
56
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
57
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
58
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
59
+ if (t[2]) _.ops.pop();
60
+ _.trys.pop(); continue;
61
+ }
62
+ op = body.call(thisArg, _);
63
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
64
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
65
+ }
66
+ }
67
+
68
+ var Semaphore = /** @class */ (function () {
69
+ function Semaphore() {
70
+ }
71
+ /**
72
+ * Generates a SnarkJS full proof with Groth16.
73
+ * @param witness The parameters for creating the proof.
74
+ * @param wasmFilePath The WASM file path.
75
+ * @param finalZkeyPath The ZKey file path.
76
+ * @returns The full SnarkJS proof.
77
+ */
78
+ /* istanbul ignore next */
79
+ Semaphore.genProof = function (witness, wasmFilePath, finalZkeyPath) {
80
+ return __awaiter(this, void 0, void 0, function () {
81
+ var _a, proof, publicSignals;
82
+ return __generator(this, function (_b) {
83
+ switch (_b.label) {
84
+ case 0: return [4 /*yield*/, groth16.fullProve(witness, wasmFilePath, finalZkeyPath, null)];
85
+ case 1:
86
+ _a = _b.sent(), proof = _a.proof, publicSignals = _a.publicSignals;
87
+ return [2 /*return*/, {
88
+ proof: proof,
89
+ publicSignals: {
90
+ merkleRoot: publicSignals[0],
91
+ nullifierHash: publicSignals[1],
92
+ signalHash: publicSignals[2],
93
+ externalNullifier: publicSignals[3]
94
+ }
95
+ }];
96
+ }
97
+ });
98
+ });
99
+ };
100
+ /**
101
+ * Verifies a zero-knowledge SnarkJS proof.
102
+ * @param verificationKey The zero-knowledge verification key.
103
+ * @param fullProof The SnarkJS full proof.
104
+ * @returns True if the proof is valid, false otherwise.
105
+ */
106
+ /* istanbul ignore next */
107
+ Semaphore.verifyProof = function (verificationKey, _a) {
108
+ var proof = _a.proof, publicSignals = _a.publicSignals;
109
+ return groth16.verify(verificationKey, [
110
+ publicSignals.merkleRoot,
111
+ publicSignals.nullifierHash,
112
+ publicSignals.signalHash,
113
+ publicSignals.externalNullifier
114
+ ], proof);
115
+ };
116
+ /**
117
+ * Creates a Semaphore witness for the Semaphore ZK proof.
118
+ * @param identityTrapdoor The identity trapdoor.
119
+ * @param identityNullifier The identity nullifier.
120
+ * @param merkleProof The Merkle proof that identity exists in Semaphore tree.
121
+ * @param externalNullifier The topic on which vote should be broadcasted.
122
+ * @param signal The signal that should be broadcasted.
123
+ * @returns The Semaphore witness.
124
+ */
125
+ Semaphore.genWitness = function (identityTrapdoor, identityNullifier, merkleProof, externalNullifier, signal) {
126
+ return {
127
+ identityNullifier: identityNullifier,
128
+ identityTrapdoor: identityTrapdoor,
129
+ treePathIndices: merkleProof.pathIndices,
130
+ treeSiblings: merkleProof.siblings,
131
+ externalNullifier: externalNullifier,
132
+ signalHash: Semaphore.genSignalHash(signal)
133
+ };
134
+ };
135
+ /**
136
+ * Generates a nullifier by hashing the external and the identity nullifiers.
137
+ * @param externalNullifier The external nullifier.
138
+ * @param identityNullifier The identity nullifier.
139
+ * @returns The nullifier hash.
140
+ */
141
+ Semaphore.genNullifierHash = function (externalNullifier, identityNullifier) {
142
+ return poseidon([BigInt(externalNullifier), BigInt(identityNullifier)]);
143
+ };
144
+ /**
145
+ * Hashes a signal string with Keccak256.
146
+ * @param signal The Semaphore signal.
147
+ * @returns The signal hash.
148
+ */
149
+ Semaphore.genSignalHash = function (signal) {
150
+ return BigInt(keccak256(["bytes32"], [formatBytes32String(signal)])) >> BigInt(8);
151
+ };
152
+ /**
153
+ * Converts a full proof in a proof compatible with the Verifier.sol method inputs.
154
+ * @param proof The proof generated with SnarkJS.
155
+ * @returns The Solidity compatible proof.
156
+ */
157
+ /* istanbul ignore next */
158
+ Semaphore.packToSolidityProof = function (proof) {
159
+ return [
160
+ proof.pi_a[0],
161
+ proof.pi_a[1],
162
+ proof.pi_b[0][1],
163
+ proof.pi_b[0][0],
164
+ proof.pi_b[1][1],
165
+ proof.pi_b[1][0],
166
+ proof.pi_c[0],
167
+ proof.pi_c[1]
168
+ ];
169
+ };
170
+ return Semaphore;
171
+ }());
172
+
173
+ BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
174
+ function genExternalNullifier(plaintext) {
175
+ var hashed = keccak256(["string"], [plaintext]);
176
+ var hexStr = "0x".concat(hashed.slice(8));
177
+ var len = 32 * 2;
178
+ var h = hexStr.slice(2, len + 2);
179
+ return "0x".concat(h.padStart(len, "0"));
180
+ }
181
+ /**
182
+ * Creates a Merkle tree.
183
+ * @param depth The depth of the tree.
184
+ * @param zeroValue The zero value of the tree.
185
+ * @param leaves The list of the leaves of the tree.
186
+ * @returns The Merkle tree.
187
+ */
188
+ function generateMerkleTree(depth, zeroValue, leaves) {
189
+ var tree = new IncrementalMerkleTree(poseidon, depth, zeroValue, 2);
190
+ for (var _i = 0, leaves_1 = leaves; _i < leaves_1.length; _i++) {
191
+ var leaf = leaves_1[_i];
192
+ tree.insert(BigInt(leaf));
193
+ }
194
+ return tree;
195
+ }
196
+ /**
197
+ * Creates a Merkle proof.
198
+ * @param depth The depth of the tree.
199
+ * @param zeroValue The zero value of the tree.
200
+ * @param leaves The list of the leaves of the tree.
201
+ * @param leaf The leaf for which Merkle proof should be created.
202
+ * @returns The Merkle proof.
203
+ */
204
+ function generateMerkleProof(depth, zeroValue, leaves, leaf) {
205
+ if (leaf === zeroValue) {
206
+ throw new Error("Can't generate a proof for a zero leaf");
207
+ }
208
+ var tree = generateMerkleTree(depth, zeroValue, leaves);
209
+ var leafIndex = tree.leaves.indexOf(BigInt(leaf));
210
+ if (leafIndex === -1) {
211
+ throw new Error("The leaf does not exist");
212
+ }
213
+ var merkleProof = tree.createProof(leafIndex);
214
+ merkleProof.siblings = merkleProof.siblings.map(function (s) { return s[0]; });
215
+ return merkleProof;
216
+ }
217
+
218
+ export { Semaphore, genExternalNullifier, generateMerkleProof, generateMerkleTree };
@@ -0,0 +1,225 @@
1
+ /**
2
+ * @module @semaphore-protocol/proof
3
+ * @version 0.1.0
4
+ * @file A library for generating and verifying Semaphore proofs.
5
+ * @copyright Ethereum Foundation 2022
6
+ * @license MIT
7
+ * @see [Github]{@link https://github.com/semaphore-protocol/semaphore.js/tree/main/packages/proof}
8
+ */
9
+ 'use strict';
10
+
11
+ Object.defineProperty(exports, '__esModule', { value: true });
12
+
13
+ var solidity = require('@ethersproject/solidity');
14
+ var strings = require('@ethersproject/strings');
15
+ var circomlibjs = require('circomlibjs');
16
+ var snarkjs = require('snarkjs');
17
+ var incrementalMerkleTree = require('@zk-kit/incremental-merkle-tree');
18
+
19
+ /*! *****************************************************************************
20
+ Copyright (c) Microsoft Corporation.
21
+
22
+ Permission to use, copy, modify, and/or distribute this software for any
23
+ purpose with or without fee is hereby granted.
24
+
25
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
26
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
27
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
28
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
29
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
30
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
31
+ PERFORMANCE OF THIS SOFTWARE.
32
+ ***************************************************************************** */
33
+
34
+ function __awaiter(thisArg, _arguments, P, generator) {
35
+ function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
36
+ return new (P || (P = Promise))(function (resolve, reject) {
37
+ function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
38
+ function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
39
+ function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
40
+ step((generator = generator.apply(thisArg, _arguments || [])).next());
41
+ });
42
+ }
43
+
44
+ function __generator(thisArg, body) {
45
+ var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
46
+ return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
47
+ function verb(n) { return function (v) { return step([n, v]); }; }
48
+ function step(op) {
49
+ if (f) throw new TypeError("Generator is already executing.");
50
+ while (_) try {
51
+ if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
52
+ if (y = 0, t) op = [op[0] & 2, t.value];
53
+ switch (op[0]) {
54
+ case 0: case 1: t = op; break;
55
+ case 4: _.label++; return { value: op[1], done: false };
56
+ case 5: _.label++; y = op[1]; op = [0]; continue;
57
+ case 7: op = _.ops.pop(); _.trys.pop(); continue;
58
+ default:
59
+ if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
60
+ if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
61
+ if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
62
+ if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
63
+ if (t[2]) _.ops.pop();
64
+ _.trys.pop(); continue;
65
+ }
66
+ op = body.call(thisArg, _);
67
+ } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
68
+ if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
69
+ }
70
+ }
71
+
72
+ var Semaphore = /** @class */ (function () {
73
+ function Semaphore() {
74
+ }
75
+ /**
76
+ * Generates a SnarkJS full proof with Groth16.
77
+ * @param witness The parameters for creating the proof.
78
+ * @param wasmFilePath The WASM file path.
79
+ * @param finalZkeyPath The ZKey file path.
80
+ * @returns The full SnarkJS proof.
81
+ */
82
+ /* istanbul ignore next */
83
+ Semaphore.genProof = function (witness, wasmFilePath, finalZkeyPath) {
84
+ return __awaiter(this, void 0, void 0, function () {
85
+ var _a, proof, publicSignals;
86
+ return __generator(this, function (_b) {
87
+ switch (_b.label) {
88
+ case 0: return [4 /*yield*/, snarkjs.groth16.fullProve(witness, wasmFilePath, finalZkeyPath, null)];
89
+ case 1:
90
+ _a = _b.sent(), proof = _a.proof, publicSignals = _a.publicSignals;
91
+ return [2 /*return*/, {
92
+ proof: proof,
93
+ publicSignals: {
94
+ merkleRoot: publicSignals[0],
95
+ nullifierHash: publicSignals[1],
96
+ signalHash: publicSignals[2],
97
+ externalNullifier: publicSignals[3]
98
+ }
99
+ }];
100
+ }
101
+ });
102
+ });
103
+ };
104
+ /**
105
+ * Verifies a zero-knowledge SnarkJS proof.
106
+ * @param verificationKey The zero-knowledge verification key.
107
+ * @param fullProof The SnarkJS full proof.
108
+ * @returns True if the proof is valid, false otherwise.
109
+ */
110
+ /* istanbul ignore next */
111
+ Semaphore.verifyProof = function (verificationKey, _a) {
112
+ var proof = _a.proof, publicSignals = _a.publicSignals;
113
+ return snarkjs.groth16.verify(verificationKey, [
114
+ publicSignals.merkleRoot,
115
+ publicSignals.nullifierHash,
116
+ publicSignals.signalHash,
117
+ publicSignals.externalNullifier
118
+ ], proof);
119
+ };
120
+ /**
121
+ * Creates a Semaphore witness for the Semaphore ZK proof.
122
+ * @param identityTrapdoor The identity trapdoor.
123
+ * @param identityNullifier The identity nullifier.
124
+ * @param merkleProof The Merkle proof that identity exists in Semaphore tree.
125
+ * @param externalNullifier The topic on which vote should be broadcasted.
126
+ * @param signal The signal that should be broadcasted.
127
+ * @returns The Semaphore witness.
128
+ */
129
+ Semaphore.genWitness = function (identityTrapdoor, identityNullifier, merkleProof, externalNullifier, signal) {
130
+ return {
131
+ identityNullifier: identityNullifier,
132
+ identityTrapdoor: identityTrapdoor,
133
+ treePathIndices: merkleProof.pathIndices,
134
+ treeSiblings: merkleProof.siblings,
135
+ externalNullifier: externalNullifier,
136
+ signalHash: Semaphore.genSignalHash(signal)
137
+ };
138
+ };
139
+ /**
140
+ * Generates a nullifier by hashing the external and the identity nullifiers.
141
+ * @param externalNullifier The external nullifier.
142
+ * @param identityNullifier The identity nullifier.
143
+ * @returns The nullifier hash.
144
+ */
145
+ Semaphore.genNullifierHash = function (externalNullifier, identityNullifier) {
146
+ return circomlibjs.poseidon([BigInt(externalNullifier), BigInt(identityNullifier)]);
147
+ };
148
+ /**
149
+ * Hashes a signal string with Keccak256.
150
+ * @param signal The Semaphore signal.
151
+ * @returns The signal hash.
152
+ */
153
+ Semaphore.genSignalHash = function (signal) {
154
+ return BigInt(solidity.keccak256(["bytes32"], [strings.formatBytes32String(signal)])) >> BigInt(8);
155
+ };
156
+ /**
157
+ * Converts a full proof in a proof compatible with the Verifier.sol method inputs.
158
+ * @param proof The proof generated with SnarkJS.
159
+ * @returns The Solidity compatible proof.
160
+ */
161
+ /* istanbul ignore next */
162
+ Semaphore.packToSolidityProof = function (proof) {
163
+ return [
164
+ proof.pi_a[0],
165
+ proof.pi_a[1],
166
+ proof.pi_b[0][1],
167
+ proof.pi_b[0][0],
168
+ proof.pi_b[1][1],
169
+ proof.pi_b[1][0],
170
+ proof.pi_c[0],
171
+ proof.pi_c[1]
172
+ ];
173
+ };
174
+ return Semaphore;
175
+ }());
176
+
177
+ BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
178
+ function genExternalNullifier(plaintext) {
179
+ var hashed = solidity.keccak256(["string"], [plaintext]);
180
+ var hexStr = "0x".concat(hashed.slice(8));
181
+ var len = 32 * 2;
182
+ var h = hexStr.slice(2, len + 2);
183
+ return "0x".concat(h.padStart(len, "0"));
184
+ }
185
+ /**
186
+ * Creates a Merkle tree.
187
+ * @param depth The depth of the tree.
188
+ * @param zeroValue The zero value of the tree.
189
+ * @param leaves The list of the leaves of the tree.
190
+ * @returns The Merkle tree.
191
+ */
192
+ function generateMerkleTree(depth, zeroValue, leaves) {
193
+ var tree = new incrementalMerkleTree.IncrementalMerkleTree(circomlibjs.poseidon, depth, zeroValue, 2);
194
+ for (var _i = 0, leaves_1 = leaves; _i < leaves_1.length; _i++) {
195
+ var leaf = leaves_1[_i];
196
+ tree.insert(BigInt(leaf));
197
+ }
198
+ return tree;
199
+ }
200
+ /**
201
+ * Creates a Merkle proof.
202
+ * @param depth The depth of the tree.
203
+ * @param zeroValue The zero value of the tree.
204
+ * @param leaves The list of the leaves of the tree.
205
+ * @param leaf The leaf for which Merkle proof should be created.
206
+ * @returns The Merkle proof.
207
+ */
208
+ function generateMerkleProof(depth, zeroValue, leaves, leaf) {
209
+ if (leaf === zeroValue) {
210
+ throw new Error("Can't generate a proof for a zero leaf");
211
+ }
212
+ var tree = generateMerkleTree(depth, zeroValue, leaves);
213
+ var leafIndex = tree.leaves.indexOf(BigInt(leaf));
214
+ if (leafIndex === -1) {
215
+ throw new Error("The leaf does not exist");
216
+ }
217
+ var merkleProof = tree.createProof(leafIndex);
218
+ merkleProof.siblings = merkleProof.siblings.map(function (s) { return s[0]; });
219
+ return merkleProof;
220
+ }
221
+
222
+ exports.Semaphore = Semaphore;
223
+ exports.genExternalNullifier = genExternalNullifier;
224
+ exports.generateMerkleProof = generateMerkleProof;
225
+ exports.generateMerkleTree = generateMerkleTree;
@@ -0,0 +1,5 @@
1
+ import { MerkleProof } from "@zk-kit/incremental-merkle-tree";
2
+ import Semaphore from "./semaphore";
3
+ import { generateMerkleProof, generateMerkleTree, genExternalNullifier } from "./utils";
4
+ export { Semaphore, generateMerkleProof, generateMerkleTree, genExternalNullifier, MerkleProof };
5
+ export * from "./types";
@@ -0,0 +1,48 @@
1
+ import { MerkleProof } from "@zk-kit/incremental-merkle-tree";
2
+ import { Proof, SemaphoreFullProof, SemaphoreSolidityProof, SemaphoreWitness, StrBigInt } from "./types";
3
+ export default class Semaphore {
4
+ /**
5
+ * Generates a SnarkJS full proof with Groth16.
6
+ * @param witness The parameters for creating the proof.
7
+ * @param wasmFilePath The WASM file path.
8
+ * @param finalZkeyPath The ZKey file path.
9
+ * @returns The full SnarkJS proof.
10
+ */
11
+ static genProof(witness: any, wasmFilePath: string, finalZkeyPath: string): Promise<SemaphoreFullProof>;
12
+ /**
13
+ * Verifies a zero-knowledge SnarkJS proof.
14
+ * @param verificationKey The zero-knowledge verification key.
15
+ * @param fullProof The SnarkJS full proof.
16
+ * @returns True if the proof is valid, false otherwise.
17
+ */
18
+ static verifyProof(verificationKey: string, { proof, publicSignals }: SemaphoreFullProof): Promise<boolean>;
19
+ /**
20
+ * Creates a Semaphore witness for the Semaphore ZK proof.
21
+ * @param identityTrapdoor The identity trapdoor.
22
+ * @param identityNullifier The identity nullifier.
23
+ * @param merkleProof The Merkle proof that identity exists in Semaphore tree.
24
+ * @param externalNullifier The topic on which vote should be broadcasted.
25
+ * @param signal The signal that should be broadcasted.
26
+ * @returns The Semaphore witness.
27
+ */
28
+ static genWitness(identityTrapdoor: StrBigInt, identityNullifier: StrBigInt, merkleProof: MerkleProof, externalNullifier: StrBigInt, signal: string): SemaphoreWitness;
29
+ /**
30
+ * Generates a nullifier by hashing the external and the identity nullifiers.
31
+ * @param externalNullifier The external nullifier.
32
+ * @param identityNullifier The identity nullifier.
33
+ * @returns The nullifier hash.
34
+ */
35
+ static genNullifierHash(externalNullifier: StrBigInt, identityNullifier: StrBigInt): bigint;
36
+ /**
37
+ * Hashes a signal string with Keccak256.
38
+ * @param signal The Semaphore signal.
39
+ * @returns The signal hash.
40
+ */
41
+ static genSignalHash(signal: string): bigint;
42
+ /**
43
+ * Converts a full proof in a proof compatible with the Verifier.sol method inputs.
44
+ * @param proof The proof generated with SnarkJS.
45
+ * @returns The Solidity compatible proof.
46
+ */
47
+ static packToSolidityProof(proof: Proof): SemaphoreSolidityProof;
48
+ }
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,36 @@
1
+ export declare type StrBigInt = string | bigint;
2
+ export declare type Proof = {
3
+ pi_a: StrBigInt[];
4
+ pi_b: StrBigInt[][];
5
+ pi_c: StrBigInt[];
6
+ protocol: string;
7
+ curve: string;
8
+ };
9
+ export declare type SemaphoreFullProof = {
10
+ proof: Proof;
11
+ publicSignals: SemaphorePublicSignals;
12
+ };
13
+ export declare type SemaphorePublicSignals = {
14
+ merkleRoot: StrBigInt;
15
+ nullifierHash: StrBigInt;
16
+ signalHash: StrBigInt;
17
+ externalNullifier: StrBigInt;
18
+ };
19
+ export declare type SemaphoreSolidityProof = [
20
+ StrBigInt,
21
+ StrBigInt,
22
+ StrBigInt,
23
+ StrBigInt,
24
+ StrBigInt,
25
+ StrBigInt,
26
+ StrBigInt,
27
+ StrBigInt
28
+ ];
29
+ export declare type SemaphoreWitness = {
30
+ identityNullifier: StrBigInt;
31
+ identityTrapdoor: StrBigInt;
32
+ treeSiblings: StrBigInt[];
33
+ treePathIndices: number[];
34
+ externalNullifier: StrBigInt;
35
+ signalHash: StrBigInt;
36
+ };
@@ -0,0 +1,21 @@
1
+ import { IncrementalMerkleTree, MerkleProof } from "@zk-kit/incremental-merkle-tree";
2
+ import { StrBigInt } from "./types";
3
+ export declare const SNARK_FIELD_SIZE: bigint;
4
+ export declare function genExternalNullifier(plaintext: string): string;
5
+ /**
6
+ * Creates a Merkle tree.
7
+ * @param depth The depth of the tree.
8
+ * @param zeroValue The zero value of the tree.
9
+ * @param leaves The list of the leaves of the tree.
10
+ * @returns The Merkle tree.
11
+ */
12
+ export declare function generateMerkleTree(depth: number, zeroValue: StrBigInt, leaves: StrBigInt[]): IncrementalMerkleTree;
13
+ /**
14
+ * Creates a Merkle proof.
15
+ * @param depth The depth of the tree.
16
+ * @param zeroValue The zero value of the tree.
17
+ * @param leaves The list of the leaves of the tree.
18
+ * @param leaf The leaf for which Merkle proof should be created.
19
+ * @returns The Merkle proof.
20
+ */
21
+ export declare function generateMerkleProof(depth: number, zeroValue: StrBigInt, leaves: StrBigInt[], leaf: StrBigInt): MerkleProof;
package/package.json ADDED
@@ -0,0 +1,44 @@
1
+ {
2
+ "name": "@semaphore-protocol/proof",
3
+ "version": "0.1.0",
4
+ "description": "A library for generating and verifying Semaphore proofs.",
5
+ "license": "MIT",
6
+ "main": "dist/index.node.js",
7
+ "exports": {
8
+ "import": "./dist/index.mjs",
9
+ "require": "./dist/index.node.js"
10
+ },
11
+ "types": "dist/types/index.d.ts",
12
+ "files": [
13
+ "dist/",
14
+ "src/",
15
+ "LICENSE",
16
+ "README.md"
17
+ ],
18
+ "repository": "https://github.com/semaphore-protocol/semaphore.js",
19
+ "homepage": "https://github.com/semaphore-protocol/semaphore.js/tree/main/packages/proof",
20
+ "scripts": {
21
+ "build:watch": "rollup -c rollup.config.ts -w --configPlugin typescript",
22
+ "build": "rimraf dist && rollup -c rollup.config.ts --configPlugin typescript",
23
+ "prepublishOnly": "yarn build",
24
+ "docs": "typedoc src/index.ts --out ../../docs/protocols"
25
+ },
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "devDependencies": {
30
+ "ffjavascript": "^0.2.54",
31
+ "rollup-plugin-cleanup": "^3.2.1",
32
+ "rollup-plugin-typescript2": "^0.31.2",
33
+ "typedoc": "^0.22.11"
34
+ },
35
+ "dependencies": {
36
+ "@ethersproject/bytes": "^5.5.0",
37
+ "@ethersproject/solidity": "^5.5.0",
38
+ "@ethersproject/strings": "^5.5.0",
39
+ "@zk-kit/incremental-merkle-tree": "^0.4.3",
40
+ "circomlibjs": "0.0.8",
41
+ "snarkjs": "^0.4.13"
42
+ },
43
+ "gitHead": "6c1b469a4b5ffaac562f478fc2bbc78731734e81"
44
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ import { MerkleProof } from "@zk-kit/incremental-merkle-tree"
2
+ import Semaphore from "./semaphore"
3
+ import { generateMerkleProof, generateMerkleTree, genExternalNullifier } from "./utils"
4
+
5
+ export { Semaphore, generateMerkleProof, generateMerkleTree, genExternalNullifier, MerkleProof }
6
+ export * from "./types"
@@ -0,0 +1,72 @@
1
+ import { Identity } from "@semaphore-protocol/identity"
2
+ import { getCurveFromName } from "ffjavascript"
3
+ import fs from "fs"
4
+ import path from "path"
5
+ import Semaphore from "./semaphore"
6
+ import { generateMerkleProof, genExternalNullifier } from "./utils"
7
+
8
+ describe("Semaphore", () => {
9
+ const assets = "./packages/proof/assets"
10
+
11
+ let curve: any
12
+
13
+ beforeAll(async () => {
14
+ curve = await getCurveFromName("bn128")
15
+ })
16
+
17
+ afterAll(async () => {
18
+ await curve.terminate()
19
+ })
20
+
21
+ describe("Generate and verify proof", () => {
22
+ it("Should generate a Semaphore witness", async () => {
23
+ const identity = new Identity()
24
+ const identityCommitment = identity.genIdentityCommitment()
25
+ const externalNullifier = genExternalNullifier("voting_1")
26
+ const leaves = [BigInt(3), BigInt(2), identityCommitment, BigInt(4)]
27
+ const signal = "0x111"
28
+
29
+ const merkleProof = generateMerkleProof(20, BigInt(0), leaves, identityCommitment)
30
+
31
+ const witness = Semaphore.genWitness(
32
+ identity.getTrapdoor(),
33
+ identity.getNullifier(),
34
+ merkleProof,
35
+ externalNullifier,
36
+ signal
37
+ )
38
+
39
+ expect(typeof witness).toBe("object")
40
+ })
41
+
42
+ // eslint-disable-next-line jest/no-disabled-tests
43
+ it.skip("Should generate and verify Semaphore proof", async () => {
44
+ const identity = new Identity()
45
+ const identityCommitment = identity.genIdentityCommitment()
46
+ const externalNullifier = genExternalNullifier("voting_1")
47
+ const leaves = [BigInt(3), BigInt(2), identityCommitment, BigInt(4)]
48
+ const signal = "0x111"
49
+
50
+ const merkleProof = generateMerkleProof(20, BigInt(0), leaves, identityCommitment)
51
+
52
+ const witness = Semaphore.genWitness(
53
+ identity.getTrapdoor(),
54
+ identity.getNullifier(),
55
+ merkleProof,
56
+ externalNullifier,
57
+ signal
58
+ )
59
+
60
+ const wasmFilePath = path.join(assets, "semaphore", "semaphore.wasm")
61
+ const zkeyFilePath = path.join(assets, "semaphore", "semaphore.zkey")
62
+ const fullProof = await Semaphore.genProof(witness, wasmFilePath, zkeyFilePath)
63
+
64
+ const vkeyPath = path.join(assets, "semaphore", "verification_key.json")
65
+ const vKey = JSON.parse(fs.readFileSync(vkeyPath, "utf-8"))
66
+
67
+ const response = await Semaphore.verifyProof(vKey, fullProof)
68
+
69
+ expect(response).toBe(true)
70
+ }, 30000)
71
+ })
72
+ })
@@ -0,0 +1,118 @@
1
+ import { keccak256 } from "@ethersproject/solidity"
2
+ import { formatBytes32String } from "@ethersproject/strings"
3
+ import { MerkleProof } from "@zk-kit/incremental-merkle-tree"
4
+ import { poseidon } from "circomlibjs"
5
+ import { groth16 } from "snarkjs"
6
+ import { Proof, SemaphoreFullProof, SemaphoreSolidityProof, SemaphoreWitness, StrBigInt } from "./types"
7
+
8
+ export default class Semaphore {
9
+ /**
10
+ * Generates a SnarkJS full proof with Groth16.
11
+ * @param witness The parameters for creating the proof.
12
+ * @param wasmFilePath The WASM file path.
13
+ * @param finalZkeyPath The ZKey file path.
14
+ * @returns The full SnarkJS proof.
15
+ */
16
+ /* istanbul ignore next */
17
+ public static async genProof(
18
+ witness: any,
19
+ wasmFilePath: string,
20
+ finalZkeyPath: string
21
+ ): Promise<SemaphoreFullProof> {
22
+ const { proof, publicSignals } = await groth16.fullProve(witness, wasmFilePath, finalZkeyPath, null)
23
+
24
+ return {
25
+ proof,
26
+ publicSignals: {
27
+ merkleRoot: publicSignals[0],
28
+ nullifierHash: publicSignals[1],
29
+ signalHash: publicSignals[2],
30
+ externalNullifier: publicSignals[3]
31
+ }
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Verifies a zero-knowledge SnarkJS proof.
37
+ * @param verificationKey The zero-knowledge verification key.
38
+ * @param fullProof The SnarkJS full proof.
39
+ * @returns True if the proof is valid, false otherwise.
40
+ */
41
+ /* istanbul ignore next */
42
+ public static verifyProof(verificationKey: string, { proof, publicSignals }: SemaphoreFullProof): Promise<boolean> {
43
+ return groth16.verify(
44
+ verificationKey,
45
+ [
46
+ publicSignals.merkleRoot,
47
+ publicSignals.nullifierHash,
48
+ publicSignals.signalHash,
49
+ publicSignals.externalNullifier
50
+ ],
51
+ proof
52
+ )
53
+ }
54
+
55
+ /**
56
+ * Creates a Semaphore witness for the Semaphore ZK proof.
57
+ * @param identityTrapdoor The identity trapdoor.
58
+ * @param identityNullifier The identity nullifier.
59
+ * @param merkleProof The Merkle proof that identity exists in Semaphore tree.
60
+ * @param externalNullifier The topic on which vote should be broadcasted.
61
+ * @param signal The signal that should be broadcasted.
62
+ * @returns The Semaphore witness.
63
+ */
64
+ public static genWitness(
65
+ identityTrapdoor: StrBigInt,
66
+ identityNullifier: StrBigInt,
67
+ merkleProof: MerkleProof,
68
+ externalNullifier: StrBigInt,
69
+ signal: string
70
+ ): SemaphoreWitness {
71
+ return {
72
+ identityNullifier,
73
+ identityTrapdoor,
74
+ treePathIndices: merkleProof.pathIndices,
75
+ treeSiblings: merkleProof.siblings,
76
+ externalNullifier,
77
+ signalHash: Semaphore.genSignalHash(signal)
78
+ }
79
+ }
80
+
81
+ /**
82
+ * Generates a nullifier by hashing the external and the identity nullifiers.
83
+ * @param externalNullifier The external nullifier.
84
+ * @param identityNullifier The identity nullifier.
85
+ * @returns The nullifier hash.
86
+ */
87
+ public static genNullifierHash(externalNullifier: StrBigInt, identityNullifier: StrBigInt): bigint {
88
+ return poseidon([BigInt(externalNullifier), BigInt(identityNullifier)])
89
+ }
90
+
91
+ /**
92
+ * Hashes a signal string with Keccak256.
93
+ * @param signal The Semaphore signal.
94
+ * @returns The signal hash.
95
+ */
96
+ public static genSignalHash(signal: string): bigint {
97
+ return BigInt(keccak256(["bytes32"], [formatBytes32String(signal)])) >> BigInt(8)
98
+ }
99
+
100
+ /**
101
+ * Converts a full proof in a proof compatible with the Verifier.sol method inputs.
102
+ * @param proof The proof generated with SnarkJS.
103
+ * @returns The Solidity compatible proof.
104
+ */
105
+ /* istanbul ignore next */
106
+ public static packToSolidityProof(proof: Proof): SemaphoreSolidityProof {
107
+ return [
108
+ proof.pi_a[0],
109
+ proof.pi_a[1],
110
+ proof.pi_b[0][1],
111
+ proof.pi_b[0][0],
112
+ proof.pi_b[1][1],
113
+ proof.pi_b[1][0],
114
+ proof.pi_c[0],
115
+ proof.pi_c[1]
116
+ ]
117
+ }
118
+ }
@@ -0,0 +1,41 @@
1
+ export type StrBigInt = string | bigint
2
+
3
+ export type Proof = {
4
+ pi_a: StrBigInt[]
5
+ pi_b: StrBigInt[][]
6
+ pi_c: StrBigInt[]
7
+ protocol: string
8
+ curve: string
9
+ }
10
+
11
+ export type SemaphoreFullProof = {
12
+ proof: Proof
13
+ publicSignals: SemaphorePublicSignals
14
+ }
15
+
16
+ export type SemaphorePublicSignals = {
17
+ merkleRoot: StrBigInt
18
+ nullifierHash: StrBigInt
19
+ signalHash: StrBigInt
20
+ externalNullifier: StrBigInt
21
+ }
22
+
23
+ export type SemaphoreSolidityProof = [
24
+ StrBigInt,
25
+ StrBigInt,
26
+ StrBigInt,
27
+ StrBigInt,
28
+ StrBigInt,
29
+ StrBigInt,
30
+ StrBigInt,
31
+ StrBigInt
32
+ ]
33
+
34
+ export type SemaphoreWitness = {
35
+ identityNullifier: StrBigInt
36
+ identityTrapdoor: StrBigInt
37
+ treeSiblings: StrBigInt[]
38
+ treePathIndices: number[]
39
+ externalNullifier: StrBigInt
40
+ signalHash: StrBigInt
41
+ }
package/src/utils.ts ADDED
@@ -0,0 +1,65 @@
1
+ import { keccak256 } from "@ethersproject/solidity"
2
+ import { IncrementalMerkleTree, MerkleProof } from "@zk-kit/incremental-merkle-tree"
3
+ import { poseidon } from "circomlibjs"
4
+ import { StrBigInt } from "./types"
5
+
6
+ export const SNARK_FIELD_SIZE = BigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617")
7
+
8
+ export function genExternalNullifier(plaintext: string): string {
9
+ const hashed = keccak256(["string"], [plaintext])
10
+ const hexStr = `0x${hashed.slice(8)}`
11
+ const len = 32 * 2
12
+ const h = hexStr.slice(2, len + 2)
13
+
14
+ return `0x${h.padStart(len, "0")}`
15
+ }
16
+
17
+ /**
18
+ * Creates a Merkle tree.
19
+ * @param depth The depth of the tree.
20
+ * @param zeroValue The zero value of the tree.
21
+ * @param leaves The list of the leaves of the tree.
22
+ * @returns The Merkle tree.
23
+ */
24
+ export function generateMerkleTree(depth: number, zeroValue: StrBigInt, leaves: StrBigInt[]): IncrementalMerkleTree {
25
+ const tree = new IncrementalMerkleTree(poseidon, depth, zeroValue, 2)
26
+
27
+ for (const leaf of leaves) {
28
+ tree.insert(BigInt(leaf))
29
+ }
30
+
31
+ return tree
32
+ }
33
+
34
+ /**
35
+ * Creates a Merkle proof.
36
+ * @param depth The depth of the tree.
37
+ * @param zeroValue The zero value of the tree.
38
+ * @param leaves The list of the leaves of the tree.
39
+ * @param leaf The leaf for which Merkle proof should be created.
40
+ * @returns The Merkle proof.
41
+ */
42
+ export function generateMerkleProof(
43
+ depth: number,
44
+ zeroValue: StrBigInt,
45
+ leaves: StrBigInt[],
46
+ leaf: StrBigInt
47
+ ): MerkleProof {
48
+ if (leaf === zeroValue) {
49
+ throw new Error("Can't generate a proof for a zero leaf")
50
+ }
51
+
52
+ const tree = generateMerkleTree(depth, zeroValue, leaves)
53
+
54
+ const leafIndex = tree.leaves.indexOf(BigInt(leaf))
55
+
56
+ if (leafIndex === -1) {
57
+ throw new Error("The leaf does not exist")
58
+ }
59
+
60
+ const merkleProof = tree.createProof(leafIndex)
61
+
62
+ merkleProof.siblings = merkleProof.siblings.map((s) => s[0])
63
+
64
+ return merkleProof
65
+ }