#!/bin/sh
# Re-runs a Proof of Decompile verdict on your machine.
#   sh verify.sh <proof number | submission id> [decrypted-archive]
# Needs: curl, tar, sha256sum (or shasum), cargo (Rust). With an archive, also cargo build-sbf (Agave platform tools).
set -eu
SITE="${SITE:-https://www.proofofdecompile.com}"
ID="${1:?usage: sh verify.sh <proof number | submission id> [archive]}"
sha() { if command -v sha256sum >/dev/null; then sha256sum "$1" | cut -d' ' -f1; else shasum -a 256 "$1" | cut -d' ' -f1; fi; }
json() { node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>{const j=JSON.parse(s);const v=$1;process.stdout.write(String(v??''))})"; }
W="pod-verify-$ID"; mkdir -p "$W"; cd "$W"
case "$ID" in s*) curl -fsS "$SITE/api/v1/verdicts/$ID" -o verdict.json ;; *) curl -fsS "$SITE/api/v1/proofs/$ID" -o verdict.json ;; esac
PROGRAM=$(json "j.program" < verdict.json)
CORPUS=$(json "(j.report||{}).corpus_sha256" < verdict.json)
CAND=$(json "(j.report||{}).candidate_sha256" < verdict.json)
ORIG=$(json "(j.report||{}).original_sha256" < verdict.json)
SRC=$(json "j.sourceCommitment" < verdict.json)
echo "program   $PROGRAM"; echo "corpus    $CORPUS"; echo "original  $ORIG"; echo "candidate $CAND"
curl -fsS "$SITE/api/verifier/original/$PROGRAM" -o original.so
curl -fsS "$SITE/api/verifier/corpus/$CORPUS" -o corpus.json
curl -fsS "$SITE/api/verifier/candidate/$CAND" -o candidate.so
[ "$(sha original.so)" = "$ORIG" ] || { echo "original.so hash differs"; exit 1; }
[ "$(sha corpus.json)" = "$CORPUS" ] || { echo "corpus hash differs"; exit 1; }
[ "$(sha candidate.so)" = "$CAND" ] || { echo "candidate hash differs"; exit 1; }
if [ "${2:-}" != "" ]; then
  [ "$(sha "$2")" = "$SRC" ] || { echo "archive does not match the commitment $SRC"; exit 1; }
  echo "archive matches the commitment"
fi
[ -f replayer-src.tar.gz ] || curl -fsS "$SITE/verifier/replayer-src.tar.gz" -o replayer-src.tar.gz
tar -xzf replayer-src.tar.gz
(cd replayer && cargo build --release --locked -q)
./replayer/target/release/replayer replay --original original.so --candidate candidate.so --corpus corpus.json --source-sha256 "$SRC" --out report.json
node -e "const a=require('./report.json'),b=require('./verdict.json').report;for(const k of ['verdict','matched','compared','original_outcomes_sha256','candidate_outcomes_sha256'])console.log(k.padEnd(28),a[k]===b[k]?'same':'DIFFERENT',a[k])"
