arnaucube
arnaucube/miksi-corePublic Self-hosted repository
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    let resInsert = await tree.insert(currKey+1, commitment[u]);
187    rootNew[u] = tree.root;
188    currKey += 1;
189
190    // calculate witness
191    const wasm = await fs.promises.readFile("./test/build/deposit.wasm");
192    const input = unstringifyBigInts({
193      "coinCode": coinCode,
194      "amount": amount,
195      "secret": secret[u],
196      "oldKey": resInsert.isOld0 ? 0 : resInsert.oldKey,
197      "oldValue": resInsert.isOld0 ? 0 : resInsert.oldValue,
198      "isOld0": resInsert.isOld0 ? 1 : 0,
199      "siblings": resInsert.siblings,
200      "rootOld": resInsert.oldRoot,
201      "rootNew": resInsert.newRoot,
202      "commitment": commitment[u],
203      "key": currKey
204    });
205    const options = {};
206    // console.log("Calculate witness");
207    const wc = await WitnessCalculatorBuilder(wasm, options);
208    const w = await wc.calculateWitness(input);
209    const witness = unstringifyBigInts(stringifyBigInts(w));
210
211    // generate zkproof of commitment using snarkjs (as is a test)
212    const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-proving_key.json", "utf8")));
213
214    // console.log("Generate zkSNARK proof");
215    const res = groth.genProof(provingKey, witness);
216    proof[u] = res.proof;
217    publicSignals[u] = res.publicSignals;
218
219    const verificationKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-verification_key.json", "utf8")));
220    let pubI = unstringifyBigInts([coinCode, amount, res.oldRoot.toString(), res.newRoot.toString(), commitment[u], currKey]);
221    let validCheck = groth.isValid(verificationKey, proof[u], pubI);
222    assert(validCheck);
223    await insMiksi.deposit(
224      commitment[u],
225      tree.root.toString(),
226      [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
227      [
228        [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
229        [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
230      ],
231      [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()],
232      {from: addr, value: amount}
233    );
234
235}
236
237async function genZKProof(u, addr, k) {
238    const resC = await tree.find(k);
239    assert(resC.found);
240    let siblings = resC.siblings;
241    while (siblings.length < nLevels) {
242        siblings.push("0");
243    };
244    // console.log("siblings", siblings);
245
246    // calculate witness
247    const wasm = await fs.promises.readFile("./test/build/withdraw.wasm");
248    const input = unstringifyBigInts({
249      "coinCode": coinCode,
250      "amount": amount,
251      "secret": secret[u],
252      "nullifier": nullifier[u],
253      "siblings": siblings,
254      "root": tree.root,
255      "address": addr,
256      "key": k
257    });
258    const options = {};
259    // console.log("Calculate witness");
260    const wc = await WitnessCalculatorBuilder(wasm, options);
261    const w = await wc.calculateWitness(input);
262    const witness = unstringifyBigInts(stringifyBigInts(w));
263
264    // generate zkproof of commitment using snarkjs (as is a test)
265    const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/withdraw-proving_key.json", "utf8")));
266
267    // console.log("Generate zkSNARK proof");
268    const res = groth.genProof(provingKey, witness);
269    proof[u] = res.proof;
270    publicSignals[u] = res.publicSignals;
271}
272
273async function withdrawSC(u, addr) {
274      return insMiksi.withdraw(
275        addr,
276        nullifier[u],
277        [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
278        [
279          [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
280          [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
281        ],
282        [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()]
283      );
284}
285