#!/bin/bash

CIRC=cverecord
POW2=14
# Generate R1CS circuit to represent statement to prove
npx circom2 ./src/${CIRC}.circom --r1cs --wasm -l "./src/node_modules/circomlib/circuits/comparators.circom"

# See https://docs.circom.io/getting-started/proving-circuits/

if [ ! -f ./deploy/pot${POW2}_final.ptau ]; then
	# Phase 1: Initial MPC ceremoney to begin trusted setup
	# allows for proofs up to 2^14 ~= 16k constraints, with proof working in bn128 elliptic curve
	snarkjs powersoftau new bn128 ${POW2} pot${POW2}_0000.ptau -v
	# Party 1 provides their contribution to initial setup, with 128 random characters as input for greater entropy
	(sudo < /dev/urandom tr -dc A-Za-z0-9 | head -c128; echo) | snarkjs powersoftau contribute pot${POW2}_0000.ptau pot${POW2}_0001.ptau --name="Party 1 Contribution" -v
	# Finalize Phase 1
	snarkjs powersoftau prepare phase2 pot${POW2}_0001.ptau pot${POW2}_final.ptau -v
	# Verify that trusted setup has been performed correctly so far
	(snarkjs powersoftau verify pot${POW2}_final.ptau | tail -n1 | grep -q "Powers of Tau Ok!") || (echo -e "\e[0;31mERROR: Initial trusted setup not properly validated!\e[0m" && rm pot* && exit 1)

	# Powers of tau are toxic waste, if these private inputs are leaked it will break ZKP soundness. Since we're done with this part of trusted setup now, delete.
	mv pot${POW2}_final.ptau ./deploy/
	rm pot*
fi

cp ./deploy/pot${POW2}_final.ptau ./
# Phase 2: Circuit-specific MPC trusted setup
snarkjs groth16 setup ./${CIRC}.r1cs ./pot${POW2}_final.ptau ./${CIRC}_0000.zkey
# Party 1 also contributes to circuit-specific setup
(sudo < /dev/urandom tr -dc A-Za-z0-9 | head -c128; echo) | snarkjs zkey contribute ./${CIRC}_0000.zkey ./${CIRC}.zkey --name="Party 1 Contributor" -v
# Verify that circuit-specific trusted setup has been performed correctly
(snarkjs zkv ./${CIRC}.r1cs ./pot${POW2}_final.ptau ./${CIRC}.zkey | tail -n1 | grep -q "ZKey Ok!") || (echo -e "\e[0;31mERROR: Circuit-specific trusted setup not properly validated!\e[0m" && exit 1)
rm pot*
rm ${CIRC}_0000.zkey

# Export verification key (removing the prover specific values)
(snarkjs zkey export verificationkey ./${CIRC}.zkey ./${CIRC}_verification_key.json | tail -n1 | grep -q "EXPORT VERIFICATION KEY FINISHED") || (echo -e "\e[0;31mERROR: Exported verification key invalid!\e[0m" && exit 1)

# Move everything into the correct place for deployment/distribution
pwd
cp ./${CIRC}_verification_key.json ./src/
mv ./${CIRC}_verification_key.json ./dist/
mv ./${CIRC}.r1cs ./dist/
mv ./${CIRC}_js/ ./dist/
mv ./${CIRC}.zkey ./dist/
cp ./src/app.js ./dist/
cp ./src/server.js ./dist/
cp ./src/${CIRC}.circom ./dist/
cp ./src/package.json ./dist/

cd ./dist/
zip -r ${CIRC}.zip ./*

# Keep just the input
rm ./${CIRC}_verification_key.json
rm ./${CIRC}.r1cs
rm -rf ./${CIRC}_js/
rm ./${CIRC}.zkey
rm ./app.js
rm ./server.js
rm ./${CIRC}.circom
rm ./package.json
cd ..
