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.

288 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. const resC = await tree.find(currKey);
  159. assert(resC.found);
  160. siblingsNew[u] = resC.siblings;
  161. while (siblingsNew[u].length < nLevels) {
  162. siblingsNew[u].push("0");
  163. };
  164. // calculate witness
  165. const wasm = await fs.promises.readFile("./test/build/deposit.wasm");
  166. const input = unstringifyBigInts({
  167. "coinCode": coinCode,
  168. "amount": amount,
  169. "secret": secret[u],
  170. "oldKey": oldKey[u],
  171. "oldValue": oldValue[u],
  172. "siblingsOld": siblingsOld[u],
  173. "siblingsNew": siblingsNew[u],
  174. "rootOld": rootOld[u],
  175. "rootNew": rootNew[u],
  176. "commitment": commitment[u],
  177. "key": currKey
  178. });
  179. const options = {};
  180. // console.log("Calculate witness");
  181. const wc = await WitnessCalculatorBuilder(wasm, options);
  182. const w = await wc.calculateWitness(input);
  183. const witness = unstringifyBigInts(stringifyBigInts(w));
  184. // generate zkproof of commitment using snarkjs (as is a test)
  185. const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-proving_key.json", "utf8")));
  186. // console.log("Generate zkSNARK proof");
  187. const res = groth.genProof(provingKey, witness);
  188. proof[u] = res.proof;
  189. publicSignals[u] = res.publicSignals;
  190. const verificationKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/deposit-verification_key.json", "utf8")));
  191. let pubI = unstringifyBigInts([coinCode, amount, rootOld[u].toString(), rootNew[u].toString(), commitment[u], currKey]);
  192. let validCheck = groth.isValid(verificationKey, proof[u], pubI);
  193. assert(validCheck);
  194. await insMiksi.deposit(
  195. commitment[u],
  196. tree.root.toString(),
  197. [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
  198. [
  199. [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
  200. [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
  201. ],
  202. [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()],
  203. {from: addr, value: amount}
  204. );
  205. }
  206. async function genZKProof(u, addr, k) {
  207. const resC = await tree.find(k);
  208. assert(resC.found);
  209. let siblings = resC.siblings;
  210. while (siblings.length < nLevels) {
  211. siblings.push("0");
  212. };
  213. // console.log("siblings", siblings);
  214. // calculate witness
  215. const wasm = await fs.promises.readFile("./test/build/withdraw.wasm");
  216. const input = unstringifyBigInts({
  217. "coinCode": coinCode,
  218. "amount": amount,
  219. "secret": secret[u],
  220. "nullifier": nullifier[u],
  221. "siblings": siblings,
  222. "root": tree.root,
  223. "address": addr,
  224. "key": k
  225. });
  226. const options = {};
  227. // console.log("Calculate witness");
  228. const wc = await WitnessCalculatorBuilder(wasm, options);
  229. const w = await wc.calculateWitness(input);
  230. const witness = unstringifyBigInts(stringifyBigInts(w));
  231. // generate zkproof of commitment using snarkjs (as is a test)
  232. const provingKey = unstringifyBigInts(JSON.parse(fs.readFileSync("./test/build/withdraw-proving_key.json", "utf8")));
  233. // console.log("Generate zkSNARK proof");
  234. const res = groth.genProof(provingKey, witness);
  235. proof[u] = res.proof;
  236. publicSignals[u] = res.publicSignals;
  237. }
  238. async function withdrawSC(u, addr) {
  239. return insMiksi.withdraw(
  240. addr,
  241. nullifier[u],
  242. [proof[u].pi_a[0].toString(), proof[u].pi_a[1].toString()],
  243. [
  244. [proof[u].pi_b[0][1].toString(), proof[u].pi_b[0][0].toString()],
  245. [proof[u].pi_b[1][1].toString(), proof[u].pi_b[1][0].toString()]
  246. ],
  247. [proof[u].pi_c[0].toString(), proof[u].pi_c[1].toString()]
  248. );
  249. }