arnaucube
arnaucube/miksi-corePublic Self-hosted repository
miksi-core/src/miksi.ts
src/miksi.tsRaw
 1const fs = require("fs");
 2const bigInt = require("big-integer");
 3const { groth } = require('snarkjs');
 4const { stringifyBigInts, unstringifyBigInts } = require('ffjavascript').utils;
 5const WitnessCalculatorBuilder = require("circom_runtime").WitnessCalculatorBuilder;
 6const circomlib = require("circomlib");
 7const smt = require("circomlib").smt;
 8const Web3 = require("web3");
 9// const buildBn128 = require("wasmsnark").buildBn128;
10
11
12const nLevels = 5;
13const coinCode = "0"; // refearing to ETH
14const ethAmount = '1';
15const amount = Web3.utils.toWei(ethAmount, 'ether');
16
17// let bn128;
18// 
19// exports.init = async () => {
20//         bn128 = await buildBn128();
21// }
22
23exports.calcWitness = async (wasm, secret, nullifier, commitments) => {
24	const poseidon = circomlib.poseidon.createHash(6, 8, 57);
25	const commitment = poseidon([coinCode, amount, secret, nullifier]).toString();
26
27	let tree = await smt.newMemEmptyTrie();
28	await tree.insert(1, 0);
29
30	// old root
31	const rootOld = tree.root;
32	const resOld = await tree.find(commitment);
33	if (resOld.found) {
34		console.error("leaf expect to not exist but exists");
35	}
36	let siblingsOld = resOld.siblings;
37	while (siblingsOld.length < nLevels) {
38		siblingsOld.push("0");
39	};
40
41	await tree.insert(commitment, 0);
42
43	// new root
44	const rootNew = tree.root;
45	const resNew = await tree.find(commitment);
46	if (!resNew.found) {
47		console.error("leaf expect to exist but not exists");
48	}
49	let siblingsNew = resNew.siblings;
50	while (siblingsNew.length < nLevels) {
51		siblingsNew.push("0");
52	};
53
54	// calculate witness
55	const input = unstringifyBigInts({
56		"coinCode": coinCode,
57		"amount": amount,
58		"secret": secret,
59		"nullifier": nullifier,
60		"siblingsOld": siblingsOld,
61		"siblingsNew": siblingsNew,
62		"rootOld": rootOld,
63		"rootNew": rootNew,
64		"commitment": commitment
65	});
66	console.log("input", input);
67	// const options = {};
68	// const wc = await WitnessCalculatorBuilder(wasm, options);
69
70	const wc = await WitnessCalculatorBuilder(wasm);
71
72	const witness = await wc.calculateWitness(input, {sanityCheck: true});
73
74	const wBuff = Buffer.allocUnsafe(witness.length*32);
75
76	for (let i=0; i<witness.length; i++) {
77		for (let j=0; j<8; j++) {
78			const bi = witness[i];
79			const v = bigInt(bi).shiftRight(j*32).and(0xFFFFFFFF).toJSNumber();
80			wBuff.writeUInt32LE(v, i*32 + j*4, 4)
81		}
82	}
83
84
85	// const witness = unstringifyBigInts(stringifyBigInts(w));
86	return wBuff;
87}
88
89