#!/bin/sh
# Checks the Fluton ceremony's final keys from scratch, trusting nothing the coordinator says.
#
# Put these in one folder with this script:
#   transaction.r1cs, transaction16.r1cs  compiled from the commit and with the compiler named in
#                                         transcript.json (header.commit, header.compiler)
#   the phase 1 file named in header.ptau.name, from its publisher
#   transaction_final.zkey, transaction16_final.zkey, transcript.json
#
# Then run: sh verify.sh
# snarkjs prints every contribution's hash, newest first: the beacon's, then the last
# contribution's, down to the first. Compare them with transcript.json, whose list is oldest
# first. Recompute the beacon yourself from the block named there.
set -e
cd "$(dirname "$0")"

node -e '
  const fs = require("fs"), crypto = require("crypto");
  const t = JSON.parse(fs.readFileSync("transcript.json", "utf8"));
  const sha = (f) => crypto.createHash("sha256").update(fs.readFileSync(f)).digest("hex");
  const want = [[t.header.ptau.name, t.header.ptau.hash]];
  for (const c of t.header.circuits) want.push([c.id + ".r1cs", c.r1csHash]);
  for (const [id, f] of Object.entries(t.final)) want.push([f.zkey.name, f.zkey.sha256]);
  let bad = 0;
  for (const [file, hash] of want) {
    const ok = sha(file) === hash;
    if (!ok) bad++;
    console.log((ok ? "ok    " : "WRONG ") + file);
  }
  if (bad) process.exit(1);
'

PTAU=$(node -p 'require("./transcript.json").header.ptau.name')
for c in transaction transaction16; do
  echo "== $c"
  npx -y snarkjs@0.7.6 zkey verify "$c.r1cs" "$PTAU" "${c}_final.zkey"
done
echo "Both final keys check out."
