export function gradeAnswer(answer) { if (answer === "bound-statement") { return { correct: true, heading: "Exercise complete", message: "Exactly. The proof binds a public statement: starting value 2, final value 52, and 2 steps. Claiming 53 changes that statement while the proof stays fixed, so verification fails." }; } if (answer === "changed-proof") { return { correct: false, heading: "The claim changed, not the proof", message: "Editing the field does not rewrite the bundled proof. It still binds the original starting value, final value, and step count. Try again." }; } if (answer === "steps-only") { return { correct: false, heading: "There is more to the statement", message: "The step count is only one part. The proof also binds the starting and final values. Both attempts used 2 steps, but only one claimed final value matched. Try again." }; } return { correct: false, heading: "Choose an explanation", message: "Choose one answer, then check it." }; } export function validateVerificationResponse(result, claimedFinal, expectedProof) { if (!result || typeof result !== "object" || Array.isArray(result)) throw new Error("Invalid verifier response"); if (!/^[0-9]{1,20}$/.test(claimedFinal) || BigInt(claimedFinal) > 18446744073709551615n) throw new Error("Invalid claim echo"); const normalized = BigInt(claimedFinal).toString(); if (typeof result.verified !== "boolean" || result.status !== (result.verified ? "accepted" : "rejected") || result.proof_sha256 !== expectedProof || result.statement?.initial !== 2 || result.statement?.steps !== 2 || result.statement?.claimed_final !== normalized) { throw new Error("Unexpected verifier response"); } return result; } export function classifyHttpError(status, result) { if ([400, 413, 415, 422].includes(status)) { return { status: "invalid_input", heading: "Invalid input", message: typeof result?.message === "string" ? result.message : status === 413 ? "The request is too large. Enter a single whole number." : "Enter a nonnegative whole number and try again." }; } return { status: "server_error", heading: "Verification unavailable", message: "The check did not complete. No proof result was returned. Please try again." }; } function startLesson() { const $ = (id) => document.getElementById(id); const expectedProof = document.querySelector("main").dataset.proofSha256; const state = { accepted52: false, rejected53: false, complete: false, busy: false, questionShown: false }; const prediction = () => document.querySelector('input[name="prediction"]:checked'); const bothChecks = () => state.accepted52 && state.rejected53; function showOutcome(id, status, heading, message, extra) { const box = $(id); box.dataset.status = status; const title = document.createElement("h3"); title.textContent = heading; const detail = document.createElement("p"); detail.textContent = message; box.replaceChildren(title, detail); if (extra) { const note = document.createElement("p"); note.textContent = extra; box.append(note); } box.hidden = false; } function update() { $("verify-button").disabled = state.busy || !prediction(); $("verify-button").setAttribute("aria-busy", String(state.busy)); document.body.dataset.verifying = String(state.busy); $("claimed-final").disabled = state.busy; $("prediction").disabled = state.busy; $("try-53").disabled = state.busy; $("verify-button").textContent = state.busy ? "Verifying…" : "Verify proof"; $("verify-hint").textContent = state.busy ? "Running the real verifier…" : prediction() ? "Ready to test your claim." : "Choose a prediction to continue."; $("answer-options").disabled = !bothChecks(); $("answer-button").disabled = !bothChecks() || !document.querySelector('input[name="answer"]:checked'); $("question-lock").hidden = bothChecks(); $("question-section").hidden = !bothChecks(); $("completion-actions").hidden = !state.complete; $("next-step").hidden = !state.accepted52 || state.rejected53; $("observations").hidden = !state.accepted52 && !state.rejected53; $("accepted-observation").hidden = !state.accepted52; $("rejected-observation").hidden = !state.rejected53; $("same-proof-observation").hidden = !bothChecks(); for (const [id, complete, active] of [ ["progress-predict", Boolean(prediction()), !prediction()], ["progress-test", bothChecks(), Boolean(prediction()) && !bothChecks()], ["progress-explain", state.complete, bothChecks() && !state.complete], ]) { $(id).classList.toggle("complete", complete); $(id).classList.toggle("active", active); if (active) $(id).setAttribute("aria-current", "step"); else $(id).removeAttribute("aria-current"); } if (bothChecks() && !state.questionShown) { state.questionShown = true; requestAnimationFrame(() => { if ($("question-title").getBoundingClientRect().bottom > window.innerHeight) { $("question-section").scrollIntoView({ behavior: matchMedia("(prefers-reduced-motion: reduce)").matches ? "auto" : "smooth", block: "nearest" }); } }); } } document.querySelectorAll('input[name="prediction"], input[name="answer"]').forEach((input) => input.addEventListener("change", update)); $("claimed-final").addEventListener("input", () => { document.querySelectorAll('input[name="prediction"]').forEach((input) => { input.checked = false; }); $("outcome").hidden = true; $("verification-time").hidden = true; $("claimed-final").removeAttribute("aria-invalid"); update(); }); $("try-53").addEventListener("click", () => { $("claimed-final").value = "53"; $("claimed-final").dispatchEvent(new Event("input", { bubbles: true })); $("claimed-final").focus(); $("claimed-final").select(); }); $("reset-exercise").addEventListener("click", () => window.location.reload()); $("verify-form").addEventListener("submit", async (event) => { event.preventDefault(); if (state.busy || !prediction()) return; const predicted = prediction().value; const claimedFinal = $("claimed-final").value; state.busy = true; $("claimed-final").removeAttribute("aria-invalid"); $("verification-time").hidden = true; update(); showOutcome("outcome", "pending", "Checking the proof…", "Waiting for the server verifier."); const controller = new AbortController(); const timeout = setTimeout(() => controller.abort(), 30000); try { const response = await fetch("/api/verify", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ claimed_final: claimedFinal }), signal: controller.signal, }); const payload = await response.json().catch(() => null); if (!response.ok) { const error = classifyHttpError(response.status, payload); if (error.status === "invalid_input") $("claimed-final").setAttribute("aria-invalid", "true"); showOutcome("outcome", error.status, error.heading, error.message); return; } const result = validateVerificationResponse(payload, claimedFinal, expectedProof); const claim = result.statement.claimed_final; const predictionNote = predicted === "unsure" ? "You have a real result to compare with your prediction." : `Your prediction: ${predicted === "accept" ? "accept" : "reject"}.`; showOutcome("outcome", result.status, result.verified ? "Proof accepted" : "Proof rejected", result.verified ? `The proof verifies for start 2, 2 steps, and final value ${claim}.` : `Final value ${claim} does not match the statement this proof supports. The artifact is unchanged.`, predictionNote); if (Number.isFinite(result.verification_ms) && result.verification_ms >= 0) { $("verification-time").textContent = `${Math.round(result.verification_ms).toLocaleString()} ms · server check`; $("verification-time").hidden = false; } if (result.verified && claim === "52") state.accepted52 = true; if (!result.verified && claim === "53" && state.accepted52) state.rejected53 = true; } catch { showOutcome("outcome", "server_error", "Verification unavailable", "No complete result was returned. Check your connection and try again; this is not a proof rejection."); } finally { clearTimeout(timeout); state.busy = false; update(); } }); $("question-form").addEventListener("submit", (event) => { event.preventDefault(); if (!bothChecks()) return; const answer = document.querySelector('input[name="answer"]:checked')?.value; const feedback = gradeAnswer(answer); state.complete = feedback.correct; showOutcome("answer-feedback", feedback.correct ? "correct" : "incorrect", feedback.heading, feedback.message); update(); }); update(); } if (typeof document !== "undefined") startLesson();