// ============================================================================
//  The Price of Going Backward: verifier for the combine portal.
//
//  THE SPINE. Five layers of this place each show a function that is cheap
//  forward and expensive backward. The portal's claim, which none of them states
//  alone, is that the PRICE is a different KIND of quantity in each, and that
//  the world's conversion between those kinds is one asymptotic formula pinned
//  at different points.
//
//  This file checks that claim four ways, and none of them is "the page says so":
//
//    A. THE PARENTS. Read the shipped source of every layer walked and require
//       that it still carries the fact this portal lifts from it, including that
//       our SHA-256 is byte-identical to the one /strata/hash-function/ ships.
//    B. THE ARITHMETIC. Re-derive NIST's formula against NIST's own worked table;
//       recover its two constants; reproduce BSI's published table from BSI's
//       own stated anchor.
//    C. THE SEARCHES. Re-run the experiment the page describes and require the
//       counts in measured.json.
//    D. THE PAGE. Extract every marked figure from the shipped HTML and require
//       each to be in the register, and every register entry to be used. Then
//       run a mutation control proving that check can actually go red.
//
//  Run:  node research/the-price-of-going-backward/verify.mjs
//        node research/the-price-of-going-backward/verify.mjs --selftest
// ============================================================================

import { readFileSync } from "node:fs";
import { fileURLToPath } from "node:url";
import { dirname, join } from "node:path";
import {
  sha256hex, log2L, GNFS_C, log2WorkRatio, log2Birthday, log2PollardRho,
  log2Exhaustive, roundsFor, findPreimageOfPrefix, findCollisionOfPrefix,
  expectedPreimageTrials, expectedCollisionTrials, prefixBits, sha256
} from "../../public/strata/the-price-of-going-backward/engine.js";
import { build, nistE, nistES, evidence, measured } from "./figures.mjs";

const HERE = dirname(fileURLToPath(import.meta.url));
const ROOT = join(HERE, "..", "..");
const P = (rel) => join(ROOT, rel);
const PAGE_DIR = "public/strata/the-price-of-going-backward";

let PASS = 0, FAIL = 0;
const lines = [];
function ok(label, cond, got, want) {
  if (cond) { PASS++; lines.push(`  ok   ${label}`); }
  else { FAIL++; lines.push(`  FAIL ${label}${got !== undefined ? `  (got ${got}, want ${want})` : ""}`); }
  return cond;
}
function head(s) { lines.push(""); lines.push(s); }
const near = (a, b, eps) => Math.abs(a - b) <= eps;
const src = (rel) => readFileSync(P(rel), "utf8");

/* =====================================================================
   A. THE PARENTS: every layer this portal walks, read at its shipped source.
   ===================================================================== */
head("A. THE PARENTS: the layers walked, checked against their own shipped bytes");

// A1. Our SHA-256 IS the hash layer's SHA-256, byte for byte.
{
  const parent = src("public/strata/hash-function/index.html");
  const start = parent.indexOf("    var K = new Uint32Array([");
  const end = parent.indexOf("    var enc = new TextEncoder();");
  ok("the parent page still contains the SHA-256 block we lifted", start > 0 && end > start);
  const block = parent.slice(start, end);

  const engine = src(`${PAGE_DIR}/engine.js`);
  const b0 = engine.indexOf("/* ---- AW-LIFTED-BEGIN");
  const b1 = engine.indexOf("/* ---- AW-LIFTED-END ---- */");
  const lifted = engine.slice(engine.indexOf("\n", b0) + 1, b1);
  ok("our engine's SHA-256 is byte-identical to the parent's", lifted === block,
    `${lifted.length} bytes`, `${block.length} bytes`);
}

// A2. FIPS 180-4 test vectors, through the lifted code.
ok('lifted SHA-256("abc") matches FIPS 180-4',
  sha256hex("abc") === "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad");
ok('lifted SHA-256("") matches FIPS 180-4',
  sha256hex("") === "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855");
{
  // and against the platform, over many messages, which is a different instrument
  const { createHash } = await import("node:crypto");
  let agree = 0;
  for (let i = 0; i < 3000; i++) {
    const m = "aw-" + i + "-" + "x".repeat(i % 137);
    if (sha256hex(m) === createHash("sha256").update(m).digest("hex")) agree++;
  }
  ok("lifted SHA-256 agrees with node:crypto over 3,000 messages", agree === 3000, agree, 3000);
}

// A3. Each parent still carries the claim the portal lifts from it.
const PARENT_CLAIMS = [
  ["public/strata/hash-function/index.html", "2<sup>128</sup>", "the hash layer still states the 2^128 collision bound"],
  ["public/strata/public-key-cryptography/index.html", "RSA-2048 has never been factored", "the RSA layer still states RSA-2048 has never been factored"],
  ["public/strata/the-secret-you-can-say-out-loud/index.html", "795 bits", "the Diffie-Hellman layer still states the 795-bit record"],
  ["public/strata/how-long-to-crack-your-password/index.html", "184.0", "the password layer still carries its bcrypt rate"],
  ["public/strata/the-proof-that-tells-you-nothing/index.html", "14/15", "the zero-knowledge layer still states the per-round cheating probability"],
];
for (const [rel, needle, label] of PARENT_CLAIMS) ok(label, src(rel).includes(needle));

// A4. The control layer really is two-directional, in its own words.
ok("the control layer states the formula reads in both directions",
  /backwards/i.test(src("public/strata/harmonics-of-the-primes/index.html")));

// A5. The near-neighbour we EXCLUDED really is about handwriting, not crypto.
{
  const sig = src("public/strata/the-signature-you-cannot-repeat/index.html");
  const cryptoish = /one-way function|RSA|preimage|public key/i.test(sig);
  ok("the excluded signature layer carries no cryptographic one-way claim", !cryptoish);
}

// A6. Our independent re-derivation reproduces the ZK layer's published round count.
ok("roundsFor(14/15, 1e-6) reproduces the parent's published 201 rounds",
  roundsFor(14 / 15, 1e-6) === 201, roundsFor(14 / 15, 1e-6), 201);

/* =====================================================================
   B. THE ARITHMETIC: the page's central claim, re-derived from scratch.
   ===================================================================== */
head("B. THE ARITHMETIC: NIST's formula, its constants, and BSI's table");

// B1. NIST's formula reproduces NIST's OWN worked table, every row.
{
  let rows = 0;
  for (const r of evidence.nist_formula.workedTable.rows) {
    const e = nistE(r.modulus), es = nistES(r.modulus);
    const eOK = near(e, r.E, 0.05);            // NIST prints 1 or 2 decimals
    const esOK = es === r.ES;
    if (ok(`SP 800-56B Table 4, ${r.modulus} bits: E ${e.toFixed(2)} vs printed ${r.E}; ES ${es} vs printed ${r.ES}`,
      eOK && esOK)) rows++;
  }
  ok("all five rows of NIST's own worked table reproduce", rows === 5, rows, 5);
}

// B2. The constant 1.923 IS the GNFS constant. (Our identification, not NIST's.)
ok("NIST's 1.923 equals (64/9)^(1/3) to the precision printed",
  near(GNFS_C, evidence.nist_formula.constants.c, 5e-4),
  GNFS_C.toFixed(6), evidence.nist_formula.constants.c);

// B3. The constant 4.69 IS the anchor that puts 1024 bits at 80.
{
  const c = evidence.nist_formula.constants.c;
  const exact = c * Math.cbrt(1024 * Math.LN2) * Math.cbrt(Math.pow(Math.log(1024 * Math.LN2), 2)) - 80 * Math.LN2;
  ok("the constant placing 1024 bits at exactly 80 rounds to NIST's 4.69",
    Number(exact.toFixed(2)) === evidence.nist_formula.constants.offset, exact.toFixed(4), 4.69);
  ok("so E(1024) lands on 80 to within a thousandth", near(nistE(1024), 80, 1e-3), nistE(1024).toFixed(6), 80);
}

// B4. The formula does NOT reproduce Table 2's top two rows, and DOES the lower three.
{
  const t2 = Object.fromEntries(evidence.nist_sp800_57.rows.map((r) => [r.rsa, r.strength]));
  ok("Table 2 at 1024 agrees with the formula", nistES(1024) === t2[1024], nistES(1024), t2[1024]);
  ok("Table 2 at 2048 agrees with the formula", nistES(2048) === t2[2048], nistES(2048), t2[2048]);
  ok("Table 2 at 3072 agrees with the formula", nistES(3072) === t2[3072], nistES(3072), t2[3072]);
  ok("Table 2 at 7680 DISAGREES with the formula (200 vs 192), as the page states",
    nistES(7680) === 200 && t2[7680] === 192, nistES(7680), 200);
  ok("Table 2 at 15360 DISAGREES with the formula (264 vs 256), as the page states",
    nistES(15360) === 264 && t2[15360] === 256, nistES(15360), 264);
}

// B5. The knife edge at 3072, and the flip at the next PERMITTED size.
{
  const e = nistE(3072);
  ok("E(3072) sits below the 132 midpoint", e < 132, e.toFixed(4), "< 132");
  ok("the margin is under a twentieth of a bit", 132 - e < 0.05, (132 - e).toFixed(4));
  ok("ES(3072) = 128", nistES(3072) === 128);
  ok("ES(3074) = 136, so the next even modulus flips the label", nistES(3074) === 136, nistES(3074), 136);
  // The reason 3074 is "the next size" is a rule in the same appendix. Assert the
  // rule is actually recorded, rather than asserting something that cannot fail.
  ok("SP 800-56B's even-modulus rule is on record, which is why 3074 is the next permitted size",
    /nBits must be an even integer/.test(evidence.nist_formula.quotes.evenModulus || ""));
  ok("and 3073 is odd, so it is not a size a reader may choose", 3073 % 2 === 1);
}

// B6. BSI's published table, reproduced from BSI's OWN stated anchor.
{
  const anchor = log2L(512, evidence.nist_formula.constants.c) - 50;
  let within1 = 0, worst = 0;
  for (const r of evidence.bsi.equivalenceTable.rows) {
    const pred = log2L(r.factoring, evidence.nist_formula.constants.c) - anchor;
    const d = Math.abs(pred - r.log2R);
    worst = Math.max(worst, d);
    if (d < 1) within1++;
    ok(`BSI row ${r.log2R} <-> ${r.factoring} bits: anchored model gives ${pred.toFixed(1)}`, d < 2.0, pred.toFixed(2), r.log2R);
  }
  ok("five of BSI's six rows land within one bit", within1 === 5, within1, 5);
  ok("and the worst row is under two bits", worst < 2.0, worst.toFixed(2));
  // the mechanism claim: the two bodies differ by an anchor, not by a formula
  const nistAnchor = log2L(1024, evidence.nist_formula.constants.c) - 80;
  ok("NIST's anchor offset is about 6.77 bits", near(nistAnchor, 6.77, 0.01), nistAnchor.toFixed(3));
  ok("BSI's anchor offset is about 13.93 bits", near(anchor, 13.93, 0.01), anchor.toFixed(3));
  ok("the two anchors differ by about 7.16 bits", near(anchor - nistAnchor, 7.16, 0.01), (anchor - nistAnchor).toFixed(3));
}

// B7. The three generic costs the page tabulates.
ok("exhausting a 128-bit key expects 2^127", log2Exhaustive(128) === 127);
ok("a 256-bit digest's birthday bound is just over 2^128", near(log2Birthday(256), 128.33, 0.01), log2Birthday(256).toFixed(3));
ok("Pollard rho on a 256-bit order is just under 2^128", near(log2PollardRho(256), 127.83, 0.01), log2PollardRho(256).toFixed(3));
ok("the birthday bound exceeds rho by exactly the constant ratio",
  near(log2Birthday(256) - log2PollardRho(256), 0.5, 1e-12));

// B8. The empirical ladder's arithmetic.
{
  const L = evidence.empirical.workLadder, B = L.bitcoinEver.log2;
  ok("128-bit security is about 3.4 billion times all Bitcoin hashing ever",
    near(Math.pow(2, 128 - B) / 1e9, 3.44, 0.02), (Math.pow(2, 128 - B) / 1e9).toFixed(3));
  ok("the best published MD5 preimage is over 10^8 times all Bitcoin hashing ever",
    Math.pow(2, L.md5preimage.log2 - B) > 1e8);
  ok("the RC5-72 percentage matches its stated key count",
    near(776178588780001755136 / Math.pow(2, 72) * 100, L.rc572.percentComplete, 0.001),
    (776178588780001755136 / Math.pow(2, 72) * 100).toFixed(5), L.rc572.percentComplete);
  ok("and that key count is 2^69.4", near(Math.log2(776178588780001755136), L.rc572.log2, 0.05));
}

// B9. The spread across authorities, and the record-to-recommendation gap.
{
  const { F } = build();
  ok("the 128-bit spread runs 3,000 to 5,888 bits", F["x.128.min"] === "3,000" && F["x.128.max"] === "5,888");
  ok("the record is 829 bits", evidence.empirical.rsa250.bits === 829);
  ok("record to the 2048-bit floor is about 37.8 bits of work",
    near(log2WorkRatio(2048, 829), 37.8, 0.05), log2WorkRatio(2048, 829).toFixed(2));
  ok("record to 15360 bits is about 190 bits of work",
    near(log2WorkRatio(15360, 829), 190.3, 0.05), log2WorkRatio(15360, 829).toFixed(2));
}

/* =====================================================================
   C. THE SEARCHES: re-run the experiment, do not trust the file.
   ===================================================================== */
head("C. THE SEARCHES: the instrument's own claim, re-run");

{
  // The committed measurement must be internally consistent.
  for (const r of measured.preimage) {
    ok(`measured.json preimage n=${r.n} is labelled with its own width`, r.n >= 8 && r.n <= 32);
    ok(`measured.json preimage n=${r.n} predicted mean is 2^n`, r.predictedMean === Math.pow(2, r.n));
    ok(`measured.json preimage n=${r.n} observed mean is within 5% of theory`,
      Math.abs(1 - r.meanOverPredicted) < 0.05, r.meanOverPredicted.toFixed(4));
  }
  for (const r of measured.collision) {
    ok(`measured.json collision n=${r.n} predicted mean is sqrt(pi/2)*2^(n/2)`,
      near(r.predictedMean, expectedCollisionTrials(r.n), 1e-9));
    ok(`measured.json collision n=${r.n} observed mean is within 6% of theory`,
      Math.abs(1 - r.meanOverPredicted) < 0.06, r.meanOverPredicted.toFixed(4));
  }
  // And a fresh run, here, now: the searches are deterministic given their seeds.
  const target = sha256(new TextEncoder().encode("aw-target-12-0"));
  const r = findPreimageOfPrefix(target, 12, { prefix: "aw-p12-0-", budget: 1 << 22 });
  ok("a fresh preimage search finds a message whose digest shares the target's first 12 bits",
    r.found && prefixBits(sha256(new TextEncoder().encode(r.message)), 12) === prefixBits(target, 12));
  ok("and it reports every evaluation it spent, not just the successful one", r.evaluations >= 1);
  const c = findCollisionOfPrefix(16, { prefix: "aw-c16-0-", budget: 1 << 22 });
  ok("a fresh collision search returns two DISTINCT messages agreeing on 16 bits",
    c.found && c.a !== c.b
    && prefixBits(sha256(new TextEncoder().encode(c.a)), 16) === prefixBits(sha256(new TextEncoder().encode(c.b)), 16));
  ok("the collision cost far less than the preimage bound at the same width",
    c.evaluations < expectedPreimageTrials(16) / 10, c.evaluations, `< ${expectedPreimageTrials(16) / 10}`);
}

/* =====================================================================
   D. THE PAGE: every printed figure, against the register.
   ===================================================================== */
head("D. THE PAGE: marked figures against the computed register");

const FIG_RE = /<span class="fig" data-fig="([^"]+)"\s*>([\s\S]*?)<\/span>/g;
function auditPage(html, F) {
  const bad = [], seen = new Set();
  let m;
  const re = new RegExp(FIG_RE.source, "g");
  while ((m = re.exec(html))) {
    const [, key, body] = m;
    seen.add(key);
    if (!(key in F)) bad.push({ key, body, why: "no register entry" });
    else if (body !== String(F[key])) bad.push({ key, body, why: `register says ${F[key]}` });
  }
  const unused = Object.keys(F).filter((k) => !seen.has(k));
  return { bad, unused, count: seen.size };
}

{
  const { F } = build();
  const html = src(`${PAGE_DIR}/index.html`);
  const a = auditPage(html, F);
  for (const b of a.bad) lines.push(`       ! ${b.key}: page has "${b.body}", ${b.why}`);
  ok(`every one of the ${a.count} marked figures on the page matches the register`, a.bad.length === 0, a.bad.length, 0);
  ok("and the page uses every entry the register builds", a.unused.length === 0, a.unused.join(","), "none");
  ok("the page marks a substantial number of figures", a.count >= 50, a.count, ">= 50");

  // D2. NEGATIVE CONTROL. The audit must be able to go red. Mutate one digit of
  // one figure in a copy of the shipped HTML and require exactly one failure.
  // Without this the check above is indistinguishable from a check that passes
  // because it never looks.
  const firstKey = Object.keys(F).find((k) => /\d/.test(String(F[k])));
  const orig = `data-fig="${firstKey}">${F[firstKey]}<`;
  const broken = html.replace(orig, `data-fig="${firstKey}">${String(F[firstKey]).replace(/\d/, (d) => (d === "9" ? "8" : String(Number(d) + 1)))}<`);
  ok("the mutation control actually changed the HTML", broken !== html);
  const b = auditPage(broken, F);
  ok("a single mutated digit produces exactly one audit failure", b.bad.length === 1, b.bad.length, 1);

  // D3. The two hand-typed tables in page.js must equal evidence.json.
  const pjs = src(`${PAGE_DIR}/page.js`);
  const grab = (name) => {
    const i = pjs.indexOf(`/* AW-DATA-BEGIN ${name} */`);
    const j = pjs.indexOf("/* AW-DATA-END */", i);
    return pjs.slice(i, j);
  };
  const authBlock = grab("authorities128");
  const expected128 = [3000, 3072, 3072, 3072, 3072, 3200, 3248, 3253, 4440, 5888];
  const gotAuth = [...authBlock.matchAll(/bits:\s*(\d+)/g)].map((m2) => Number(m2[1])).sort((x, y) => x - y);
  ok("page.js's authority table matches the sourced values",
    JSON.stringify(gotAuth) === JSON.stringify(expected128), gotAuth.join(","), expected128.join(","));
  const ecrypt128 = evidence.ecrypt.comparisonTable.rows.map((r) => r.at128);
  ok("and each ECRYPT comparison row in evidence.json appears in it",
    ecrypt128.every((v) => gotAuth.includes(v)), ecrypt128.join(","), gotAuth.join(","));

  const bsiBlock = grab("bsiTable");
  const gotBsi = [...bsiBlock.matchAll(/level:\s*(\d+),\s*modulus:\s*(\d+)/g)].map((m2) => [Number(m2[1]), Number(m2[2])]);
  const wantBsi = evidence.bsi.equivalenceTable.rows.map((r) => [r.log2R, r.factoring]);
  ok("page.js's BSI table is exactly BSI's published Table 2.3",
    JSON.stringify(gotBsi) === JSON.stringify(wantBsi), JSON.stringify(gotBsi), JSON.stringify(wantBsi));

  // D4. The page must not have quietly dropped its instruments or its refusals.
  for (const [needle, label] of [
    ["id=\"asym\"", "instrument I is present"],
    ["id=\"fan\"", "instrument II is present"],
    ["id=\"curve\"", "instrument III is present"],
    ["What this page does not claim", "the refusal block is present"],
    ["not a security problem", "the page still says the knife edge is not a security problem"],
    ["our arithmetic", "the page still marks the constant identification as ours, not NIST's"],
  ]) ok(label, html.includes(needle));

  // D5. Every source quoted on the page must be in evidence.json.
  const ev = src("research/the-price-of-going-backward/evidence.json");
  for (const s of ["SP 800-57", "SP 800-56B", "TR-02102-1", "ANSSI", "ECRYPT", "Lenstra"])
    ok(`the page's citation of ${s} is backed by evidence.json`, html.includes(s) && ev.includes(s));
}

/* =====================================================================
   selftest: prove the parent-coupling check can fail too.
   ===================================================================== */
if (process.argv.includes("--selftest")) {
  head("SELFTEST: the parent check, deliberately broken");
  const engine = src(`${PAGE_DIR}/engine.js`);
  const parent = src("public/strata/hash-function/index.html");
  const start = parent.indexOf("    var K = new Uint32Array([");
  const end = parent.indexOf("    var enc = new TextEncoder();");
  const block = parent.slice(start, end);
  const b0 = engine.indexOf("/* ---- AW-LIFTED-BEGIN");
  const b1 = engine.indexOf("/* ---- AW-LIFTED-END ---- */");
  const lifted = engine.slice(engine.indexOf("\n", b0) + 1, b1);
  const tampered = lifted.replace("0x428a2f98", "0x428a2f99");
  ok("a one-character change to the lifted SHA-256 breaks the byte-identity check",
    tampered !== block);
}

/* ===================================================================== */
console.log(lines.join("\n"));
console.log("");
console.log(FAIL === 0 ? `PASS ${PASS}/${PASS + FAIL}` : `FAIL ${FAIL} of ${PASS + FAIL}`);
process.exit(FAIL === 0 ? 0 : 1);
