#!/bin/bash
CIRC=cverecord
set -e

# Setup cannot be generated by prover, must come from dist
#cp ../src/${CIRC}.circom .
#cp ../dist/${CIRC}.zkey .

# Can generate these with npx circom2 + SnarkJS yourself, or use the ones provided. Doesn't really matter. We'll generate it outselves.
#cp ../dist/${CIRC}.r1cs .
#cp ../dist/{CIRC}_js/ .
#cp ../src/${CIRC}_verification_key.json .
unzip ../dist/${CIRC}.zip

# A good and honest proof with i1 <-- year and year <= 2025. Shouldn't release flag.
# Can write the JSON for this yourself, or use the one provided. Doesn't really matter.
#cp ../dist/${CIRC}_input.json .

# Generate R1CS circuit representation of honest witness inputs
# --inspect gives you a big hint :)
npx circom2 ./${CIRC}.circom --r1cs --wasm --inspect --sym
cat ./${CIRC}_input.json
cd ${CIRC}_js/
(node generate_witness.js ${CIRC}.wasm ../${CIRC}_input.json ../witness.wtns) || (echo -e "\e[0;31mERROR: Cannot convert witness from Circom to SnarkJS; honest witness likely does not satisfy circuit!\e[0m" && exit 1)

cd ..

# Export witness to JSON, in case you want to modify, create the proof, and send this entirely in JavaScript
# CVERecord circuit: [1, out, year, id, name[0], ..., name[31], i1, i2] = [1, 20035, 2025, 20035, 'D', 'O', 'G', 'E', ..., name[31], i1, i2 == i1]
snarkjs wtns export json ./witness.wtns ./witness.json
cat ./witness.json

# Check that the witness satisfies the circuit
(snarkjs wtns check ./${CIRC}.r1cs ./witness.wtns | tail -n2 | grep -q "WITNESS IS CORRECT") || (echo -e "\e[0;31mERROR: Honest witness does not satisfy circuit!\e[0m" && exit 1)

# Manipulate the witness to exploit the underconstrained circuit, show + save to exploit_witness.wtns
node change_witness.js
# Export modified witness to JSON so we can send this in POST request
snarkjs wtns export json ./exploit_witness.wtns ./exploit_witness.json
cat ./exploit_witness.json
# Check that the witness satisfies the circuit
(snarkjs wtns check ./${CIRC}.r1cs ./exploit_witness.wtns | tail -n2 | grep -q "WITNESS IS CORRECT") || (echo -e "\e[0;31mERROR: Exploit witness does not satisfy circuit!\e[0m" && exit 1)

# Create a satisfying proof of this circuit + extract only public inputs
snarkjs groth16 prove ./${CIRC}.zkey ./exploit_witness.wtns ./${CIRC}_proof.json ./${CIRC}_public_input.json

# Verify that the proof + public inputs are also satisfying
(snarkjs groth16 verify ./${CIRC}_verification_key.json ./${CIRC}_public_input.json ./${CIRC}_proof.json | tail -n1 | grep -q "OK!") || (echo -e "\e[0;31mERROR: Forged proof does not satisfy circuit!\e[0m" && exit 1)
cat ./${CIRC}_public_input.json

# Send proof and public input as POST request to server
python3 send_solve.py

# Cleanup
rm -rf ./${CIRC}_js/
rm ./${CIRC}.r1cs
rm ./${CIRC}_input.json
rm ./${CIRC}_public_input.json
rm ./${CIRC}.zkey
rm ./${CIRC}_verification_key.json
rm ./*witness.wtns
rm ./*witness.json
rm ./*.circom
rm ./package*.json
