// ML-DSA-65 (FIPS 204) helpers for Hashfort v3: the per-key data a vault stores on chain so that each signature check // only does the work that depends on the signature. Everything here is public-key math; no secrets. // precompute(pk) -> { A, B } A = Â (k×l polynomials, NTT domain), B = tr || NTT(t1·2^d), coefficients as 3 bytes BE // The verifier contract can recompute both from the public key (checkExpansion) so anyone can audit what a vault stores. import { shake128, shake256 } from "@noble/hashes/sha3"; export const Q = 8380417, D = 13, K = 6, L = 5, N = 256; export const PK_LEN = 1952, SIG_LEN = 3309; function brv8(x) { let r = 0; for (let i = 0; i < 8; i++) r |= ((x >> i) & 1) << (7 - i); return r; } const mulq = (a, b) => Number((BigInt(a) * BigInt(b)) % BigInt(Q)); function powq(b, e) { let r = 1, x = b; while (e > 0) { if (e & 1) r = mulq(r, x); x = mulq(x, x); e >>= 1; } return r; } export const ZETAS = Array.from({ length: 256 }, (_, k) => powq(1753, brv8(k))); export function ntt(w) { w = w.slice(); let m = 0; for (let len = 128; len >= 1; len >>= 1) for (let start = 0; start < 256; start += 2 * len) { const z = ZETAS[++m]; for (let j = start; j < start + len; j++) { const t = mulq(z, w[j + len]); w[j + len] = (w[j] - t + Q) % Q; w[j] = (w[j] + t) % Q; } } return w; } function rejNttPoly(seed) { const out = []; let len = 840; while (true) { const s = shake128(seed, { dkLen: len }); out.length = 0; for (let i = 0; i + 3 <= s.length && out.length < 256; i += 3) { const v = s[i] | (s[i + 1] << 8) | ((s[i + 2] & 0x7f) << 16); if (v < Q) out.push(v); } if (out.length === 256) return out; len *= 2; } } export function expandA(rho) { const A = []; for (let r = 0; r < K; r++) for (let s = 0; s < L; s++) { const seed = new Uint8Array(34); seed.set(rho); seed[32] = s; seed[33] = r; A.push(rejNttPoly(seed)); } return A; // index r*L + s } export function t1Of(pk) { const t = []; for (let r = 0; r < K; r++) { const p = [], off = 32 + 320 * r; for (let g = 0; g < 64; g++) { let v = 0n; for (let b = 0; b < 5; b++) v |= BigInt(pk[off + 5 * g + b]) << BigInt(8 * b); for (let j = 0; j < 4; j++) p.push(Number((v >> BigInt(10 * j)) & 0x3ffn)); } t.push(p); } return t; } const pack3 = (polys) => { const out = new Uint8Array(polys.length * 256 * 3); let o = 0; for (const p of polys) for (const c of p) { out[o++] = c >> 16; out[o++] = (c >> 8) & 255; out[o++] = c & 255; } return out; }; export function precompute(pk) { if (pk.length !== PK_LEN) throw new Error("ML-DSA-65 public key must be 1952 bytes"); const A = pack3(expandA(pk.slice(0, 32))); const that = t1Of(pk).map((p) => ntt(p.map((c) => mulq(c, 1 << D)))); const tr = shake256(pk, { dkLen: 64 }); const B = new Uint8Array(64 + K * 768); B.set(tr); B.set(pack3(that), 64); return { A, B }; }