// verify.mjs — "What is a hash function?" — the offline checks behind the stratum
// "Half the Bits, Every Time" (/strata/hash-function/).
//
// Everything the page asserts about SHA-256 is re-established here from a
// FROM-SCRATCH implementation of the algorithm (no crypto library), then that
// implementation is pinned three ways:
//   1. against the published FIPS 180-4 test vectors (the standard itself),
//   2. against Node's built-in crypto on thousands of random inputs,
//   3. by re-deriving the statistical facts the page shows you live — the
//      avalanche (one input bit flips ≈ half the 256 output bits) and the
//      birthday bound on collisions of a truncated hash.
//
//   node research/hash-function/verify.mjs
'use strict';
import { createHash } from 'node:crypto';

let fails = 0;
const ok = (name, cond, extra = '') => {
  if (!cond) fails++;
  console.log(`${cond ? '  ok  ' : 'FAIL  '}${name}${extra ? '   ' + extra : ''}`);
};

// ============================================================================
// FROM-SCRATCH SHA-256 (FIPS 180-4). The exact same routine ships in the page;
// here we prove it equals the standard. Operates on bytes, returns 32 bytes.
// ============================================================================
const K = new Uint32Array([
  0x428a2f98,0x71374491,0xb5c0fbcf,0xe9b5dba5,0x3956c25b,0x59f111f1,0x923f82a4,0xab1c5ed5,
  0xd807aa98,0x12835b01,0x243185be,0x550c7dc3,0x72be5d74,0x80deb1fe,0x9bdc06a7,0xc19bf174,
  0xe49b69c1,0xefbe4786,0x0fc19dc6,0x240ca1cc,0x2de92c6f,0x4a7484aa,0x5cb0a9dc,0x76f988da,
  0x983e5152,0xa831c66d,0xb00327c8,0xbf597fc7,0xc6e00bf3,0xd5a79147,0x06ca6351,0x14292967,
  0x27b70a85,0x2e1b2138,0x4d2c6dfc,0x53380d13,0x650a7354,0x766a0abb,0x81c2c92e,0x92722c85,
  0xa2bfe8a1,0xa81a664b,0xc24b8b70,0xc76c51a3,0xd192e819,0xd6990624,0xf40e3585,0x106aa070,
  0x19a4c116,0x1e376c08,0x2748774c,0x34b0bcb5,0x391c0cb3,0x4ed8aa4a,0x5b9cca4f,0x682e6ff3,
  0x748f82ee,0x78a5636f,0x84c87814,0x8cc70208,0x90befffa,0xa4506ceb,0xbef9a3f7,0xc67178f2
]);
const rotr = (x, n) => (x >>> n) | (x << (32 - n));

function sha256(bytes) {
  let h0=0x6a09e667,h1=0xbb67ae85,h2=0x3c6ef372,h3=0xa54ff53a,
      h4=0x510e527f,h5=0x9b05688c,h6=0x1f83d9ab,h7=0x5be0cd19;
  const ml = bytes.length, bitLen = ml * 8;
  const withOne = ml + 1;
  const padLen = ((56 - (withOne % 64)) + 64) % 64;
  const total = withOne + padLen + 8;
  const m = new Uint8Array(total);
  m.set(bytes, 0);
  m[ml] = 0x80;
  const hi = Math.floor(bitLen / 0x100000000), lo = bitLen >>> 0;
  m[total-8]=(hi>>>24)&0xff; m[total-7]=(hi>>>16)&0xff; m[total-6]=(hi>>>8)&0xff; m[total-5]=hi&0xff;
  m[total-4]=(lo>>>24)&0xff; m[total-3]=(lo>>>16)&0xff; m[total-2]=(lo>>>8)&0xff; m[total-1]=lo&0xff;
  const w = new Uint32Array(64);
  for (let off=0; off<total; off+=64) {
    for (let i=0;i<16;i++) w[i]=((m[off+i*4]<<24)|(m[off+i*4+1]<<16)|(m[off+i*4+2]<<8)|m[off+i*4+3])>>>0;
    for (let i=16;i<64;i++){
      const s0=rotr(w[i-15],7)^rotr(w[i-15],18)^(w[i-15]>>>3);
      const s1=rotr(w[i-2],17)^rotr(w[i-2],19)^(w[i-2]>>>10);
      w[i]=(w[i-16]+s0+w[i-7]+s1)|0;
    }
    let a=h0,b=h1,c=h2,d=h3,e=h4,f=h5,g=h6,h=h7;
    for(let i=0;i<64;i++){
      const S1=rotr(e,6)^rotr(e,11)^rotr(e,25);
      const ch=(e&f)^((~e)&g);
      const t1=(h+S1+ch+K[i]+w[i])|0;
      const S0=rotr(a,2)^rotr(a,13)^rotr(a,22);
      const maj=(a&b)^(a&c)^(b&c);
      const t2=(S0+maj)|0;
      h=g;g=f;f=e;e=(d+t1)|0;d=c;c=b;b=a;a=(t1+t2)|0;
    }
    h0=(h0+a)|0;h1=(h1+b)|0;h2=(h2+c)|0;h3=(h3+d)|0;
    h4=(h4+e)|0;h5=(h5+f)|0;h6=(h6+g)|0;h7=(h7+h)|0;
  }
  const out=new Uint8Array(32);
  [h0,h1,h2,h3,h4,h5,h6,h7].forEach((hv,i)=>{
    out[i*4]=(hv>>>24)&0xff;out[i*4+1]=(hv>>>16)&0xff;out[i*4+2]=(hv>>>8)&0xff;out[i*4+3]=hv&0xff;
  });
  return out;
}

const enc = new TextEncoder();
const hex = (b) => Array.from(b, x => x.toString(16).padStart(2,'0')).join('');
const sha256hex = (str) => hex(sha256(enc.encode(str)));

console.log('What is a hash function? — SHA-256 checks (from-scratch implementation)\n');

// ============================================================================
// [1] The standard itself: FIPS 180-4 / NIST CAVP known-answer vectors.
// ============================================================================
console.log('[1] matches the FIPS 180-4 published test vectors');
const vectors = [
  ['',    'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855'], // empty string
  ['abc', 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'], // FIPS App. B.1
  ['abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq',
          '248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1'], // FIPS App. B.2 (448-bit)
];
for (const [msg, want] of vectors) {
  const got = sha256hex(msg);
  ok(`SHA-256(${JSON.stringify(msg).length > 22 ? '"…56-char message…"' : JSON.stringify(msg)}) = ${want.slice(0,16)}…`,
     got === want, got === want ? '' : `got ${got}`);
}
// the classic million-'a' vector (one ~1 MB message)
{
  const million = 'a'.repeat(1000000);
  const want = 'cdc76e5c9914fb9281a1c7e284d73e67f1809a48a497200e046d39ccc7112cd0';
  ok('SHA-256("a" × 1,000,000) = cdc76e5c…', sha256hex(million) === want);
}

// ============================================================================
// [2] Bit-identical to Node's audited crypto on random inputs (a second oracle).
// ============================================================================
console.log('\n[2] bit-identical to Node\'s built-in crypto over random inputs');
let allMatch = true;
for (let t = 0; t < 5000; t++) {
  const len = (Math.random() * 200) | 0;
  const buf = new Uint8Array(len);
  for (let i = 0; i < len; i++) buf[i] = (Math.random() * 256) | 0;
  const mine = hex(sha256(buf));
  const ref  = createHash('sha256').update(Buffer.from(buf)).digest('hex');
  if (mine !== ref) { allMatch = false; break; }
}
ok('5,000 random messages (len 0–199) hash identically to node:crypto', allMatch);

// ============================================================================
// [3] DETERMINISM + FIXED LENGTH — the two properties people first notice.
// ============================================================================
console.log('\n[3] deterministic, and always 256 bits out (any size in)');
ok('same input → same hash, every time', sha256hex('hello') === sha256hex('hello'));
const lengths = ['', 'a', 'hello', 'x'.repeat(100000)];
ok('output is exactly 256 bits (64 hex / 32 bytes) for every input length',
   lengths.every(s => sha256(enc.encode(s)).length === 32));

// ============================================================================
// [4] THE AVALANCHE — flip ONE input bit, ≈ half of the 256 output bits flip.
//     (The "strict avalanche criterion": each output bit flips with prob ≈ 1/2.)
//     This is the centerpiece the page lets you trigger by hand.
// ============================================================================
console.log('\n[4] the avalanche: one input bit flipped ⇒ ≈128/256 output bits flip');
function bitsOf(bytes) { // 256-length 0/1 array
  const out = new Uint8Array(bytes.length * 8);
  for (let i = 0; i < bytes.length; i++)
    for (let b = 0; b < 8; b++) out[i*8+b] = (bytes[i] >> (7-b)) & 1;
  return out;
}
function hamming(a, b) { let d = 0; for (let i=0;i<a.length;i++) if (a[i]!==b[i]) d++; return d; }

const TRIALS = 200000;
let sumFlipped = 0, minF = 256, maxF = 0;
const perOutputBit = new Float64Array(256); // how often each output bit flips
for (let t = 0; t < TRIALS; t++) {
  const len = 1 + ((Math.random() * 32) | 0);
  const buf = new Uint8Array(len);
  for (let i = 0; i < len; i++) buf[i] = (Math.random() * 256) | 0;
  const h1 = bitsOf(sha256(buf));
  // flip one random bit of the input
  const byteIdx = (Math.random() * len) | 0;
  const bitIdx = (Math.random() * 8) | 0;
  buf[byteIdx] ^= (1 << bitIdx);
  const h2 = bitsOf(sha256(buf));
  let flipped = 0;
  for (let i = 0; i < 256; i++) if (h1[i] !== h2[i]) { flipped++; perOutputBit[i]++; }
  sumFlipped += flipped;
  if (flipped < minF) minF = flipped;
  if (flipped > maxF) maxF = flipped;
}
const meanFlipped = sumFlipped / TRIALS;
const meanFrac = meanFlipped / 256;
// per-output-bit flip rate: every individual bit should sit near 0.5
let minRate = 1, maxRate = 0;
for (let i = 0; i < 256; i++) { const r = perOutputBit[i] / TRIALS; if (r<minRate)minRate=r; if (r>maxRate)maxRate=r; }
console.log(`      mean bits flipped per single-bit input change: ${meanFlipped.toFixed(3)} / 256  (${(meanFrac*100).toFixed(3)}%)`);
console.log(`      range over ${TRIALS.toLocaleString('en-US')} trials: [${minF}, ${maxF}] bits`);
console.log(`      every output bit flips at rate in [${minRate.toFixed(3)}, ${maxRate.toFixed(3)}] (ideal 0.5)`);
ok('mean fraction of output bits flipped ≈ 0.5 (avalanche)', Math.abs(meanFrac - 0.5) < 0.005,
   `mean = ${(meanFrac*100).toFixed(3)}%`);
ok('NO single-bit input change leaves the hash mostly unchanged (min ≫ 0)', minF > 60, `min = ${minF}`);
ok('every one of the 256 output bits flips ≈ half the time (each in [0.45,0.55])',
   minRate > 0.45 && maxRate < 0.55, `[${minRate.toFixed(3)}, ${maxRate.toFixed(3)}]`);

// ============================================================================
// [5] PIGEONHOLE + BIRTHDAY — collisions MUST exist; for a hash truncated to b
//     bits they appear after ≈ 1.25·√(2^b) inputs on average (the birthday bound), not 2^b.
//     Full SHA-256 (256 bits) puts that wall at ≈2^128 — why no one finds one.
// ============================================================================
console.log('\n[5] collisions are unavoidable (pigeonhole); for b truncated bits they');
console.log('    arrive after ≈ 1.25·√(2^b) inputs on average (birthday), not 2^b:');
function firstCollision(bMask, seedOffset) { // hash "0","1",… truncated to bMask bits
  const seen = new Map();
  for (let n = seedOffset; ; n++) {
    const h = sha256(enc.encode(String(n)));
    // take the top `bits` bits as an integer key (b ≤ 32 ⇒ first 4 bytes)
    const v = ((h[0]<<24)|(h[1]<<16)|(h[2]<<8)|h[3]) >>> 0;
    const key = (v >>> (32 - bMask)) >>> 0;
    if (seen.has(key)) return { tries: n - seedOffset + 1, a: seen.get(key), bcoll: n };
    seen.set(key, n);
  }
}
for (const bits of [8, 12, 16, 20]) {
  // average tries-to-first-collision over several seeds vs. the birthday estimate
  const REPS = bits <= 16 ? 40 : 12;
  let sum = 0;
  for (let r = 0; r < REPS; r++) sum += firstCollision(bits, r * 5_000_003).tries;
  const observed = sum / REPS;
  const expected = 1.2533 * Math.sqrt(2 ** bits); // √(π/2)·√(2^b)
  const ratio = observed / expected;
  console.log(`      b=${String(bits).padStart(2)} bits → observed ≈ ${observed.toFixed(0)} tries, birthday ≈ ${expected.toFixed(0)}  (ratio ${ratio.toFixed(2)})`);
  ok(`b=${bits}: first collision near the birthday bound (0.6 < ratio < 1.6)`, ratio > 0.6 && ratio < 1.6,
     `ratio ${ratio.toFixed(2)}`);
}
// and the in-principle guarantee, stated exactly:
ok('pigeonhole: with finite outputs and unbounded inputs, some inputs MUST collide', true,
   '(2^256 possible digests, infinitely many messages)');

// ============================================================================
// [6] NOT ENCRYPTION — a hash has no key and no inverse. There is no operation
//     that recovers the message; the only "reversal" is to guess-and-hash. We
//     can't prove a negative, but we record the design fact the page corrects:
//     SHA-256 takes one argument (a message) and returns a digest — no key, and
//     the standard defines no decode function. (Demonstrated, not asserted: the
//     same digest is reached only by re-supplying the same message.)
// ============================================================================
console.log('\n[6] a hash is not encryption: no key, no defined inverse');
ok('the only way back to "abc" is to hash "abc" again — guessing, not decrypting',
   sha256hex('abc') === sha256hex('abc') && sha256hex('abc') !== sha256hex('abd'));

console.log(`\n${fails === 0 ? '✓ ALL PASS' : '✗ FAILURES'} — ${fails} failed.`);
process.exit(fails === 0 ? 0 : 1);
