// research/diffie-hellman/verify.mjs
// The math behind the immersive page "The Secret You Can Say Out Loud"
// (/strata/the-secret-you-can-say-out-loud/). Exact integer arithmetic with
// BigInt — no crypto library, nothing approximated.
//
// What it proves, all exactly:
//   1. The canonical textbook Diffie-Hellman example reproduces digit-for-digit
//      (p=23, g=5, a=4, b=3;  A=4, B=10, shared secret = 18).
//   2. The handshake identity holds ALWAYS: for thousands of random public
//      parameters (p prime, g a primitive root) and random private a, b, the
//      two parties land on the SAME number by different paths —
//        B^a  ≡  A^b  ≡  g^(ab)   (mod p).
//   3. The eavesdropper's problem is a real discrete logarithm, and it IS
//      solvable for toy p: baby-step giant-step recovers the secret exponent
//      exactly (matches the true a) in ~sqrt(p) work — its step count grows
//      like sqrt(p), the honest "wall" the page draws.
//   4. Diffie-Hellman gives secrecy but NOT authentication: an active
//      man-in-the-middle (Mallory) makes Alice and Bob end up with two
//      DIFFERENT secrets, each shared with Mallory, who holds both and relays.
//      No number is wrong; the protocol simply cannot tell you WHO is on the
//      other end. This is the load-bearing honesty of the page.
//   5. The from-scratch modpow matches an independent square-free reference.
//
//   node research/diffie-hellman/verify.mjs
'use strict';

// ---------- exact integer primitives (identical in spirit to the page's) ----------
function modpow(base, exp, mod) {
  base %= mod; if (base < 0n) base += mod;
  let r = 1n;
  while (exp > 0n) { if (exp & 1n) r = (r * base) % mod; base = (base * base) % mod; exp >>= 1n; }
  return r;
}
function modInverse(a, m) {
  let [oldR, r] = [((a % m) + m) % m, m];
  let [oldS, s] = [1n, 0n];
  while (r !== 0n) { const q = oldR / r; [oldR, r] = [r, oldR - q * r]; [oldS, s] = [s, oldS - q * s]; }
  if (oldR !== 1n) return null;
  return ((oldS % m) + m) % m;
}
const MR_BASES = [2n, 3n, 5n, 7n, 11n, 13n, 17n, 19n, 23n, 29n, 31n, 37n];
function isPrime(n) {
  if (n < 2n) return false;
  for (const p of MR_BASES) { if (n % p === 0n) return n === p; }
  let d = n - 1n, r = 0n; while ((d & 1n) === 0n) { d >>= 1n; r++; }
  for (const a of MR_BASES) {
    if (a % n === 0n) continue;
    let x = modpow(a, d, n); if (x === 1n || x === n - 1n) continue;
    let ok = false;
    for (let i = 0n; i < r - 1n; i++) { x = (x * x) % n; if (x === n - 1n) { ok = true; break; } }
    if (!ok) return false;
  }
  return true;
}
// distinct prime factors of n (trial division; n = p-1 is small here)
function primeFactors(n) {
  const fs = new Set(); let m = n;
  for (let d = 2n; d * d <= m; d++) { while (m % d === 0n) { fs.add(d); m /= d; } }
  if (m > 1n) fs.add(m);
  return [...fs];
}
// smallest primitive root mod prime p: g whose order is exactly p-1
function primitiveRoot(p) {
  const phi = p - 1n;
  const qs = primeFactors(phi);
  for (let g = 2n; g < p; g++) {
    if (qs.every(q => modpow(g, phi / q, p) !== 1n)) return g;
  }
  return null;
}

// ---------- the eavesdropper's algorithm: baby-step giant-step ----------
// Given g (order n), target h = g^x mod p, recover x in [0,n) in ~2*sqrt(n) work.
// Returns {x, steps}. This is the classic Shanks method — sqrt-time, sqrt-space.
function babyStepGiantStep(g, h, p, n) {
  let steps = 0;
  const m = BigInt(Math.ceil(Math.sqrt(Number(n))));
  // baby steps: table of g^j -> j for j in [0,m)
  const table = new Map();
  let e = 1n;
  for (let j = 0n; j < m; j++) { table.set(e.toString(), j); e = (e * g) % p; steps++; }
  // factor = g^(-m)
  const factor = modpow(modInverse(g, p), m, p);
  let gamma = h % p;
  for (let i = 0n; i < m; i++) {
    steps++;
    if (table.has(gamma.toString())) { return { x: i * m + table.get(gamma.toString()), steps }; }
    gamma = (gamma * factor) % p;
  }
  return { x: null, steps };
}

// ---------------------------- test harness ----------------------------
let fails = 0;
function ok(name, cond, detail) {
  const mark = cond ? 'PASS' : 'FAIL';
  if (!cond) fails++;
  console.log(`  [${mark}] ${name}${detail ? '  — ' + detail : ''}`);
}
function mulberry32(a) {
  return function () { a |= 0; a = (a + 0x6D2B79F5) | 0; let t = Math.imul(a ^ (a >>> 15), 1 | a);
    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; return ((t ^ (t >>> 14)) >>> 0) / 4294967296; };
}

console.log('Diffie-Hellman key exchange — exact verification\n');

// ---- 1. canonical textbook example -------------------------------------------
{
  const p = 23n, g = 5n, a = 4n, b = 3n;
  const A = modpow(g, a, p);            // Alice sends
  const B = modpow(g, b, p);            // Bob sends
  const sAlice = modpow(B, a, p);       // Alice computes B^a
  const sBob   = modpow(A, b, p);       // Bob   computes A^b
  ok('canonical example: A = g^a mod p = 4', A === 4n, `A=${A}`);
  ok('canonical example: B = g^b mod p = 10', B === 10n, `B=${B}`);
  ok('canonical example: shared secret = 18, both sides agree',
     sAlice === 18n && sBob === 18n, `B^a=${sAlice}, A^b=${sBob}`);
  ok('canonical example: 5 is a primitive root mod 23', primitiveRoot(23n) === 5n,
     `smallest primitive root = ${primitiveRoot(23n)}`);
}

// ---- 2. the handshake identity holds for random parameters --------------------
{
  const rnd = mulberry32(12345);
  // a pool of primes to draw from (each with a known primitive root)
  const primes = [];
  let cand = 1009n;
  while (primes.length < 40) { if (isPrime(cand)) primes.push(cand); cand += 2n; }
  let agree = 0, T = 0, allThreeEqual = 0;
  for (let k = 0; k < 4000; k++) {
    const p = primes[Math.floor(rnd() * primes.length)];
    const g = primitiveRoot(p);
    const a = 1n + BigInt(Math.floor(rnd() * Number(p - 2n)));
    const b = 1n + BigInt(Math.floor(rnd() * Number(p - 2n)));
    const A = modpow(g, a, p), B = modpow(g, b, p);
    const sAlice = modpow(B, a, p);
    const sBob   = modpow(A, b, p);
    const direct = modpow(g, a * b, p);   // g^(ab) computed straight
    T++;
    if (sAlice === sBob) agree++;
    if (sAlice === sBob && sBob === direct) allThreeEqual++;
  }
  ok('handshake: Alice and Bob agree (B^a == A^b) every time', agree === T, `${agree}/${T}`);
  ok('handshake: B^a == A^b == g^(ab) every time', allThreeEqual === T, `${allThreeEqual}/${T}`);
}

// ---- 3. the eavesdropper's discrete log — solvable for toy p, sqrt-time -------
{
  const rnd = mulberry32(999);
  const primes = [];
  let cand = 5003n;
  while (primes.length < 25) { if (isPrime(cand)) primes.push(cand); cand += 2n; }
  let recovered = 0, T = 0;
  for (let k = 0; k < 400; k++) {
    const p = primes[Math.floor(rnd() * primes.length)];
    const g = primitiveRoot(p);
    const a = 1n + BigInt(Math.floor(rnd() * Number(p - 2n)));   // Alice's true secret
    const A = modpow(g, a, p);                                   // what Eve sees
    const { x } = babyStepGiantStep(g, A, p, p - 1n);            // Eve solves discrete log
    T++;
    // g is a primitive root so the secret is unique in [0,p-1); Eve gets it exactly
    if (x !== null && x === a && modpow(g, x, p) === A) recovered++;
  }
  ok('eavesdropper: baby-step giant-step recovers the secret exponent exactly',
     recovered === T, `${recovered}/${T} toy exchanges broken`);

  // step count scales like sqrt(p) — the honest wall the page draws
  console.log('  ·   the wall — BSGS step count grows like √p (best simple attack):');
  for (const bits of [16, 24, 32, 40]) {
    // nearest prime near 2^bits
    let p = (1n << BigInt(bits)) | 1n;
    while (!isPrime(p)) p += 2n;
    const g = 2n;                          // g need not be primitive to count steps
    const a = 123456789n % (p - 2n) + 1n;
    const A = modpow(g, a, p);
    const { steps } = babyStepGiantStep(g, A, p, p - 1n);
    const sqrtP = Math.sqrt(Number(p));
    console.log(`        p≈2^${bits}  →  BSGS used ${steps} steps   (√p ≈ ${Math.round(sqrtP)})`);
  }
}

// ---- 4. Diffie-Hellman does NOT authenticate: the man in the middle -----------
{
  const rnd = mulberry32(7);
  let split = 0, mallorySeesBoth = 0, aliceFooled = 0, T = 0;
  const primes = [];
  let cand = 2003n;
  while (primes.length < 20) { if (isPrime(cand)) primes.push(cand); cand += 2n; }
  for (let k = 0; k < 2000; k++) {
    const p = primes[Math.floor(rnd() * primes.length)];
    const g = primitiveRoot(p);
    const a = 1n + BigInt(Math.floor(rnd() * Number(p - 2n)));   // Alice secret
    const b = 1n + BigInt(Math.floor(rnd() * Number(p - 2n)));   // Bob secret
    const m = 1n + BigInt(Math.floor(rnd() * Number(p - 2n)));   // Mallory secret

    const A = modpow(g, a, p);   // Alice -> (Mallory intercepts)
    const B = modpow(g, b, p);   // Bob   -> (Mallory intercepts)
    const M = modpow(g, m, p);   // Mallory's forged public value, sent to BOTH

    // What each honest party actually computes (they received M, believing it the peer's):
    const aliceKey = modpow(M, a, p);   // Alice: (peer)^a  where peer is really Mallory
    const bobKey   = modpow(M, b, p);   // Bob:   (peer)^b
    // What Mallory computes for each side:
    const malloryWithAlice = modpow(A, m, p);   // = g^(a m) = aliceKey
    const malloryWithBob   = modpow(B, m, p);   // = g^(b m) = bobKey
    // The secret Alice and Bob WOULD have shared with no attacker:
    const intendedAB = modpow(g, a * b, p);

    T++;
    if (aliceKey !== bobKey) split++;                              // two different secrets
    if (malloryWithAlice === aliceKey && malloryWithBob === bobKey) mallorySeesBoth++;
    if (aliceKey !== intendedAB) aliceFooled++;                    // Alice's key is not the real A-B key
  }
  // Note: split/aliceFooled hold "almost always" (they can coincide by chance for
  // tiny p); the load-bearing claim is that Mallory holds BOTH keys, always.
  ok('MITM: Mallory computes BOTH parties\' keys, every time', mallorySeesBoth === T, `${mallorySeesBoth}/${T}`);
  ok('MITM: Alice and Bob end with DIFFERENT secrets (each shared with Mallory)',
     split >= T * 0.98, `${split}/${T}`);
  ok('MITM: the key Alice computes is NOT the real Alice-Bob key',
     aliceFooled >= T * 0.98, `${aliceFooled}/${T}`);
}

// ---- 5. from-scratch modpow matches an independent reference ------------------
{
  const rnd = mulberry32(4242);
  let match = 0, T = 0;
  for (let k = 0; k < 3000; k++) {
    const p = 1n + BigInt(Math.floor(rnd() * 100000)) * 2n + 1n;
    const base = BigInt(Math.floor(rnd() * 1e9));
    const exp = BigInt(Math.floor(rnd() * 1e6));
    // independent reference: repeated multiplication for small exp, else BigInt **
    let ref;
    if (exp < 200n) { ref = 1n; for (let i = 0n; i < exp; i++) ref = (ref * (base % p)) % p; }
    else ref = (base ** 1n) % p === (base % p) ? modpowRef(base, exp, p) : null;
    const got = modpow(base, exp, p);
    T++;
    if (ref === null || got === ref) match++;
  }
  ok('modpow matches an independent reference on random inputs', match === T, `${match}/${T}`);
}
function modpowRef(base, exp, mod) {
  // deliberately different loop order (MSB-first) than modpow's LSB-first
  base %= mod; const bits = exp.toString(2); let r = 1n;
  for (const c of bits) { r = (r * r) % mod; if (c === '1') r = (r * base) % mod; }
  return r;
}

console.log(fails ? `\n${fails} CHECK(S) FAILED` : '\nAll checks passed.');
process.exit(fails ? 1 : 0);
