#!/bin/sh
# Re-run a verdict of the Prop AMM Teardown Engine on your own machine.
#   sh verify.sh <attempt id> [site]
# Needs: curl, tar, a Rust toolchain (cargo), and for a PASS the Agave cargo build-sbf listed in the docs.
# It fetches the attempt, the replayer source, the original ELF, the candidate ELF and the corpus from the
# site by hash, replays every case with the same seed and prints the report sha256 next to the judge's.
set -eu
ID="${1:?usage: sh verify.sh <attempt id> [site]}"
SITE="${2:-${TEARDOWN_SITE:-https://www.propammengine.xyz}}"
if [ -z "$SITE" ]; then echo "set the site: sh verify.sh <attempt id> https://<site>" >&2; exit 2; fi
W="$(mktemp -d)"; cd "$W"
echo "work dir $W"
curl -fsSL "$SITE/api/v1/attempts/$ID" -o attempt.json
field() { sed -n "s/.*\"$1\":\"\{0,1\}\([^\",}]*\).*/\1/p" attempt.json | head -1; }
PROGRAM="$(field program)"; CORPUS="$(field corpusSha256)"; CAND="$(field candidateSha256)"
SRC="$(field sourceSha256)"; REPORT="$(field reportSha256)"; VERDICT="$(field verdict)"
echo "attempt $ID: $VERDICT on $PROGRAM"
curl -fsSL "$SITE/verifier/replayer-src.tar.gz" -o replayer-src.tar.gz
tar -xzf replayer-src.tar.gz
(cd replayer && cargo build --release --locked -q)
curl -fsSL "$SITE/verifier/original/$PROGRAM" -o original.so
curl -fsSL "$SITE/verifier/candidate/$CAND" -o candidate.so
curl -fsSL "$SITE/verifier/corpus/$CORPUS" -o corpus.json
for f in "corpus.json:$CORPUS" "candidate.so:$CAND"; do
  got="$(./replayer/target/release/replayer hash "${f%%:*}" 2>/dev/null || shasum -a 256 "${f%%:*}" | cut -d' ' -f1)"
  [ "$got" = "${f#*:}" ] || { echo "hash mismatch on ${f%%:*}" >&2; exit 1; }
done
./replayer/target/release/replayer replay --original original.so --candidate candidate.so --corpus corpus.json \
  --fuzz 10000 --source-sha256 "$SRC" --out report.json
MINE="$(shasum -a 256 report.json | cut -d' ' -f1)"
echo "judge report sha256 $REPORT"
echo "your report sha256  $MINE"
[ "$MINE" = "$REPORT" ] && echo "MATCH: the verdict reproduces" || { echo "DIFFERENT: compare report.json with $SITE/verifier/report/$REPORT"; exit 1; }
