#!/usr/bin/env bash
# ICA Proof Room v2 · check every exhibit with BOTH independent verifiers, offline.
#
#   bash VERIFY.sh
#
# Runs tools/ica-verify/verify.js (Node) and verifier/python/ica_verify.py (Python) over every
# exhibit with the pinned trust anchor and --require-pin, compares the two verdicts, and compares
# each with the verdict the exhibit must give. Needs no network: everything it reads is in this
# folder. run_checks.py does the same checks from Python.
#
# Needs: Node 24 or later (its crypto has ML-DSA) and python3 with the `cryptography` package
# built with ML-DSA. Either one missing prints INDETERMINATE with the reason and exits 3: a
# post-quantum leg nobody checked is never reported as a pass.
#   NODE=/path/to/node PYTHON=/path/to/python3 bash VERIFY.sh   picks the runtimes yourself.
#
# Exit: 0 every check holds and nothing is pending
#       1 a verifier disagreed with the other, an exhibit gave the wrong verdict, a tampered copy
#         passed, a file is not the one MANIFEST.json names, or the latency did not recompute
#       3 INDETERMINATE: a runtime that can check every leg was not found (nothing is claimed)
#       4 everything present holds, and an exhibit is still pending (named in the output)

set -u
cd "$(dirname "$0")" || exit 2

TRUST="trust/ica-trust-anchor.json"
FLAGS=(--trust-anchor "$TRUST" --require-pin)

say() { printf '%s\n' "$*"; }
indeterminate() { say ""; say "INDETERMINATE: $1"; say "Nothing above or below is a pass. Fix the runtime and run again."; exit 3; }

say "ICA Proof Room v2 · offline check · $(date -u +%Y-%m-%dT%H:%M:%SZ)"
say ""

# ── 1. Runtimes that can check every leg ──────────────────────────────────────────
node_ok() { "$1" -e "require('crypto').generateKeyPairSync('ml-dsa-65')" >/dev/null 2>&1; }
NODE_BIN=""
TRIED_NODE=""
for cand in ${NODE:-} $(type -ap node 2>/dev/null) /opt/homebrew/bin/node /usr/local/bin/node; do
  [ -x "$cand" ] || continue
  case " $TRIED_NODE " in *" $cand "*) continue ;; esac
  TRIED_NODE="$TRIED_NODE $cand"
  if node_ok "$cand"; then NODE_BIN="$cand"; break; fi
done
[ -n "$NODE_BIN" ] || indeterminate "no Node with ML-DSA was found (tried:${TRIED_NODE:- none}). The post-quantum leg needs Node 24 or later. Install it, or set NODE=/path/to/node."
say "Node    $NODE_BIN ($("$NODE_BIN" --version)), ML-DSA available"

PY_BIN=""
TRIED_PY=""
PY_WHY=""
for cand in ${PYTHON:-} $(type -ap python3 2>/dev/null); do
  [ -x "$cand" ] || continue
  case " $TRIED_PY " in *" $cand "*) continue ;; esac
  TRIED_PY="$TRIED_PY $cand"
  if ! "$cand" -c "import cryptography" >/dev/null 2>&1; then PY_WHY="$cand has no 'cryptography' package (pip install cryptography)"; continue; fi
  if ! "$cand" -c "from cryptography.hazmat.primitives.asymmetric import mldsa; mldsa.MLDSA65PublicKey" >/dev/null 2>&1; then
    PY_WHY="$cand has cryptography $("$cand" -c 'import cryptography; print(cryptography.__version__)') built without ML-DSA; install a cryptography build with ML-DSA"
    continue
  fi
  PY_BIN="$cand"; break
done
[ -n "$PY_BIN" ] || indeterminate "no python3 with ML-DSA was found (tried:${TRIED_PY:- none}). ${PY_WHY:-Install python3 and the cryptography package.} Or set PYTHON=/path/to/python3."
say "Python  $PY_BIN ($("$PY_BIN" -c 'import sys,cryptography; print("%d.%d.%d" % sys.version_info[:3], "cryptography", cryptography.__version__)')), ML-DSA available"
say ""

FAILS=0
MISMATCHES=0
PENDING=""

# ── 2. Every file is the one MANIFEST.json names ──────────────────────────────────
MANIFEST_OUT=$("$NODE_BIN" -e '
const fs = require("fs"), crypto = require("crypto");
const m = JSON.parse(fs.readFileSync("MANIFEST.json", "utf8"));
let bad = 0;
for (const [f, want] of Object.entries(m.files)) {
  let got = null;
  try { got = crypto.createHash("sha256").update(fs.readFileSync(f)).digest("hex"); } catch (_) {}
  if (got !== want) { bad += 1; console.log("  CHANGED " + f + (got ? "" : " (missing)")); }
}
console.log(`MANIFEST: ${Object.keys(m.files).length} files, ${bad ? bad + " not as built" : "every sha256 matches"} (built ${m.built_at}, production commit ${m.ica_commit_on_build_day})`);
process.exit(bad ? 1 : 0);
' 2>&1) || FAILS=$((FAILS + 1))
say "$MANIFEST_OUT"
say ""

# ── 3. The trust anchor: confirm these on your phone before relying on a verdict ──
say "Trust anchor $TRUST, fingerprints (confirm each at https://ica.aleeth.com/.well-known/ica-trust-anchor.json):"
grep -E '^[a-z0-9][a-z0-9-]*  \(|^  [0-9a-f]{4} ' trust/FINGERPRINTS.txt | sed 's/^/  /'
say ""

# ── 4. Exhibits 01, 02, 03 and 05: both verifiers, pinned, --require-pin ─────────
verdict_of() { grep -o '"overall": *"[A-Z_][A-Z_]*"' | head -1 | sed 's/.*"\([A-Z_]*\)"$/\1/'; }
reason_of() { grep -o '"reason": *"[A-Z_][A-Z_]*"' | head -1 | sed 's/.*"\([A-Z_]*\)"$/\1/'; }
finality_of() { grep -o '"external_finality": *"[A-Z_][A-Z_]*"' | head -1 | sed 's/.*"\([A-Z_]*\)"$/\1/'; }
is_pass() { case "$1" in VERIFIED_EXTERNALLY_ANCHORED|VERIFIED_INTERNAL_FINALITY|PROVISIONAL|HISTORICALLY_VALID_REVOKED_NOW) return 0 ;; *) return 1 ;; esac; }

printf '%-36s %-30s %-30s %-30s %s\n' "EXHIBIT" "MUST GIVE" "NODE VERIFIER" "PYTHON VERIFIER" "RESULT"
ROWS=$("$NODE_BIN" -e '
const e = require("./exhibits/expected-verdicts.json");
for (const x of e.exhibits) console.log([x.id, x.file, x.expect, x.reason || "-", x.must, x.external_finality || "-"].join("\t"));
')
while IFS=$'\t' read -r id file expect reason must efin; do
  [ -n "$id" ] || continue
  n_out=$("$NODE_BIN" tools/ica-verify/verify.js "$file" --json "${FLAGS[@]}" 2>/dev/null)
  p_out=$("$PY_BIN" -I -B verifier/python/ica_verify.py "$file" "${FLAGS[@]}" 2>/dev/null)
  nv=$(printf '%s' "$n_out" | verdict_of); nr=$(printf '%s' "$n_out" | reason_of)
  pv=$(printf '%s' "$p_out" | verdict_of); pr=$(printf '%s' "$p_out" | reason_of)
  nf=$(printf '%s' "$n_out" | finality_of); pf=$(printf '%s' "$p_out" | finality_of)
  [ -n "$nv" ] || nv="NO_VERDICT"; [ -n "$pv" ] || pv="NO_VERDICT"
  [ "$reason" = "-" ] && reason=""
  result="OK"
  if [ "$nv" != "$pv" ] || [ "$nr" != "$pr" ]; then result="MISMATCH between the verifiers"; MISMATCHES=$((MISMATCHES + 1)); FAILS=$((FAILS + 1))
  elif [ "$must" = "fail" ] && is_pass "$nv"; then result="FAILED: a tampered copy passed"; FAILS=$((FAILS + 1))
  elif [ "$nv" != "$expect" ] || [ "$nr" != "$reason" ]; then result="FAILED: not the stated verdict"; FAILS=$((FAILS + 1))
  elif [ "$efin" != "-" ] && { [ "$nf" != "$efin" ] || [ "$pf" != "$efin" ]; }; then result="FAILED: external finality ${nf:-none} / ${pf:-none}, must be $efin"; FAILS=$((FAILS + 1))
  elif [ "$must" = "fail" ]; then result="OK, refused as it must be"
  elif [ "$efin" != "-" ]; then result="OK, external finality $efin in both"
  fi
  show() { if [ -n "$2" ]; then printf '%s/%s' "$1" "$2"; else printf '%s' "$1"; fi; }
  printf '%-36s %-30s %-30s %-30s %s\n' "$id" "$(show "$expect" "$reason")" "$(show "$nv" "$nr")" "$(show "$pv" "$pr")" "$result"
done <<< "$ROWS"
say ""

# ── 5. Exhibit 04: the anchor spine and its registered exceptions ─────────────────
A04=$("$NODE_BIN" -e '
const a = require("./exhibits/expected-verdicts.json").anchor;
console.log([a.status, a.anchors_file, a.exceptions_file || "-", a.expect, a.strict_on_build_day.verified, a.strict_on_build_day.broken_at, a.strict_on_build_day.breaks.join(" "), a.pending_reason || "-"].join("\t"));
')
IFS=$'\t' read -r a_status a_file a_exc a_expect a_strict a_broken a_breaks a_why <<< "$A04"
say "04 anchor spine: strict verdict as served on build day: verified $a_strict, broken at $a_broken (breaks at $a_breaks)"
if [ "$a_status" = "ready" ] && [ "$a_exc" != "-" ] && "$NODE_BIN" tools/ica-verify/verify.js --help 2>&1 | grep -q -- '--anchors'; then
  a_out=$("$NODE_BIN" tools/ica-verify/verify.js --anchors "$a_file" --exceptions "$a_exc" --json 2>/dev/null)
  av=$(printf '%s' "$a_out" | verdict_of)
  if [ "$av" = "$a_expect" ]; then say "04 registered-exception verdict (Node verifier, sampled method): $av  OK"
  else say "04 registered-exception verdict: ${av:-NO_VERDICT}, must give $a_expect  FAILED"; FAILS=$((FAILS + 1)); fi
  say "   The Python verifier has no anchor-spine mode; this exhibit is checked by the Node verifier only."
else
  say "04 PENDING: ${a_why}"
  say "   Rebuild the kit once ICA serves /api/transparency/anchor-exceptions, and this row checks it."
  PENDING="$PENDING 04"
fi
say ""

# ── 6. Exhibit 06: decision latency recomputed from the sealed rollups ────────────
if "$NODE_BIN" exhibits/06-latency/recompute.js; then :; else FAILS=$((FAILS + 1)); fi
say ""

# ── 7. Bitcoin, stated separately ─────────────────────────────────────────────────
say "Bitcoin: neither verifier checks Bitcoin. Each exhibit's custody.external_anchor carries the"
say "OpenTimestamps proof of the audit seal that covers its root. Check it with an OpenTimestamps"
say "client (ots verify). The link from a receipt's root to that seal rests on ICA's audit chain,"
say "which these packages do not carry."
say ""

say "Mismatches between the two verifiers: $MISMATCHES"
if [ "$FAILS" -gt 0 ]; then say "RESULT: FAILED ($FAILS check(s) above did not hold)"; exit 1; fi
if [ -n "$PENDING" ]; then say "RESULT: every present exhibit holds on both verifiers; pending:$PENDING"; exit 4; fi
say "RESULT: every exhibit holds on both verifiers"
exit 0
