You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

285 lines
9.4 KiB

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