/* verify.mjs: the lab notebook for "The Proof That Tells You Nothing".
 *
 * Everything the page asserts about the protocol is re-derived here, offline, from the
 * SAME engine file the page ships (public/strata/the-proof-that-tells-you-nothing/zk-engine.js).
 * There is no second copy to drift. Where a check could be satisfied by the engine merely
 * agreeing with itself, it is checked against something the engine does not control:
 *   • SHA-256 against node:crypto and the FIPS 180-4 test vectors
 *   • the graph facts against exhaustive enumeration of all 3^n assignments
 *   • the soundness bound against an empirical run of the actual attack
 *   • the round checker against a mutation sweep: every way of corrupting a transcript
 *     must be caught, and if any slips through, that is a real failure, not a warning.
 *
 *   node research/the-proof-that-tells-you-nothing/verify.mjs
 */

import { createHash } from 'node:crypto';
import {
  sha256, sha256Hex, sha256HexAscii, sha256FirstWordAscii, toHex, utf8,
  commit, commitMessage, checkOpening, checkRound,
  rng, randInt, randomNonce, PERMS, GRAPHS, defect, monochromaticEdges,
  surveyThreeColourings, findColouring, honestProver, lyingProver, simulator,
  survival, roundsFor, breakRound,
} from '../../public/strata/the-proof-that-tells-you-nothing/zk-engine.js';

let fails = 0, count = 0;
const ok = (name, cond, extra = '') => {
  count++; if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};
const H = (s) => console.log('\n' + s + '\n' + '-'.repeat(s.length));
const fmt = (n) => n.toLocaleString('en-US');

const PET = GRAPHS.petersen;
const GRO = GRAPHS.grotzsch;

/* ══════════════════════════════════ 1. SHA-256 is really SHA-256 ══════════ */
H('1. The hash. Our own SHA-256 against the platform\'s, and against FIPS 180-4.');

// The two published one-block / two-block examples from FIPS 180-4 Appendix B.
ok('FIPS 180-4 B.1  "abc"',
  sha256Hex('abc') === 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad',
  sha256Hex('abc'));
ok('FIPS 180-4 B.2  56-char message',
  sha256Hex('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq')
    === '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1');
ok('empty string',
  sha256Hex('') === 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855');
// A million 'a's is the third published vector; run it as one buffer.
{
  const million = new Uint8Array(1000000).fill(0x61);
  ok('FIPS 180-4 B.3  one million "a"',
    toHex(sha256(million)) === 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0');
}

{
  let mismatch = 0;
  const next = rng(20260726);
  for (let i = 0; i < 5000; i++) {
    const len = randInt(next, 200);
    const bytes = new Uint8Array(len);
    for (let j = 0; j < len; j++) bytes[j] = randInt(next, 256);
    const mine = toHex(sha256(bytes));
    const theirs = createHash('sha256').update(Buffer.from(bytes)).digest('hex');
    if (mine !== theirs) mismatch++;
  }
  ok('5,000 random inputs, 0-200 bytes: agrees with node:crypto', mismatch === 0, `${mismatch} mismatches`);
}
{
  // Lengths straddling every padding boundary, where hand-rolled SHA-256 usually breaks.
  let mismatch = 0;
  for (let len = 0; len <= 200; len++) {
    const bytes = new Uint8Array(len).fill(0x5a);
    if (toHex(sha256(bytes)) !== createHash('sha256').update(Buffer.from(bytes)).digest('hex')) mismatch++;
  }
  ok('every length 0..200 (all padding boundaries): agrees with node:crypto', mismatch === 0, `${mismatch} mismatches`);
}

{
  // The engine ships three code paths for the same function: the general one, a
  // one-block fast path used for every commitment, and a first-word filter used by the
  // brute-force movement. All three must agree with node:crypto or the page is lying
  // at a level no reader could see.
  const next = rng(8675309);
  let fastBad = 0, wordBad = 0;
  for (let i = 0; i < 4000; i++) {
    const msg = commitMessage(randInt(next, 11), randInt(next, 3), randomNonce(next, 128));
    const truth = createHash('sha256').update(msg).digest('hex');
    if (sha256HexAscii(msg) !== truth) fastBad++;
    if (sha256FirstWordAscii(msg) !== (parseInt(truth.slice(0, 8), 16) >>> 0)) wordBad++;
  }
  ok('the one-block fast path agrees with node:crypto on 4,000 commitment messages', fastBad === 0, `${fastBad} bad`);
  ok('the brute-force first-word filter agrees with node:crypto on the same 4,000', wordBad === 0, `${wordBad} bad`);
  let boundary = 0;
  for (let L = 0; L <= 80; L++) {
    const s = 'a'.repeat(L);
    if (sha256HexAscii(s) !== createHash('sha256').update(s).digest('hex')) boundary++;
  }
  ok('fast path agrees at every ASCII length 0..80, including its 55-byte handover', boundary === 0, `${boundary} bad`);
}

/* ══════════════════════════════════ 2. The commitment ═════════════════════ */
H('2. The commitment. What is hashed, and what each part of it stops.');

ok('message format is exactly as documented',
  commitMessage(7, 2, 'deadbeef') === 'zk3c|v=7|c=2|n=deadbeef',
  commitMessage(7, 2, 'deadbeef'));
ok('an honest opening verifies', checkOpening(commit(7, 2, 'deadbeef'), 7, 2, 'deadbeef') === null);
ok('a wrong colour does not', checkOpening(commit(7, 2, 'deadbeef'), 7, 1, 'deadbeef') !== null);
ok('a wrong nonce does not', checkOpening(commit(7, 2, 'deadbeef'), 7, 2, 'deadbeee') !== null);
ok('the SAME colour+nonce at a DIFFERENT vertex does not verify (domain separation)',
  checkOpening(commit(7, 2, 'deadbeef'), 8, 2, 'deadbeef') !== null);
ok('a colour outside {0,1,2} is refused', checkOpening(commit(7, 2, 'dead'), 7, 5, 'dead') !== null);

{
  // Avalanche: one flipped nonce character should move about half the digest bits.
  const base = commit(3, 1, '0'.repeat(32));
  const flipped = commit(3, 1, '1' + '0'.repeat(31));
  let diff = 0;
  for (let i = 0; i < 64; i += 2) {
    const a = parseInt(base.slice(i, i + 2), 16), b = parseInt(flipped.slice(i, i + 2), 16);
    let x = a ^ b; while (x) { diff += x & 1; x >>= 1; }
  }
  ok('flipping one nonce character moves ~128 of 256 digest bits', diff > 96 && diff < 160, `${diff} bits`);
}
{
  // 30,000 commitments, no collision. Not a proof of anything; a smoke test that the
  // nonce space is actually being used and the digests are not degenerate.
  const next = rng(7);
  const seen = new Set();
  for (let i = 0; i < 30000; i++) seen.add(commit(randInt(next, 11), randInt(next, 3), randomNonce(next, 128)));
  ok('30,000 commitments with 128-bit nonces: all distinct', seen.size === 30000, `${seen.size} distinct`);
}

/* ══════════════════════════════════ 3. The two graphs ═════════════════════ */
H('3. The graphs. Every claim by exhaustive enumeration of all 3^n assignments.');

function degrees(g) { const d = new Array(g.n).fill(0); for (const [u, v] of g.edges) { d[u]++; d[v]++; } return d; }
function triangles(g) {
  const adj = Array.from({ length: g.n }, () => new Set());
  for (const [u, v] of g.edges) { adj[u].add(v); adj[v].add(u); }
  let t = 0;
  for (let a = 0; a < g.n; a++) for (const b of adj[a]) if (b > a) for (const c of adj[b]) if (c > b && adj[a].has(c)) t++;
  return t;
}
function bipartite(g) {
  const adj = Array.from({ length: g.n }, () => []);
  for (const [u, v] of g.edges) { adj[u].push(v); adj[v].push(u); }
  const col = new Array(g.n).fill(-1);
  for (let s = 0; s < g.n; s++) {
    if (col[s] !== -1) continue;
    col[s] = 0; const q = [s];
    while (q.length) { const x = q.pop(); for (const y of adj[x]) { if (col[y] === -1) { col[y] = 1 - col[x]; q.push(y); } else if (col[y] === col[x]) return false; } }
  }
  return true;
}
function kColourable(g, k) {
  const adj = Array.from({ length: g.n }, () => []);
  for (const [u, v] of g.edges) { adj[u].push(v); adj[v].push(u); }
  const a = new Array(g.n).fill(-1);
  const go = (i) => {
    if (i === g.n) return true;
    for (let c = 0; c < k; c++) {
      if (adj[i].some((j) => a[j] === c)) continue;
      a[i] = c; if (go(i + 1)) return true; a[i] = -1;
    }
    return false;
  };
  return go(0);
}
function uniqueEdges(g) {
  return new Set(g.edges.map(([a, b]) => (a < b ? a + '-' + b : b + '-' + a))).size;
}

const petSurvey = surveyThreeColourings(PET);
const groSurvey = surveyThreeColourings(GRO);

console.log('  Petersen  n=%d m=%d  degrees=%s', PET.n, PET.edges.length, degrees(PET).join(''));
ok('Petersen: 10 vertices, 15 edges, all distinct', PET.n === 10 && PET.edges.length === 15 && uniqueEdges(PET) === 15);
ok('Petersen: 3-regular', degrees(PET).every((d) => d === 3));
ok('Petersen: triangle-free', triangles(PET) === 0);
ok('Petersen: NOT 2-colourable (it has an odd cycle)', bipartite(PET) === false);
ok('Petersen: exactly 120 proper 3-colourings out of 59,049 assignments',
  petSurvey.proper === 120 && petSurvey.total === 59049, `${petSurvey.proper} / ${petSurvey.total}`);
ok('Petersen: 120 = 6 x 20, i.e. 20 colourings up to renaming the three colours',
  petSurvey.proper === 6 * 20);
ok('Petersen: a random assignment is proper about 1 time in 492',
  Math.round(petSurvey.total / petSurvey.proper) === 492, `1 in ${(petSurvey.total / petSurvey.proper).toFixed(2)}`);
ok('Petersen: minimum monochromatic edges over all assignments is 0 (so chi = 3)', petSurvey.minDefect === 0);

{
  /* An independent cross-check on the count of 120 that does not go through our edge list
   * at all: the Petersen graph's chromatic polynomial is a published object. Evaluate it. */
  const P = [1, -15, 105, -455, 1353, -2861, 4275, -4305, 2606, -704, 0];   // k^10 .. k^0
  const at = (k) => P.reduce((acc, c) => acc * k + c, 0);
  ok('published chromatic polynomial: P(1) = 0 and P(2) = 0 (not 1- or 2-colourable)',
    at(1) === 0 && at(2) === 0, `P(1)=${at(1)} P(2)=${at(2)}`);
  ok('published chromatic polynomial: P(3) = 120, agreeing with our enumeration',
    at(3) === petSurvey.proper, `P(3)=${at(3)} vs enumerated ${petSurvey.proper}`);
  console.log(`  cross-check: P(4)=${fmt(at(4))}  P(5)=${fmt(at(5))}`);
}

console.log('  Grotzsch  n=%d m=%d  degrees=%s', GRO.n, GRO.edges.length, degrees(GRO).join(''));
ok('Grotzsch: 11 vertices, 20 edges, all distinct', GRO.n === 11 && GRO.edges.length === 20 && uniqueEdges(GRO) === 20);
ok('Grotzsch: triangle-free', triangles(GRO) === 0);
ok('Grotzsch: ZERO proper 3-colourings out of 177,147 assignments',
  groSurvey.proper === 0 && groSurvey.total === 177147, `${groSurvey.proper} / ${groSurvey.total}`);
ok('Grotzsch: 4-colourable, so its chromatic number is exactly 4', kColourable(GRO, 4) === true);
ok('Grotzsch: the least-bad 3-assignment leaves exactly 1 monochromatic edge',
  groSurvey.minDefect === 1, `minDefect=${groSurvey.minDefect}`);
ok('Grotzsch: 660 different assignments achieve that minimum',
  groSurvey.minCount === 660, `${groSurvey.minCount}`);
ok('Grotzsch: the best liar is caught with probability exactly 1/20 per round',
  groSurvey.minDefect / GRO.edges.length === 0.05);
ok('findColouring() finds a proper colouring of Petersen',
  (() => { const c = findColouring(PET); return c && defect(PET, c) === 0; })());
ok('findColouring() finds none for Grotzsch', findColouring(GRO) === null);

const PET_COLOURING = findColouring(PET);
const GRO_BEST_LIE = groSurvey.witness;
ok('the lying prover\'s committed assignment has exactly one bad edge',
  defect(GRO, GRO_BEST_LIE) === 1, JSON.stringify(GRO_BEST_LIE));

/* ══════════════════════════════════ 4. Completeness ═══════════════════════ */
H('4. Completeness. An honest prover is never caught, ever.');
{
  const next = rng(11);
  const P = honestProver(PET, PET_COLOURING, next);
  let rejected = 0;
  const N = 20000;
  for (let i = 0; i < N; i++) {
    const { digests } = P.round();
    const e = randInt(next, PET.edges.length);
    const r = checkRound(PET, e, digests, P.open(e));
    if (!r.ok) rejected++;
  }
  ok(`honest prover, ${N.toLocaleString('en-US')} rounds on Petersen: 0 rejections`, rejected === 0, `${rejected} rejections`);
}

/* ══════════════════════════════════ 5. Soundness ══════════════════════════ */
H('5. Soundness. The bound is 1 - 1/m per round, and on Grotzsch it is exactly tight.');

ok('survival(m=20, bad=1, k=1) = 0.95', Math.abs(survival(20, 1, 1) - 0.95) < 1e-12);
ok('rounds to push a 1/20 liar below one in a million = 270',
  roundsFor(20, 1, 1e-6) === 270, String(roundsFor(20, 1, 1e-6)));
ok('rounds to push a 1/15 liar below one in a million = 201',
  roundsFor(15, 1, 1e-6) === 201, String(roundsFor(15, 1, 1e-6)));

{
  const next = rng(2718);
  const P = lyingProver(GRO, GRO_BEST_LIE, next);
  const N = 100000;
  let caught = 0;
  for (let i = 0; i < N; i++) {
    const { digests } = P.round();
    const e = randInt(next, GRO.edges.length);
    if (!checkRound(GRO, e, digests, P.open(e)).ok) caught++;
  }
  const rate = caught / N;
  const se = Math.sqrt(0.05 * 0.95 / N);
  const z = Math.abs(rate - 0.05) / se;
  console.log(`  empirical catch rate over ${N.toLocaleString('en-US')} rounds: ${rate.toFixed(5)}  (theory 0.05, z=${z.toFixed(2)})`);
  ok('empirical per-round catch rate matches 1/20 within 4 standard errors', z < 4, `z=${z.toFixed(2)}`);
}

{
  // Rounds until the liar is caught should be Geometric(1/20). Chi-square it.
  const next = rng(31415);
  const trials = 20000;
  const bins = 10;              // 1-10, 11-20, ..., 81-90, 91+
  const width = 10;
  const obs = new Array(bins).fill(0);
  let sum = 0;
  for (let t = 0; t < trials; t++) {
    const P = lyingProver(GRO, GRO_BEST_LIE, next);
    let k = 0;
    for (;;) {
      k++;
      const { digests } = P.round();
      const e = randInt(next, GRO.edges.length);
      if (!checkRound(GRO, e, digests, P.open(e)).ok) break;
    }
    sum += k;
    const b = Math.min(bins - 1, Math.floor((k - 1) / width));
    obs[b]++;
  }
  const p = 0.05;
  const exp = new Array(bins).fill(0);
  for (let b = 0; b < bins - 1; b++) {
    exp[b] = trials * (Math.pow(1 - p, b * width) - Math.pow(1 - p, (b + 1) * width));
  }
  exp[bins - 1] = trials * Math.pow(1 - p, (bins - 1) * width);
  let chi2 = 0;
  for (let b = 0; b < bins; b++) chi2 += (obs[b] - exp[b]) ** 2 / exp[b];
  const mean = sum / trials;
  console.log(`  mean rounds to catch: ${mean.toFixed(2)}   (theory 1/p = 20)`);
  console.log(`  chi-square vs Geometric(0.05), ${bins - 1} df: ${chi2.toFixed(2)}`);
  ok('mean rounds-to-catch is 20 within 2%', Math.abs(mean - 20) < 0.4, mean.toFixed(3));
  // 9 df: the 99.9th percentile is 27.88.
  ok('rounds-to-catch fits Geometric(1/20) (chi-square < 27.88, the 0.001 tail at 9 df)',
    chi2 < 27.88, `chi2=${chi2.toFixed(2)}`);
}

/* ══════════════════════════════════ 6. Mutation sweep ═════════════════════ */
H('6. Can the checker actually fail? Every corruption of a valid transcript must be caught.');
{
  const next = rng(999);
  const P = honestProver(PET, PET_COLOURING, next);
  const corruptions = {
    'flip the revealed colour of one end': (d, e, o) => { const c = o.map((x) => ({ ...x })); c[0].colour = (c[0].colour + 1) % 3; return [d, e, c]; },
    'flip one character of a nonce': (d, e, o) => { const c = o.map((x) => ({ ...x })); const n = c[1].nonce; c[1].nonce = (n[0] === 'a' ? 'b' : 'a') + n.slice(1); return [d, e, c]; },
    'answer with the other end\'s opening': (d, e, o) => [d, e, [{ ...o[1], index: o[0].index }, o[1]]],
    'give both ends the same colour': (d, e, o) => { const c = o.map((x) => ({ ...x })); c[1].colour = c[0].colour; return [d, e, c]; },
    'open a different edge than the one challenged': (d, e, o) => [d, (e + 1) % PET.edges.length, o],
    'tamper with one published digest': (d, e, o) => { const c = d.slice(); c[o[0].index] = '0'.repeat(64); return [c, e, o]; },
    'swap two published digests': (d, e, o) => { const c = d.slice(); const t = c[o[0].index]; c[o[0].index] = c[o[1].index]; c[o[1].index] = t; return [c, e, o]; },
  };
  const missed = {};
  const trials = 400;
  for (const [label, mutate] of Object.entries(corruptions)) {
    let slipped = 0;
    for (let i = 0; i < trials; i++) {
      const { digests } = P.round();
      const e = randInt(next, PET.edges.length);
      const openings = P.open(e);
      // sanity: the clean round must pass, or the sweep proves nothing
      if (!checkRound(PET, e, digests, openings).ok) { slipped = -1; break; }
      const [d2, e2, o2] = mutate(digests, e, openings);
      if (checkRound(PET, e2, d2, o2).ok) slipped++;
    }
    missed[label] = slipped;
    ok(`caught: ${label}`, slipped === 0, slipped === -1 ? 'clean round failed!' : `${slipped}/${trials} slipped through`);
  }
  void missed;
}

/* ══════════════════════════════════ 7. Zero knowledge ═════════════════════ */
H('7. Zero knowledge. What you see is identically distributed with and without a witness.');

function pairIndex(a, b) {           // the 6 ordered pairs of distinct colours
  const table = { '01': 0, '02': 1, '10': 2, '12': 3, '20': 4, '21': 5 };
  return table[`${a}${b}`];
}

{
  const N = 60000;
  const real = new Array(6).fill(0);
  const sim = new Array(6).fill(0);
  const realVertex = Array.from({ length: PET.n }, () => [0, 0, 0]);
  let rewindTotal = 0;

  const nr = rng(4242);
  const P = honestProver(PET, PET_COLOURING, nr);
  for (let i = 0; i < N; i++) {
    const { digests } = P.round();
    const e = randInt(nr, PET.edges.length);
    const o = P.open(e);
    const r = checkRound(PET, e, digests, o);
    if (!r.ok) throw new Error('honest round rejected during the ZK sweep');
    real[pairIndex(o[0].colour, o[1].colour)]++;
    realVertex[o[0].index][o[0].colour]++;
    realVertex[o[1].index][o[1].colour]++;
  }

  const ns = rng(2424);
  const S = simulator(PET, ns);
  for (let i = 0; i < N; i++) {
    const e = randInt(ns, PET.edges.length);
    const { digests, rewinds } = S.roundFor(e);
    rewindTotal += rewinds;
    const o = S.open(e);
    const r = checkRound(PET, e, digests, o);
    if (!r.ok) throw new Error('simulated round rejected');
    sim[pairIndex(o[0].colour, o[1].colour)]++;
  }

  const expected = N / 6;
  let chiReal = 0, chiSim = 0, tv = 0;
  for (let i = 0; i < 6; i++) {
    chiReal += (real[i] - expected) ** 2 / expected;
    chiSim += (sim[i] - expected) ** 2 / expected;
    tv += Math.abs(real[i] / N - sim[i] / N);
  }
  tv /= 2;
  console.log('  revealed pair (01 02 10 12 20 21)');
  console.log('    real:      ' + real.map((x) => (x / N).toFixed(4)).join('  '));
  console.log('    simulated: ' + sim.map((x) => (x / N).toFixed(4)).join('  '));
  console.log(`  total variation distance between them: ${tv.toFixed(5)}`);
  ok('real transcripts: the revealed pair is uniform over the 6 (chi-square < 20.5, 5 df, p=0.001)',
    chiReal < 20.52, `chi2=${chiReal.toFixed(2)}`);
  ok('simulated transcripts: same uniformity', chiSim < 20.52, `chi2=${chiSim.toFixed(2)}`);
  ok('the two revealed-pair distributions are within 0.01 in total variation', tv < 0.01, `TV=${tv.toFixed(5)}`);

  // Every vertex's revealed colour is uniform: this is the colour permutation doing its work.
  let worst = 0;
  for (let v = 0; v < PET.n; v++) {
    const tot = realVertex[v].reduce((a, b) => a + b, 0);
    for (let c = 0; c < 3; c++) worst = Math.max(worst, Math.abs(realVertex[v][c] / tot - 1 / 3));
  }
  ok('every vertex is revealed as each of the 3 colours equally often (max deviation < 0.01)',
    worst < 0.01, `max |p - 1/3| = ${worst.toFixed(4)}`);

  const meanRewinds = rewindTotal / N;
  console.log(`  simulator rewinds per accepted round: ${meanRewinds.toFixed(2)}   (theory m - 1 = ${PET.edges.length - 1})`);
  ok('the simulator pays about m-1 = 14 rewinds per round', Math.abs(meanRewinds - 14) < 0.5, meanRewinds.toFixed(3));
}

{
  // The simulator never touches a colouring. Prove it the blunt way: give it a graph
  // that HAS no proper 3-colouring, and watch it still produce accepted transcripts.
  const next = rng(1234);
  const S = simulator(GRO, next);
  let accepted = 0;
  for (let i = 0; i < 4000; i++) {
    const e = randInt(next, GRO.edges.length);
    const { digests } = S.roundFor(e);
    if (checkRound(GRO, e, digests, S.open(e)).ok) accepted++;
  }
  ok('the simulator passes 4,000/4,000 rounds on Grotzsch, which nobody can 3-colour',
    accepted === 4000, `${accepted}/4000`);
}

/* ══════════════════════════════════ 8. The nonce is the security ══════════ */
H('8. Shrink the nonce and the proof stops being zero knowledge. That is the whole assumption.');
{
  const next = rng(55555);
  const bits = 12;
  const P = honestProver(PET, PET_COLOURING, next, bits);
  const { digests } = P.round();
  const broken = breakRound(PET, digests, bits);
  ok(`with a ${bits}-bit nonce, brute force recovers every committed colour`,
    broken.complete, `${broken.hashes.toLocaleString('en-US')} digests`);
  ok('and what it recovers is a genuine proper 3-colouring: the witness has leaked',
    broken.complete && defect(PET, broken.assign) === 0, `defect=${defect(PET, broken.assign)}`);

  const S = simulator(PET, next, bits);
  const e = randInt(next, PET.edges.length);
  const simRound = S.roundFor(e);
  const brokenSim = breakRound(PET, simRound.digests, bits);
  ok('brute-forcing a SIMULATED round recovers an assignment that is NOT a proper colouring',
    brokenSim.complete && defect(PET, brokenSim.assign) > 0, `defect=${defect(PET, brokenSim.assign)}`);
  console.log('  so with a short nonce the two transcripts become trivially distinguishable,');
  console.log('  and with a real one they do not. Nothing else changed.');
}
{
  // What a full-length nonce actually costs an attacker, measured rather than asserted.
  // Measured with the fastest path the engine has, which is the one an attacker would
  // actually use: the first-word filter, not the full-hex commit.
  const t0 = process.hrtime.bigint();
  const probe = 1000000;
  let sink = 0;
  for (let i = 0; i < probe; i++) sink ^= sha256FirstWordAscii(commitMessage(0, i % 3, (i % 65536).toString(16).padStart(4, '0')));
  const secs = Number(process.hrtime.bigint() - t0) / 1e9;
  const rate = probe / secs;
  const workFor128 = 3 * Math.pow(2, 127);      // expected digests to find one 128-bit nonce
  const years = workFor128 / rate / (365.25 * 24 * 3600);
  console.log(`  measured here: ${(rate / 1e6).toFixed(2)} million digests/second (single core, plain JS)   [sink ${sink}]`);
  console.log(`  expected work for ONE 128-bit nonce: 3 x 2^127 = ${workFor128.toExponential(2)} digests`);
  console.log(`  at this rate: ${years.toExponential(2)} years  (the universe is 1.38e10 years old)`);
  console.log(`  ratio to the age of the universe: ${(years / 1.38e10).toExponential(2)}`);
  ok('one 128-bit nonce costs this machine more than a trillion times the age of the universe',
    years / 1.38e10 > 1e12, `${(years / 1.38e10).toExponential(2)} x`);

  // And with hardware. The Bitcoin network is the largest SHA-256 engine ever assembled:
  // ~900 EH/s as a 7-day mean, 19-25 July 2026 (blockchain.info), inferred from block times
  // and volatile by tens of percent, so it is used only as an order of magnitude. It counts
  // complete double-SHA-256 evaluations, which makes the comparison conservative.
  const BITCOIN_HASHES_PER_SEC = 1.0e21;
  const btcYears = workFor128 / BITCOIN_HASHES_PER_SEC / (365.25 * 24 * 3600);
  console.log(`  the entire Bitcoin network at ~1e21 H/s would need ${btcYears.toExponential(2)} years`);
  ok('at ~1e21 hashes/second, one 128-bit nonce costs of order 1e10 years, comparable to the age of the universe',
    btcYears > 1e9 && btcYears < 1e12, `${btcYears.toExponential(2)} years vs 1.38e10`);
  ok('this rests on an assumption, named on the page: no attack on SHA-256 better than brute force', true);
}

/* ══════════════════════════════════ 9. Numbers quoted on the page ═════════ */
H('9. The figures the page prints, pinned here.');
const PINNED = {
  petersen_vertices: 10, petersen_edges: 15, petersen_proper_3_colourings: 120,
  petersen_assignments: 59049, petersen_one_in: 492,
  grotzsch_vertices: 11, grotzsch_edges: 20, grotzsch_proper_3_colourings: 0,
  grotzsch_min_defect: 1, grotzsch_min_count: 660, grotzsch_catch_per_round: 0.05,
  rounds_to_one_in_a_million_grotzsch: 270, rounds_to_one_in_a_million_petersen: 201,
  simulator_rewinds_petersen: 14, revealed_pairs: 6,
};
ok('Petersen proper 3-colourings = 120', petSurvey.proper === PINNED.petersen_proper_3_colourings);
ok('Grotzsch proper 3-colourings = 0', groSurvey.proper === PINNED.grotzsch_proper_3_colourings);
ok('Grotzsch minimum defect = 1', groSurvey.minDefect === PINNED.grotzsch_min_defect);
ok('Grotzsch minimisers = 660', groSurvey.minCount === PINNED.grotzsch_min_count);
ok('rounds to one-in-a-million on Grotzsch = 270', roundsFor(20, 1, 1e-6) === PINNED.rounds_to_one_in_a_million_grotzsch);
ok('rounds to one-in-a-million on Petersen = 201', roundsFor(15, 1, 1e-6) === PINNED.rounds_to_one_in_a_million_petersen);
ok('the 6 ordered pairs of distinct colours', PERMS.length === 6 && PINNED.revealed_pairs === 6);
console.log('\n' + JSON.stringify(PINNED, null, 2));

console.log(`\n${fails === 0 ? 'PASS' : 'FAIL'} ${count - fails}/${count}`);
process.exit(fails === 0 ? 0 : 1);
