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