miksi-core/test/contracts/miksi.test.ts
test/contracts/miksi.test.tsRaw
1const DepositVerifier = artifacts.require("../build/DepositVerifier");
2const WithdrawVerifier = artifacts.require("../build/WithdrawVerifier");
3const Miksi = artifacts.require("../build/Miksi.sol");
4
5const chai = require("chai");
6const expect = chai.expect;
7const truffleAssert = require('truffle-assertions');
8
9const fs = require("fs");
10const { groth } = require('snarkjs');
11const { stringifyBigInts, unstringifyBigInts } = require('ffjavascript').utils;
12const WitnessCalculatorBuilder = require("circom_runtime").WitnessCalculatorBuilder;
13const circomlib = require("circomlib");
14const smt = require("circomlib").smt;
15
16let insVerifier;
17let insMiksi;
18
19const nLevels = 4;
20const secret = ["1234567890", "987654321", "123"];
21
22const coinCode = "0"; // refearing to ETH
23const ethAmount = '1';
24const amount = web3.utils.toWei(ethAmount, 'ether');
25const nullifier = ["0", "0", "0"];
26let commitment = [];
27let tree;
28let oldKey = [];
29let oldValue = [];
30let siblingsOld = [];
31let siblingsNew = [];
32let rootOld = [];
33let rootNew = [];
34// let commitment = [];
35let proof = [];
36let publicSignals = [];
37let commitmentsArray = [];
38let currKey=0;
39let u = 0;
40
41contract("miksi", (accounts) => {
42
43
44 const {
45 0: owner,
46 1: addr1, // used for the deposit
47 2: addr2, // used for the withdraw
48 3: addr3,
49 4: addr4,
50 } = accounts;
51
52
53 before(async () => {
54 insDepositVerifier = await DepositVerifier.new();
55 insWithdrawVerifier = await WithdrawVerifier.new();
56 insMiksi = await Miksi.new(insDepositVerifier.address, insWithdrawVerifier.address);
57 });
58
59 before(async() => {
60 let balance_wei = await web3.eth.getBalance(addr1);
61 // console.log("Balance at " + addr1, web3.utils.fromWei(balance_wei, 'ether'));
62 expect(balance_wei).to.be.equal('100000000000000000000');
63
64 tree = await smt.newMemEmptyTrie();
65 await tree.insert(currKey, 0);
66
67 await computeTree(0);
68
69 expect(rootOld[0].toString()).to.be.equal('7191590165524151132621032034309259185021876706372059338263145339926209741311');
70 // expect(rootNew[0].toString()).to.be.equal('9328869343897770565751281504295758914771207504252217956739346620422361279598');
71 });
72
73 it("Make first deposit", async () => {
74 await makeDeposit(0, addr1);
75 balance_wei = await web3.eth.getBalance(addr1);
76 // console.log("Balance at " + addr1, web3.utils.fromWei(balance_wei, 'ether'));
77 // expect(balance_wei).to.be.equal('98993526980000000000');
78 });
79 it("Make second deposit", async () => {
80 await computeTree(1);
81 await makeDeposit(1, addr3);
82 });
83 it("Make 3rd deposit", async () => {
84 await computeTree(2);
85 await makeDeposit(2, addr3);
86 });
87
88 it("Get the commitments data", async () => {
89 // getCommitments data
90 let res = await insMiksi.getCommitments();
91 expect(res[1].toString()).to.be.equal(tree.root.toString());
92 commitmentsArray[0] = res[0];
93 currKey = res[2];
94 });
95
96 it("Rebuild the tree from sc commitments", async () => {
97 let treeTmp = await smt.newMemEmptyTrie();
98 await treeTmp.insert(0, 0);
99 for (let i=0; i<commitmentsArray[0].length; i++) {
100 await treeTmp.insert(i+1, commitmentsArray[0][i]);
101 }
102 expect(treeTmp.root).to.be.equal(tree.root);
103 });
104
105 it("Calculate witness and generate the zkProof", async () => {
106 await genZKProof(0, addr2, "1");
107 await genZKProof(1, addr4, "2");
108 await genZKProof(2, addr4, "3");
109 });
110
111 it("Try to use the zkProof with another address and get revert", async () => {
112 // console.log("Try to reuse the zkproof and expect revert");
113 await truffleAssert.fails(
114 withdrawSC(0, addr1),
115 truffleAssert.ErrorType.REVERT,
116 "zkProof withdraw could not be verified"
117 );
118 });
119
120 it("Withdraw 1 ETH with the zkProof of the 1st deposit to addr2", async () => {
121 // withdraw
122 // console.log("Withdraw of " + ethAmount + " ETH to " + addr2);
123 let resW = await withdrawSC(0, addr2);
124 // console.log("resW", resW);
125
126 balance_wei = await web3.eth.getBalance(addr2);
127 // console.log("Balance at " + addr2, web3.utils.fromWei(balance_wei, 'ether'));
128 expect(balance_wei).to.be.equal('101000000000000000000');
129 });
130
131 it("Try to reuse the zkProof and get revert", async () => {
132 // console.log("Try to reuse the zkproof and expect revert");
133 await truffleAssert.fails(
134 withdrawSC(0, addr2),
135 truffleAssert.ErrorType.REVERT,
136 "nullifier already used"
137 );
138 balance_wei = await web3.eth.getBalance(addr2);
139 expect(balance_wei).to.be.equal('101000000000000000000');
140 });
141 it("Withdraw 1 ETH with the zkProof of the 2nd deposit to addr4", async () => {
142 let resW = await withdrawSC(1, addr4);
143 balance_wei = await web3.eth.getBalance(addr4);
144 expect(balance_wei).to.be.equal('101000000000000000000');
145 });
146 it("Withdraw 1 ETH with the zkProof of the 3rd deposit to addr4", async () => {
147 let resW = await withdrawSC(2, addr4);
148 balance_wei = await web3.eth.getBalance(addr4);
149 expect(balance_wei).to.be.equal('102000000000000000000');
150 });
151});
152
153
154async function computeTree(u) {
155 const poseidon = circomlib.poseidon.createHash(6, 8, 57);
156 nullifier[u] = poseidon([currKey+1, secret[u]]).toString();
157 commitment[u] = poseidon([coinCode, amount, secret[u], nullifier[u]]).toString();
158
159 // deposit
160 // add commitment into SMT
161
162 // console.log("currKey", currKey);
163 rootOld[u] = tree.root;
164 const resC = await tree.find(currKey+1);
165 assert(!resC.found);
166 oldKey[u] = "0";
167 oldValue[u] = "0";
168 if (!resC.found) {
169 oldKey[u] = resC.notFoundKey.toString();
170 oldValue[u] = resC.notFoundValue.toString();
171 }
172 // console.log(oldValue[u]);
173 // console.log("FIND", resC);
174 siblingsOld[u] = resC.siblings;
175 while (siblingsOld[u].length < nLevels) {
176 siblingsOld[u].push("0");
177 };
178
179 await tree.insert(currKey+1, commitment[u]);
180 rootNew[u] = tree.root;
181 currKey += 1;
182 // console.log("currKey", currKey);
183}
184
185async function makeDeposit(u, addr) {
186 const resC = await tree.find(currKey);
187 assert(resC.found);
188 siblingsNew[u] = resC.siblings;
189 while (siblingsNew[u].length < nLevels) {
190 siblingsNew[u].push("0");
191 };
192
193 // calculate witness
194 const wasm = await fs.promises.readFile("./test/build/deposit.wasm");
195 const input = unstringifyBigInts({
196 "coinCode": coinCode,
197 "amount": amount,
198 "secret": secret[u],
199 "oldKey": oldKey[u],
200 "oldValue": oldValue[u],
201 "siblingsOld": siblingsOld[u],
202 "siblingsNew": siblingsNew[u],
203 "rootOld": rootOld[u],
204 "rootNew": rootNew[u],
205 "commitment": commitment[u],
206 "key": currKey
207 });
208 const options = {};
209 // console.log("Calculate witness");
210 const wc = await WitnessCalculatorBuilder(wasm, options);
211 const w = await wc.calculateWitness(input);
212 const witness = unstringifyBigInts(stringifyBigInts(w));
213
214 // generate zkproof of commitment using snarkjs (as is a test)
215 const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-proving_key.json", "utf8")));
216
217 // console.log("Generate zkSNARK proof");
218 const res = groth.genProof(provingKey, witness);
219 proof[u] = res.proof;
220 publicSignals[u] = res.publicSignals;
221
222 const verificationKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-verification_key.json", "utf8")));
223 let pubI = unstringifyBigInts([coinCode, amount, rootOld[u].toString(), rootNew[u].toString(), commitment[u], currKey]);
224 let validCheck = groth.isValid(verificationKey, proof[u], pubI);
225 assert(validCheck);
226 await insMiksi.deposit(
227 commitment[u],
228 tree.root.toString(),
229 [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
230 [
231 [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
232 [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
233 ],
234 [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()],
235 {from: addr, value: amount}
236 );
237
238}
239
240async function genZKProof(u, addr, k) {
241 const resC = await tree.find(k);
242 assert(resC.found);
243 let siblings = resC.siblings;
244 while (siblings.length < nLevels) {
245 siblings.push("0");
246 };
247 // console.log("siblings", siblings);
248
249 // calculate witness
250 const wasm = await fs.promises.readFile("./test/build/withdraw.wasm");
251 const input = unstringifyBigInts({
252 "coinCode": coinCode,
253 "amount": amount,
254 "secret": secret[u],
255 "nullifier": nullifier[u],
256 "siblings": siblings,
257 "root": tree.root,
258 "address": addr,
259 "key": k
260 });
261 const options = {};
262 // console.log("Calculate witness");
263 const wc = await WitnessCalculatorBuilder(wasm, options);
264 const w = await wc.calculateWitness(input);
265 const witness = unstringifyBigInts(stringifyBigInts(w));
266
267 // generate zkproof of commitment using snarkjs (as is a test)
268 const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/withdraw-proving_key.json", "utf8")));
269
270 // console.log("Generate zkSNARK proof");
271 const res = groth.genProof(provingKey, witness);
272 proof[u] = res.proof;
273 publicSignals[u] = res.publicSignals;
274}
275
276async function withdrawSC(u, addr) {
277 return insMiksi.withdraw(
278 addr,
279 nullifier[u],
280 [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
281 [
282 [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
283 [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
284 ],
285 [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()]
286 );
287}
288