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.

290 lines
9.6 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 = ["567891234", "432198765", "321"];
  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[0][0].toString()).to.be.equal('189025084074544266465422070282645213792582195466360448472858620722286781863');
  76. // expect(res[1].toString()).to.be.equal('9328869343897770565751281504295758914771207504252217956739346620422361279598');
  77. console.log(res[0]);
  78. commitmentsArray[0] = res[0];
  79. currKey = res[2];
  80. });
  81. it("Rebuild the tree from sc commitments", async () => {
  82. let treeTmp = await smt.newMemEmptyTrie();
  83. await treeTmp.insert(0, 0);
  84. for (let i=0; i<commitmentsArray[0].length; i++) {
  85. await treeTmp.insert(i+1, commitmentsArray[0][i]);
  86. }
  87. expect(treeTmp.root).to.be.equal(tree.root);
  88. });
  89. it("Calculate witness and generate the zkProof", async () => {
  90. await genZKProof(0, addr2, "1");
  91. await genZKProof(1, addr4, "2");
  92. await genZKProof(2, addr4, "3");
  93. });
  94. it("Try to use the zkProof with another address and get revert", async () => {
  95. // console.log("Try to reuse the zkproof and expect revert");
  96. await truffleAssert.fails(
  97. withdrawSC(0, addr1),
  98. truffleAssert.ErrorType.REVERT,
  99. "zkProof withdraw could not be verified"
  100. );
  101. });
  102. it("Withdraw 1 ETH with the zkProof of the 1st deposit to addr2", async () => {
  103. // withdraw
  104. // console.log("Withdraw of " + ethAmount + " ETH to " + addr2);
  105. let resW = await withdrawSC(0, addr2);
  106. // console.log("resW", resW);
  107. balance_wei = await web3.eth.getBalance(addr2);
  108. // console.log("Balance at " + addr2, web3.utils.fromWei(balance_wei, 'ether'));
  109. expect(balance_wei).to.be.equal('101000000000000000000');
  110. });
  111. it("Try to reuse the zkProof and get revert", async () => {
  112. // console.log("Try to reuse the zkproof and expect revert");
  113. await truffleAssert.fails(
  114. withdrawSC(0, addr2),
  115. truffleAssert.ErrorType.REVERT,
  116. "nullifier already used"
  117. );
  118. balance_wei = await web3.eth.getBalance(addr2);
  119. expect(balance_wei).to.be.equal('101000000000000000000');
  120. });
  121. it("Withdraw 1 ETH with the zkProof of the 2nd deposit to addr4", async () => {
  122. let resW = await withdrawSC(1, addr4);
  123. balance_wei = await web3.eth.getBalance(addr4);
  124. expect(balance_wei).to.be.equal('101000000000000000000');
  125. });
  126. it("Withdraw 1 ETH with the zkProof of the 3rd deposit to addr4", async () => {
  127. let resW = await withdrawSC(2, addr4);
  128. balance_wei = await web3.eth.getBalance(addr4);
  129. expect(balance_wei).to.be.equal('102000000000000000000');
  130. });
  131. });
  132. async function computeTree(u) {
  133. const poseidon = circomlib.poseidon.createHash(6, 8, 57);
  134. commitment[u] = poseidon([coinCode, amount, secret[u], nullifier[u]]).toString();
  135. // deposit
  136. // add commitment into SMT
  137. // console.log("currKey", currKey);
  138. rootOld[u] = tree.root;
  139. const resC = await tree.find(currKey+1);
  140. assert(!resC.found);
  141. oldKey[u] = "0";
  142. oldValue[u] = "0";
  143. if (!resC.found) {
  144. oldKey[u] = resC.notFoundKey.toString();
  145. oldValue[u] = resC.notFoundValue.toString();
  146. }
  147. // console.log(oldValue[u]);
  148. // console.log("FIND", resC);
  149. siblingsOld[u] = resC.siblings;
  150. while (siblingsOld[u].length < nLevels) {
  151. siblingsOld[u].push("0");
  152. };
  153. await tree.insert(currKey+1, commitment[u]);
  154. rootNew[u] = tree.root;
  155. currKey += 1;
  156. // console.log("currKey", currKey);
  157. }
  158. async function makeDeposit(u, addr) {
  159. const resC = await tree.find(currKey);
  160. assert(resC.found);
  161. siblingsNew[u] = resC.siblings;
  162. while (siblingsNew[u].length < nLevels) {
  163. siblingsNew[u].push("0");
  164. };
  165. // calculate witness
  166. const wasm = await fs.promises.readFile("./test/build/deposit.wasm");
  167. const input = unstringifyBigInts({
  168. "coinCode": coinCode,
  169. "amount": amount,
  170. "secret": secret[u],
  171. "nullifier": nullifier[u],
  172. "oldKey": oldKey[u],
  173. "oldValue": oldValue[u],
  174. "siblingsOld": siblingsOld[u],
  175. "siblingsNew": siblingsNew[u],
  176. "rootOld": rootOld[u],
  177. "rootNew": rootNew[u],
  178. "commitment": commitment[u],
  179. "key": currKey
  180. });
  181. const options = {};
  182. // console.log("Calculate witness");
  183. const wc = await WitnessCalculatorBuilder(wasm, options);
  184. const w = await wc.calculateWitness(input);
  185. const witness = unstringifyBigInts(stringifyBigInts(w));
  186. // generate zkproof of commitment using snarkjs (as is a test)
  187. const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-proving_key.json", "utf8")));
  188. // console.log("Generate zkSNARK proof");
  189. const res = groth.genProof(provingKey, witness);
  190. proof[u] = res.proof;
  191. publicSignals[u] = res.publicSignals;
  192. const verificationKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-verification_key.json", "utf8")));
  193. let pubI = unstringifyBigInts([coinCode, amount, rootOld[u].toString(), rootNew[u].toString(), commitment[u], currKey]);
  194. let validCheck = groth.isValid(verificationKey, proof[u], pubI);
  195. assert(validCheck);
  196. await insMiksi.deposit(
  197. commitment[u],
  198. tree.root.toString(),
  199. [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
  200. [
  201. [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
  202. [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
  203. ],
  204. [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()],
  205. {from: addr, value: amount}
  206. );
  207. }
  208. async function genZKProof(u, addr, k) {
  209. const resC = await tree.find(k);
  210. assert(resC.found);
  211. let siblings = resC.siblings;
  212. while (siblings.length < nLevels) {
  213. siblings.push("0");
  214. };
  215. // console.log("siblings", siblings);
  216. // calculate witness
  217. const wasm = await fs.promises.readFile("./test/build/withdraw.wasm");
  218. const input = unstringifyBigInts({
  219. "coinCode": coinCode,
  220. "amount": amount,
  221. "secret": secret[u],
  222. "nullifier": nullifier[u],
  223. "siblings": siblings,
  224. "root": tree.root,
  225. "address": addr,
  226. "key": k
  227. });
  228. const options = {};
  229. // console.log("Calculate witness");
  230. const wc = await WitnessCalculatorBuilder(wasm, options);
  231. const w = await wc.calculateWitness(input);
  232. const witness = unstringifyBigInts(stringifyBigInts(w));
  233. // generate zkproof of commitment using snarkjs (as is a test)
  234. const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/withdraw-proving_key.json", "utf8")));
  235. // console.log("Generate zkSNARK proof");
  236. const res = groth.genProof(provingKey, witness);
  237. proof[u] = res.proof;
  238. publicSignals[u] = res.publicSignals;
  239. }
  240. async function withdrawSC(u, addr) {
  241. return insMiksi.withdraw(
  242. addr,
  243. nullifier[u],
  244. [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
  245. [
  246. [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
  247. [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
  248. ],
  249. [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()]
  250. );
  251. }