From 883daa32099f1a2871e96f026f11efe00ed6541f Mon Sep 17 00:00:00 2001 From: Chris Duncan Date: Sat, 7 Nov 2026 20:15:55 -0800 Subject: [PATCH] Add more tests and update agent file. --- AGENTS.md | 51 ++++++-- test/arithmetic.mjs | 201 +++++++++++++++++++++++++++- test/node.mjs | 310 ++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 546 insertions(+), 16 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 28e0e1d..64398b7 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -641,8 +641,8 @@ show up on the clock; only the point arithmetic does. `npm test` builds, then runs seven suites: `test/node.mjs` little-endian, big-endian and under `--frozen-intrinsics`, then `test:mutants`, `test:module`, -`test:arithmetic` and `test:heap`. Current state is **6369, 6369, 6229, 17, 16, -80 and 10 passing, 0 failing**; the frozen run skips the 140 checks under +`test:arithmetic` and `test:heap`. Current state is **6403, 6403, 6263, 17, 16, +109 and 10 passing, 0 failing**; the frozen run skips the 140 checks under prototype and static patches, since frozen intrinsics cannot be patched, but keeps the 15 under global replacements. `test:heap` reports SKIP and passes nothing off Linux. There is no expected failure — if anything fails, it is a regression. `test:all` @@ -775,11 +775,15 @@ every input real callers produce** — the `fe_reduce` one was a gap. **Add a mutant whenever you add a guard or change a guarded function** — a guard nobody has seen fail is the shape of every bug in this section. -`verify_blocks` now has vector coverage — a single block, a full -`MAX_VERIFY_BLOCKS`-sized batch, both range errors, and the three block-shape `TypeError`s. Coverage still -runs thin in the middle: its bugs have twice been invisible below a boundary -(64, then 256) and appeared only past it, so exercise new changes across the -whole range rather than at one size, and always corrupt at least one signature +`verify_blocks` now has vector coverage — a single block, in an array and +outside one, a full `MAX_VERIFY_BLOCKS`-sized batch, both range errors, the +three block-shape `TypeError`s, and **every batch size from the cap down to 1**, +each with distinct hashes and two forged blocks, the last and one that moves +through the middle. The sizes run downward so that each forged block sits where +the previous, larger batch left a `true`: a module that wrote only successes, +with both `OUTPUT_VERIFY` scrubs dropped, fails there. Its bugs have twice been +invisible below a boundary (64, then 256) and appeared only past it, so keep +exercising new changes across the whole range rather than at one size, and always corrupt at least one signature in the batch — the bug this feature has actually shipped is reporting invalid signatures as valid, which an all-valid batch cannot catch. @@ -881,9 +885,22 @@ are not wasm exports and exporting them leaves the production binary unchanged. A `Uint8Array` subclass that lies through `Symbol.species`, `length`, `byteLength` and `Symbol.toStringTag`, and overrides `set`, is passed as every byte argument of every primitive and as both output buffers. Each call must -return what plain bytes return, and the subclass's code must never run. Views -over a `SharedArrayBuffer`, a bare `SharedArrayBuffer`, a `Uint16Array` and an -output buffer that lies about its `byteLength` must each be rejected. A Proxy +return what plain bytes return, and the subclass's code must never run. A Node +`Buffer` at an odd `byteOffset` inside a larger one, the form most Node callers +have, goes in every argument and both output buffers, which must leave the +bytes either side alone. Thirteen shapes that are neither hex nor +`Uint8Array` — a bare `ArrayBuffer` or `SharedArrayBuffer`, a view +over shared memory, a `DataView`, other typed arrays, arrays, array-likes, a +`String` object, a number, `null` and `undefined` — go in every byte argument +of every primitive, and every fixed-length argument is tried a byte and a hex +digit either side of its size; each must throw a `Nano25519TypeError` naming the +argument. Output buffers of the wrong shape, a view over shared memory among +them, must be refused and left unwritten, and so must one that lies about its +`byteLength`. Error classes are asserted, not just messages: input errors are +`TypeError`s, block counts `RangeError`s, and a module refusal a +`Nano25519WasmError`, which is neither. Check `err.constructor.name`, not +`err.name`: `errors.ts` names the classes, which survives minification, but +instances inherit `name` from `TypeError.prototype` and friends. A Proxy over a blocks array, which passes `Array.isArray`, reporting a length of `'1'`, `NaN` or an infinity must be refused as an invalid length, and `1.5` by the missing second block. @@ -939,7 +956,7 @@ its own code and details, and `setInputPrv` must ignore everything above each the `setInputMsg` guard moved 32 bytes late and the key halves widened to `u32`. `test:arithmetic` compiles a probe with an extra entry file, embedded in the -test, that wraps internals over buffers of its own, and compares about 95,800 +test, that wraps internals over buffers of its own, and compares about 103,500 results with `test/reference.mjs`. It covers: - **every `fe_*` operation**, the paired SIMD ones included, with its operands @@ -958,13 +975,23 @@ results with `test/reference.mjs`. It covers: checking `XY = ZT` and `[0]A + [0]B`. - **the checks `verify()` makes on the key and `R`**, at their call sites. - **degenerate points**, which both small-order predicates must refuse. +- **every operation in `p.ts` on its own**, over the identity, torsion points + and random points in random projective scalings, each result read back + through its own representation and checked as a point and as a well-formed + one, sums with `q = p`, `-p` and the identity, and every operation that can + write over its input run both ways. Then chained as the double scalar + multiplication chains them, so a doubling also takes a sum's loose limbs. Point inputs are tight signed limbs, as real callers produce: the canonical non-negative form overflows `fe_mul`'s i32 `19·g` lanes on a sum like `Y + X`, a false mismatch no caller can trigger. It is seeded, so a failure reproduces. Its controls make `p1p1_0` leave `T = 0`, recompute `T` as `X·Y`, and, in one probe, drop both canonicity checks and the malformed-point term from each of -the two small-order predicates; each of the six must be seen. +the two small-order predicates; each of the six must be seen. A seventh +reorders `dbl_to_p1p1` to square its inputs before summing them, which is +still right for every caller but `p1p1_dbl_to_p1p1`, the one that hands it its +own output's coordinates; the point-operation tests must name that function +alone. ### Beside the API: `test:heap` diff --git a/test/arithmetic.mjs b/test/arithmetic.mjs index 641f3c3..0a698d8 100644 --- a/test/arithmetic.mjs +++ b/test/arithmetic.mjs @@ -66,7 +66,7 @@ const HARNESS = ` import './env' import { FieldElement, fe, fe_0, fe_1, fe_add, fe_addsub, fe_cmov, fe_copy, fe_dbl, fe_frombytes, fe_isnegative, fe_iszero, fe_mul, fe_mul_2d, fe_mul_d, fe_mul_pair, fe_mul_pair_2d, fe_mul_pair_dbl, fe_mul_pair_dbl_2d, fe_mul_pair_sqrtm1, fe_mul_sqrtm1, fe_neg, fe_reduce, fe_sq, fe_sq_n, fe_sq_pair, fe_sq_pair_dbl, fe_sub, fe_tobytes } from './ed25519/fe' import { ge_cache_odd_multiples, ge_double_scalarmult_vartime_to_p3, ge_frombytes, ge_frombytes_negate, ge_accept_small_order, ge_reject_small_order, ge_is_canonical, ge_scalarmult_base_tobytes } from './ed25519/ge' -import { p3, p3_dbl_to_p3, p3_sub_cached_to_p3, p3_tobytes, p_cached } from './ed25519/p' +import { p1p1, p1p1_0, p1p1_dbl_to_p1p1, p1p1_to_cached, p1p1_to_p2, p1p1_to_p3, p2, p2_0, p2_dbl_to_p2, p2_dbl_to_p3, p3, p3_0, p3_add_cached, p3_add_cached_to_cached, p3_add_precomp, p3_dbl_to_p2, p3_dbl_to_p3, p3_sub_cached, p3_sub_cached_to_p3, p3_sub_precomp, p3_to_cached, p3_tobytes, p_cached, p_precomp, precomp_0 } from './ed25519/p' import { fe_invert, fe_pow22523 } from './ed25519/z' import { sc_is_canonical, sc_muladd, sc_reduce } from './ed25519/sc' import { ge_double_scalarmult_vartime_to_cached } from './ed25519/ge/double_scalarmult' @@ -78,6 +78,8 @@ const FA = F[0], FB = F[1], FH = F[2] const U8A = new StaticArray(32), U8B = new StaticArray(32), U8C = new StaticArray(32), U8D = new StaticArray(32) const U8W = new StaticArray(64) const PA = new p3(), PB = new p3(), PC = new p3(), A2 = new p3(), CB = new p_cached() +// one of each representation for the point operations, two where an operation can write over its input +const R1 = new p1p1(), R1B = new p1p1(), Q2 = new p2(), Q2B = new p2(), CA = new p_cached(), CC = new p_cached(), PP = new p_precomp() const AI: StaticArray = StaticArray.fromArray([new p_cached(), new p_cached(), new p_cached(), new p_cached(), new p_cached(), new p_cached(), new p_cached(), new p_cached()]) export function ptr (id: i32): usize { @@ -112,6 +114,31 @@ export function ptr (id: i32): usize { case 31: return changetype(PC.Y) case 32: return changetype(PC.Z) case 33: return changetype(PC.T) + case 50: return changetype(R1.X) + case 51: return changetype(R1.Y) + case 52: return changetype(R1.Z) + case 53: return changetype(R1.T) + case 60: return changetype(R1B.X) + case 61: return changetype(R1B.Y) + case 62: return changetype(R1B.Z) + case 63: return changetype(R1B.T) + case 70: return changetype(Q2.X) + case 71: return changetype(Q2.Y) + case 72: return changetype(Q2.Z) + case 80: return changetype(Q2B.X) + case 81: return changetype(Q2B.Y) + case 82: return changetype(Q2B.Z) + case 90: return changetype(CA.YplusX) + case 91: return changetype(CA.YminusX) + case 92: return changetype(CA.Z) + case 93: return changetype(CA.T2d) + case 94: return changetype(CC.YplusX) + case 95: return changetype(CC.YminusX) + case 96: return changetype(CC.Z) + case 97: return changetype(CC.T2d) + case 140: return changetype(PP.yplusx) + case 141: return changetype(PP.yminusx) + case 142: return changetype(PP.xy2d) } return 0 } @@ -165,6 +192,30 @@ export function p3_sub_cached_to_p3_ (): void { ge_double_scalarmult_vartime_to_cached(CB, U8A, AI, U8B) p3_sub_cached_to_p3(PC, PA, CB) } +// every operation in p.ts, by number; with alias set, the output is also the input it shares a representation with +export function point_op_ (op: i32, alias: i32): void { + switch (op) { + case 0: p1p1_0(R1); break + case 1: p2_0(Q2); break + case 2: p3_0(PB); break + case 3: precomp_0(PP); break + case 4: p1p1_to_p2(Q2, R1); break + case 5: p1p1_to_p3(PB, R1); break + case 6: p3_to_cached(CA, PA); break + case 7: p1p1_to_cached(CA, R1); break + case 8: if (alias) p1p1_dbl_to_p1p1(R1, R1); else p1p1_dbl_to_p1p1(R1B, R1); break + case 9: if (alias) p2_dbl_to_p2(Q2, Q2); else p2_dbl_to_p2(Q2B, Q2); break + case 10: p2_dbl_to_p3(PB, Q2); break + case 11: p3_dbl_to_p2(Q2, PA); break + case 12: if (alias) p3_dbl_to_p3(PA, PA); else p3_dbl_to_p3(PB, PA); break + case 13: p3_add_cached(R1, PA, CA); break + case 14: p3_sub_cached(R1, PA, CA); break + case 15: if (alias) p3_add_cached_to_cached(CA, PA, CA); else p3_add_cached_to_cached(CC, PA, CA); break + case 16: if (alias) p3_sub_cached_to_p3(PA, PA, CA); else p3_sub_cached_to_p3(PB, PA, CA); break + case 17: p3_add_precomp(R1, PA, PP); break + case 18: p3_sub_precomp(R1, PA, PP); break + } +} export function verify_pubkey_ (): i32 { return verify_pubkey(U8A) ? 1 : 0 } export function verify_signature_ (): i32 { return verify_signature(U8W) ? 1 : 0 } ` @@ -172,6 +223,7 @@ export function verify_signature_ (): i32 { return verify_signature(U8W) ? 1 : 0 /** Seeded controls: each `from` must occur once inside its `fn`; an optional `import` line is added to the file. */ const NO_IDENTITY = [{ file: 'src/assembly/ed25519/p.ts', fn: 'p1p1_0', from: 'fe_1(h.T)', to: 'fe_0(h.T)' }] const STALE_T = [{ file: 'src/assembly/ed25519/ge/double_scalarmult.ts', fn: 'ge_double_scalarmult_vartime_to_p3', from: 'p1p1_to_p3(r, t)', to: 'p1p1_to_p3(r, t)\n\t\t\tfe_mul(r.T, r.X, r.Y)', import: "import { fe_mul } from '../fe'" }] +const DBL_ORDER = [{ file: 'src/assembly/ed25519/p.ts', fn: 'dbl_to_p1p1', from: 'fe_add(r.X, X, Y) // X = X₁+Y₁\n\tfe_sq_pair_dbl(r.X, r.X, r.T, Z) // X = (X₁+Y₁)², T = 2Z₁²\n\tfe_sq_pair(r.Z, X, r.Y, Y) // Z = X₁², Y = Y₁²', to: 'fe_sq_pair(r.Z, X, r.Y, Y)\n\tfe_add(r.X, X, Y)\n\tfe_sq_pair_dbl(r.X, r.X, r.T, Z)' }] const NO_PRECONDITIONS = [ { file: 'src/assembly/crypto_verify.ts', fn: 'verify_pubkey', from: 'if (ge_is_canonical(pub) != 0) {', to: 'if (false) {' }, { file: 'src/assembly/crypto_verify.ts', fn: 'verify_signature', from: 'if (ge_is_canonical(sig) != 0) {', to: 'if (false) {' }, @@ -191,7 +243,8 @@ async function probe (name, edits = []) { for (const edit of edits) { const path = new URL(edit.file, dir) const source = await readFile(path, 'utf8') - const start = source.indexOf(`export function ${edit.fn} (`) + const exported = source.indexOf(`export function ${edit.fn} (`) + const start = exported < 0 ? source.indexOf(`\nfunction ${edit.fn} (`) : exported const end = source.indexOf('\n}\n', start) const body = source.slice(start, end) if (start < 0 || end < 0 || body.split(edit.from).length !== 2) { @@ -262,6 +315,8 @@ function harness (compiled) { setPoint: (base, p) => { const zi = modinv(p[2]), xa = mod(p[0] * zi), ya = mod(p[1] * zi);[xa, ya, 1n, mod(xa * ya)].forEach((c, k) => { const a = limbs(base + k); a.fill(0); a.set(tight(c)) }) }, setProjective: (base, p) => p.forEach((c, k) => { const a = limbs(base + k); a.fill(0); a.set(tight(c)) }), getPoint: (base) => [0, 1, 2, 3].map(k => mod(value(Array.from(limbs(base + k))))), + /** `n` coordinates from `base` as values, or `null` if any has dirty padding limbs. */ + getCoords: (base, n) => Array.from({ length: n }, (_, k) => limbs(base + k)).every(a => a[10] === 0 && a[11] === 0) ? Array.from({ length: n }, (_, k) => mod(value(Array.from(limbs(base + k))))) : null, /** Entry `k` of the table of odd multiples, `(Y + X, Y - X, Z, 2dT)`, as extended `(X, Y, Z, T)`. */ getCached: (k) => { const [plus, minus, Z, T2d] = [0, 1, 2, 3].map(f => mod(value(Array.from(limbs(AI + 4 * k + f))))) @@ -270,6 +325,7 @@ function harness (compiled) { } } const [FA, FB, FH, U8A, U8B, U8C, U8D, U8W, PA, PB, PC, FS, AI] = [0, 1, 2, 3, 4, 5, 6, 7, 10, 20, 30, 40, 100] +const [R1, R1B, Q2, Q2B, CA, CC, PP] = [50, 60, 70, 80, 90, 94, 140] const HALF = modinv(2n) /** Runs `[a]A + [b]B` and the subtraction `verify()` makes of it, collecting results under `note`. */ @@ -380,6 +436,125 @@ function degenerate (h, note) { } } +/** + * Every operation in `p.ts` on its own, over the identity, every torsion point, + * torsion offsets and random points, each input written in a random projective + * scaling. Each result is read back through its own representation and must be + * the right point and a well-formed one: a completed point as `(XT, YZ, ZT, XY)`, + * a projective one as `(XZ, YZ, Z², XY)`, and a cached one with `T` recovered + * from `2dT`, so a wrong `T2d` fails `XY = ZT`. Sums take `q = p`, `q = -p` and the + * identity as well as unrelated points. + * + * Until these, the operations were reached only through the scalar + * multiplications, and an operation that a caller does not happen to alias was + * never run aliased: an output that is also an input runs both ways here. Then + * the operations run chained as the double scalar multiplication chains them, + * so a doubling also takes the loose limbs a sum leaves rather than only tight + * ones. Draws from its own generator, so the inputs above do not move. + */ +function pointOps (h, note) { + const { x, setProjective, getCoords } = h + const draw = generator('nano25519 point operations') + const scalar = () => toLE(draw(32)) % L + const nonzero = () => toLE(draw(32)) % (P - 1n) + 1n + const twoD = mod(2n * D) + const affine = (p) => { const zi = modinv(p[2]); return [mod(p[0] * zi), mod(p[1] * zi)] } + // writers, each in a fresh random scaling + const asP3 = (p) => { const [ax, ay] = affine(p), l = nonzero(); return [ax * l, ay * l, l, ax * ay * l] } + const asP1p1 = (p) => { const [ax, ay] = affine(p), l = nonzero(), m = nonzero(); return [ax * l, ay * m, l, m] } + const asP2 = (p) => { const [ax, ay] = affine(p), l = nonzero(); return [ax * l, ay * l, l] } + const asCached = (p) => { const [X, Y, Z, T] = asP3(p); return [Y + X, Y - X, Z, twoD * T] } + const asPrecomp = (p) => { const [ax, ay] = affine(p); return [ay + ax, ay - ax, twoD * ax * ay] } + // readers, back to extended coordinates; null for dirty padding + const fromP3 = (base) => getCoords(base, 4) + const fromP1p1 = (base) => { const c = getCoords(base, 4); return c && [c[0] * c[3], c[1] * c[2], c[2] * c[3], c[0] * c[1]].map(v => mod(v)) } + const fromP2 = (base) => { const c = getCoords(base, 3); return c && [c[0] * c[2], c[1] * c[2], c[2] * c[2], c[0] * c[1]].map(v => mod(v)) } + const fromCached = (base) => { const c = getCoords(base, 4); return c && [mod((c[0] - c[1]) * HALF), mod((c[0] + c[1]) * HALF), c[2], mod(c[3] * modinv(twoD))] } + const same = (got, want) => got != null && equal(got, want) && isExtended(got) + const garbage = () => Array.from({ length: 4 }, () => toLE(draw(32)) % P) + + const points = [IDENTITY, ...TORSION] + for (const T of TORSION) points.push(add(mul(B, scalar()), T)) + for (let k = 0; k < 120; k++) points.push(mul(B, scalar())) + + // each zero must write every coordinate, so fill them with garbage first + for (let k = 0; k < 8; k++) { + setProjective(R1, garbage()); x.point_op_(0, 0) + note('p1p1_0 is the identity', same(fromP1p1(R1), IDENTITY), k) + setProjective(Q2, garbage().slice(0, 3)); x.point_op_(1, 0) + note('p2_0 is the identity', same(fromP2(Q2), IDENTITY), k) + setProjective(PB, garbage()); x.point_op_(2, 0) + note('p3_0 is the identity', same(fromP3(PB), IDENTITY), k) + setProjective(PP, garbage().slice(0, 3)); x.point_op_(3, 0) + const pp = getCoords(PP, 3) + note('precomp_0 is the identity', pp != null && pp[0] === 1n && pp[1] === 1n && pp[2] === 0n, k) + } + + for (const [i, p] of points.entries()) { + const p2 = add(p, p) + setProjective(R1, asP1p1(p)); x.point_op_(4, 0) + note('p1p1_to_p2', same(fromP2(Q2), p), i) + setProjective(R1, asP1p1(p)); x.point_op_(5, 0) + note('p1p1_to_p3', same(fromP3(PB), p), i) + setProjective(PA, asP3(p)); x.point_op_(6, 0) + note('p3_to_cached', same(fromCached(CA), p), i) + setProjective(R1, asP1p1(p)); x.point_op_(7, 0) + note('p1p1_to_cached', same(fromCached(CA), p), i) + for (const alias of [0, 1]) { + const into = alias ? 'into its input' : 'into a separate point' + setProjective(R1, asP1p1(p)); x.point_op_(8, alias) + note(`p1p1_dbl_to_p1p1 ${into}`, same(fromP1p1(alias ? R1 : R1B), p2), i) + setProjective(Q2, asP2(p)); x.point_op_(9, alias) + note(`p2_dbl_to_p2 ${into}`, same(fromP2(alias ? Q2 : Q2B), p2), i) + setProjective(PA, asP3(p)); x.point_op_(12, alias) + note(`p3_dbl_to_p3 ${into}`, same(fromP3(alias ? PA : PB), p2), i) + } + setProjective(Q2, asP2(p)); x.point_op_(10, 0) + note('p2_dbl_to_p3', same(fromP3(PB), p2), i) + setProjective(PA, asP3(p)); x.point_op_(11, 0) + note('p3_dbl_to_p2', same(fromP2(Q2), p2), i) + + for (const q of [p, negate(p), IDENTITY, points[(i * 7 + 3) % points.length], mul(B, scalar())]) { + const sum = add(p, q), diff = add(p, negate(q)) + setProjective(PA, asP3(p)); setProjective(CA, asCached(q)); x.point_op_(13, 0) + note('p3_add_cached', same(fromP1p1(R1), sum), [i, q]) + setProjective(PA, asP3(p)); setProjective(CA, asCached(q)); x.point_op_(14, 0) + note('p3_sub_cached', same(fromP1p1(R1), diff), [i, q]) + setProjective(PA, asP3(p)); setProjective(PP, asPrecomp(q)); x.point_op_(17, 0) + note('p3_add_precomp', same(fromP1p1(R1), sum), [i, q]) + setProjective(PA, asP3(p)); setProjective(PP, asPrecomp(q)); x.point_op_(18, 0) + note('p3_sub_precomp', same(fromP1p1(R1), diff), [i, q]) + for (const alias of [0, 1]) { + const into = alias ? 'into its input' : 'into a separate point' + setProjective(PA, asP3(p)); setProjective(CA, asCached(q)); x.point_op_(15, alias) + note(`p3_add_cached_to_cached ${into}`, same(fromCached(alias ? CA : CC), sum), [i, q]) + setProjective(PA, asP3(p)); setProjective(CA, asCached(q)); x.point_op_(16, alias) + note(`p3_sub_cached_to_p3 ${into}`, same(fromP3(alias ? PA : PB), diff), [i, q]) + } + } + + // as ge_double_scalarmult_vartime chains them: a sum or difference left in + // r, doubled in place twice, then converted for the next addition + const q = points[(i * 11 + 5) % points.length] + for (const [op, name, base, convert] of [ + [13, 'p3_add_cached', CA, asCached], + [14, 'p3_sub_cached', CA, asCached], + [17, 'p3_add_precomp', PP, asPrecomp], + [18, 'p3_sub_precomp', PP, asPrecomp], + ]) { + const first = op === 13 || op === 17 ? add(p, q) : add(p, negate(q)) + const want = mul(first, 4n) + setProjective(PA, asP3(p)); setProjective(base, convert(q)); x.point_op_(op, 0) + x.point_op_(8, 1); x.point_op_(8, 1) + const quad = fromP1p1(R1) + x.point_op_(5, 0) + const asExtended = fromP3(PB) + x.point_op_(7, 0) + note(`${name}, doubled in place twice, then to p3 and to cached`, same(quad, want) && same(asExtended, want) && same(fromCached(CA), want), i) + } + } +} + function collector () { const results = {} const note = (name, ok, input) => { @@ -404,11 +579,12 @@ function check (name, test, detail = '') { const started = performance.now() await rm(work, { recursive: true, force: true }) try { - const [clean, noIdentity, staleT, noPreconditions] = await Promise.all([ + const [clean, noIdentity, staleT, noPreconditions, dblOrder] = await Promise.all([ probe('clean'), probe('no-identity', NO_IDENTITY).catch((err) => err), probe('stale-t', STALE_T).catch((err) => err), probe('no-preconditions', NO_PRECONDITIONS).catch((err) => err), + probe('dbl-order', DBL_ORDER).catch((err) => err), ]) // positive controls @@ -447,6 +623,22 @@ try { } } + // dbl_to_p1p1 reordered to square its inputs before summing them is still + // right for every caller but the one that hands it r's own coordinates, so + // the operation tests must name p1p1_dbl_to_p1p1, both ways it is called, + // and pass every doubling built on the same helper through t + { + const control = collector() + if (dblOrder instanceof WebAssembly.Module) pointOps(harness(dblOrder), control.note) + const r = control.results + const bad = (key) => r[key] != null && r[key].bad > 0 + const clean = (key) => r[key] != null && r[key].bad === 0 + const seen = bad('p1p1_dbl_to_p1p1 into its input') && bad('p1p1_dbl_to_p1p1 into a separate point') + && ['p2_dbl_to_p2 into its input', 'p2_dbl_to_p2 into a separate point', 'p3_dbl_to_p3 into its input', 'p3_dbl_to_p3 into a separate point', 'p2_dbl_to_p3', 'p3_dbl_to_p2', 'p3_add_cached'].every(clean) + const detail = dblOrder instanceof WebAssembly.Module ? Object.entries(r).map(([k, v]) => `${k}: ${v.bad}/${v.n} bad`).join('; ') : String(dblOrder?.message ?? dblOrder) + check('control sees dbl_to_p1p1 reordered in p1p1_dbl_to_p1p1 alone', seen, detail) + } + const h = harness(clean) const { x, bytes, set, get, padded, setPoint, setProjective, getPoint } = h const { results, note } = collector() @@ -651,6 +843,7 @@ try { doubleScalarmult(h, note, 400) preconditions(h, note) degenerate(h, note) + pointOps(h, note) let comparisons = 0 for (const [name, r] of Object.entries(results)) { @@ -664,5 +857,5 @@ try { console.log(`${passes} \x1b[32mPASSED\x1b[0m`) console.log(`${failures} \x1b[31mFAILED\x1b[0m`) -console.log(`4 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`) +console.log(`5 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`) process.exitCode = failures > 0 ? 1 : 0 diff --git a/test/node.mjs b/test/node.mjs index cb802ae..ed0a276 100644 --- a/test/node.mjs +++ b/test/node.mjs @@ -996,6 +996,316 @@ check(`derive output buffer lying about byteLength`, test) passes += +test failures += +!test +// The sizes are a public API, so pin what consumers are told to rely on: the +// object is frozen, the encodings are their Ed25519 sizes, and the two derived +// limits hold the relations AGENTS.md states for them. +{ + const { BLOCKHASH_BYTELENGTH, KEY_BYTELENGTH, SIGNATURE_BYTELENGTH, MAX_VERIFY_BLOCKS, MAX_VERIFY_BLOCKS_BYTELENGTH, MAX_MESSAGE_BYTELENGTH } = constants + test = Object.isFrozen(constants) + && BLOCKHASH_BYTELENGTH === 32 && KEY_BYTELENGTH === 32 && SIGNATURE_BYTELENGTH === 64 + && Number.isInteger(MAX_VERIFY_BLOCKS) && MAX_VERIFY_BLOCKS >= 1 + && MAX_VERIFY_BLOCKS_BYTELENGTH === MAX_VERIFY_BLOCKS * (SIGNATURE_BYTELENGTH + BLOCKHASH_BYTELENGTH) + && MAX_MESSAGE_BYTELENGTH === Math.max(MAX_VERIFY_BLOCKS_BYTELENGTH, 1 << 16) + check(`constants are frozen and hold their documented sizes and relations${test ? '' : ` (${JSON.stringify(constants)})`}`, test) + passes += +test + failures += +!test +} + +/** + * Runs `f` and returns what it threw, or `null` if it returned. + * @param {() => unknown} f + */ +function thrown (f) { + try { + f() + return null + } catch (err) { + return err + } +} +/** + * True if `err` is a `Nano25519TypeError` with exactly `message`. + * @param {unknown} err + * @param {string} message + */ +const isTypeError = (err, message) => err instanceof TypeError && err.constructor.name === 'Nano25519TypeError' && err.message === message +/** @param {unknown} err */ +const describeError = (err) => err == null ? 'returned' : err instanceof Error ? `${err.constructor.name}: ${err.message}` : String(err) +/** @param {Uint8Array} b */ +const toHex = (b) => [...b].map(v => v.toString(16).padStart(2, '0')).join('') + +// Every byte argument accepts exactly two shapes: a hex string and a Uint8Array +// over a non-shared ArrayBuffer. Each shape AGENTS.md says is refused, and the +// plausible mistakes beside them, go in every position of every primitive, and +// each must throw a Nano25519TypeError naming that argument. Until these, only +// derive's private key was tried, and only as a Uint16Array and over shared +// memory; a bare ArrayBuffer and a DataView were never passed anywhere. +{ + const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR + /** @type {[string, (b: Uint8Array) => unknown][]} */ + const shapes = [ + ['a bare ArrayBuffer', (b) => b.slice().buffer], + ['a bare SharedArrayBuffer', (b) => { const s = new Uint8Array(new SharedArrayBuffer(b.length)); s.set(b); return s.buffer }], + ['a view over a SharedArrayBuffer', (b) => { const s = new Uint8Array(new SharedArrayBuffer(b.length)); s.set(b); return s }], + ['a DataView', (b) => new DataView(b.slice().buffer)], + ['an Int8Array', (b) => new Int8Array(b.slice().buffer)], + ['a Uint8ClampedArray', (b) => new Uint8ClampedArray(b)], + ['a Uint16Array', (b) => new Uint16Array(b.slice().buffer)], + ['an Array of bytes', (b) => [...b]], + ['an array-like object', (b) => ({ ...b, length: b.length })], + ['a String object', (b) => new String(toHex(b))], + ['a number', () => 0], + ['null', () => null], + ['undefined', () => undefined], + ] + /** @type {[string, string, Uint8Array, (v: any) => unknown][]} */ + const positions = [ + ['derive', 'private key', prv, (v) => derive(v)], + ['sign', 'message', hash, (v) => sign(v, prv, pub)], + ['sign', 'private key', prv, (v) => sign(hash, v, pub)], + ['sign', 'public key', pub, (v) => sign(hash, prv, v)], + ['verify', 'signature', sig, (v) => verify(v, hash, pub)], + ['verify', 'message', hash, (v) => verify(sig, v, pub)], + ['verify', 'public key', pub, (v) => verify(sig, hash, v)], + ['verify_blocks', 'public key', pub, (v) => verify_blocks(v, [{ hash, signature: sig }])], + ['verify_blocks', 'signature', sig, (v) => verify_blocks(pub, [{ hash, signature: v }])], + ['verify_blocks', 'hash', hash, (v) => verify_blocks(pub, [{ hash: v, signature: sig }])], + ] + for (const [primitive, name, bytes, call] of positions) { + /** @type {string[]} */ + const wrong = [] + for (const [shape, make] of shapes) { + const err = thrown(() => call(make(bytes))) + if (!isTypeError(err, `${name} must be a hex string or Uint8Array`)) { + wrong.push(`${shape}: ${describeError(err)}`) + } + } + test = wrong.length === 0 + check(`${primitive} refuses ${shapes.length} shapes of ${name} that are not hex or Uint8Array, with a TypeError${test ? '' : ` (${wrong.join('; ')})`}`, test) + passes += +test + failures += +!test + } + + // every fixed-length argument, one byte or one hex digit either side of its + // size, and the empty string; and a message one byte past the limit and an + // odd hex length for verify, which only sign checked + /** @type {[string, string, number, (v: any) => unknown][]} */ + const sized = [ + ['derive', 'private key', constants.KEY_BYTELENGTH, (v) => derive(v)], + ['sign', 'private key', constants.KEY_BYTELENGTH, (v) => sign(hash, v, pub)], + ['sign', 'public key', constants.KEY_BYTELENGTH, (v) => sign(hash, prv, v)], + ['verify', 'signature', constants.SIGNATURE_BYTELENGTH, (v) => verify(v, hash, pub)], + ['verify', 'public key', constants.KEY_BYTELENGTH, (v) => verify(sig, hash, v)], + ['verify_blocks', 'public key', constants.KEY_BYTELENGTH, (v) => verify_blocks(v, [{ hash, signature: sig }])], + ['verify_blocks', 'signature', constants.SIGNATURE_BYTELENGTH, (v) => verify_blocks(pub, [{ hash, signature: v }])], + ['verify_blocks', 'hash', constants.BLOCKHASH_BYTELENGTH, (v) => verify_blocks(pub, [{ hash: v, signature: sig }])], + ] + for (const [primitive, name, size, call] of sized) { + /** @type {[unknown, string][]} */ + const cases = [ + [new Uint8Array(size - 1), `${name} must be at least ${size} bytes`], + [new Uint8Array(size + 1), `${name} must be no more than ${size} bytes`], + ['', `Invalid hexadecimal length 0 for ${name}`], + ] + for (const length of [2 * size - 2, 2 * size - 1, 2 * size + 1, 2 * size + 2]) { + cases.push(['0'.repeat(length), `Invalid hexadecimal length ${length} for ${name}`]) + } + /** @type {string[]} */ + const wrong = [] + for (const [value, message] of cases) { + const err = thrown(() => call(value)) + if (!isTypeError(err, message)) { + wrong.push(`${message}: ${describeError(err)}`) + } + } + test = wrong.length === 0 + check(`${primitive} refuses a ${name} of any size but ${size} bytes${test ? '' : ` (${wrong.join('; ')})`}`, test) + passes += +test + failures += +!test + } + { + const tooLong = thrown(() => verify(sig, new Uint8Array(constants.MAX_MESSAGE_BYTELENGTH + 1), pub)) + const odd = thrown(() => verify(sig, NANO_ORG_VECTOR.invalidMessageLength, pub)) + test = isTypeError(tooLong, `message must be no more than ${constants.MAX_MESSAGE_BYTELENGTH} bytes`) + && isTypeError(odd, `Invalid hexadecimal length ${NANO_ORG_VECTOR.invalidMessageLength.length}`) + check(`verify refuses a message past the limit and an odd hex length${test ? '' : ` (${describeError(tooLong)}; ${describeError(odd)})`}`, test) + passes += +test + failures += +!test + } + + // an output buffer is checked before the lock is taken, so a refused one + // must leave the next call working, and a shared one must receive nothing + /** @type {[string, () => unknown][]} */ + const outputs = [ + ['a view over a SharedArrayBuffer', () => new Uint8Array(new SharedArrayBuffer(64))], + ['a bare ArrayBuffer', () => new ArrayBuffer(64)], + ['a DataView', () => new DataView(new ArrayBuffer(64))], + ['a Uint8ClampedArray', () => new Uint8ClampedArray(64)], + ['a Uint16Array', () => new Uint16Array(32)], + ['an Array', () => new Array(64).fill(0)], + ['null', () => null], + ] + for (const [primitive, size, call] of /** @type {[string, number, (out: any) => unknown][]} */ ([ + ['derive', constants.KEY_BYTELENGTH, (out) => derive(prv, out)], + ['sign', constants.SIGNATURE_BYTELENGTH, (out) => sign(hash, prv, pub, out)], + ])) { + const message = `${primitive === 'derive' ? 'Derive' : 'Sign'} output buffer must be ${size}-byte Uint8Array` + /** @type {string[]} */ + const wrong = [] + for (const [shape, make] of outputs) { + let out = make() + // sized to the primitive, so only the shape can be what is refused + if (out instanceof Uint8Array) out = out.subarray(0, size) + else if (out instanceof Uint8ClampedArray) out = out.subarray(0, size) + else if (Array.isArray(out)) out.length = size + const err = thrown(() => call(out)) + const untouched = !(out instanceof Uint8Array) || out.every(b => b === 0) + if (!isTypeError(err, message) || !untouched) { + wrong.push(`${shape}: ${describeError(err)}${untouched ? '' : ', and was written'}`) + } + } + const after = attempt(() => derive(prv)) + test = wrong.length === 0 && after === NANO_ORG_VECTOR.publicKey.toLowerCase() + check(`${primitive} refuses an output buffer that is not a Uint8Array, writing nothing to it${test ? '' : ` (${wrong.join('; ')}; next derive ${after})`}`, test) + passes += +test + failures += +!test + } +} + +// The error classes are part of the contract: input and shape errors are +// TypeErrors, a block count out of range is a RangeError, and a refusal from +// the module is a Nano25519WasmError, which is neither. Every check above this +// section compared message text only. +{ + const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR + const block = { hash, signature: sig } + /** @type {[string, () => unknown, (err: unknown) => boolean][]} */ + const cases = [ + ['no blocks', () => verify_blocks(pub, []), (err) => err instanceof RangeError && err.constructor.name === 'Nano25519RangeError'], + ['too many blocks', () => verify_blocks(pub, new Array(constants.MAX_VERIFY_BLOCKS + 1).fill(block)), (err) => err instanceof RangeError && err.constructor.name === 'Nano25519RangeError'], + ['a null block', () => verify_blocks(pub, [null]), (err) => isTypeError(err, 'Invalid block')], + ['a block that is a string', () => verify_blocks(pub, ['block']), (err) => isTypeError(err, 'Invalid block')], + ['a mismatched public key', () => sign(hash, prv, sig.subarray(0, 32)), (err) => err instanceof Error && !(err instanceof TypeError) && !(err instanceof RangeError) && err.constructor.name === 'Nano25519WasmError' && err.message === 'Invalid public key'], + ] + /** @type {string[]} */ + const wrong = [] + for (const [name, f, ok] of cases) { + const err = thrown(f) + if (!ok(err)) wrong.push(`${name}: ${describeError(err)}`) + } + test = wrong.length === 0 + check(`errors carry their documented classes${test ? '' : ` (${wrong.join('; ')})`}`, test) + passes += +test + failures += +!test +} + +// Subclasses and views with a byteOffset are accepted everywhere, but only a +// private key at byteOffset 1 was ever passed. A Node Buffer is both, and the +// form most Node callers have, so every argument of every primitive, and both +// output buffers, go in as a Buffer at an odd offset inside a larger one, whose +// bytes on either side must be left alone. +{ + const { blockHash, privateKey, publicKey, signature, signatureBytes } = NANO_ORG_VECTOR + /** @param {string} hex */ + const view = (hex) => { + const outer = Buffer.alloc(hex.length / 2 + 14, 0xa5) + outer.write(hex, 7, 'hex') + return outer.subarray(7, 7 + hex.length / 2) + } + /** @param {Buffer} b */ + const surroundings = (b) => { + const outer = new Uint8Array(b.buffer, b.byteOffset - 7, b.length + 14) + return outer.subarray(0, 7).every(v => v === 0xa5) && outer.subarray(7 + b.length).every(v => v === 0xa5) + } + const forged = signatureBytes.slice() + forged[33] ^= 4 + const derived = view('00'.repeat(32)) + const signed = view('00'.repeat(64)) + /** @type {[string, () => unknown, unknown][]} */ + const cases = [ + ['derive', () => derive(view(privateKey)), publicKey.toLowerCase()], + ['derive, output buffer', () => [derive(view(privateKey), derived), toHex(derived), surroundings(derived)], [undefined, publicKey.toLowerCase(), true]], + ['sign', () => sign(view(blockHash), view(privateKey), view(publicKey)), signature.toLowerCase()], + ['sign, output buffer', () => [sign(view(blockHash), view(privateKey), view(publicKey), signed), toHex(signed), surroundings(signed)], [undefined, signature.toLowerCase(), true]], + ['verify', () => verify(view(signature), view(blockHash), view(publicKey)), true], + ['verify, forged', () => verify(view(toHex(forged)), view(blockHash), view(publicKey)), false], + ['verify_blocks', () => [...verify_blocks(view(publicKey), [{ hash: view(blockHash), signature: view(signature) }, { hash: view(blockHash), signature: view(toHex(forged)) }])], [true, false]], + ] + for (const [name, f, expected] of cases) { + result = attempt(f) + test = JSON.stringify(result) === JSON.stringify(expected) + check(`${name} accepts a Node Buffer at an odd byteOffset in every argument${test ? '' : ` (returned ${JSON.stringify(result)})`}`, test) + passes += +test + failures += +!test + } +} + +// verify_blocks takes one block outside an array as a batch of one, which no +// test reached, and takes every argument as hex as well as bytes. Both must +// verify the genuine block and refuse a forged one, and return a frozen array. +{ + const { blockHash, publicKey, signature, signatureBytes } = NANO_ORG_VECTOR + const forged = signatureBytes.slice() + forged[50] ^= 0x10 + const forgedHex = toHex(forged) + /** @type {[string, () => readonly boolean[], boolean[]][]} */ + const cases = [ + ['one block outside an array', () => verify_blocks(publicKey, { hash: blockHash, signature }), [true]], + ['one forged block outside an array', () => verify_blocks(publicKey, { hash: blockHash, signature: forgedHex }), [false]], + ['hex key, hashes and signatures', () => verify_blocks(publicKey, [{ hash: blockHash, signature }, { hash: blockHash, signature: forgedHex }, { hash: blockHash.toLowerCase(), signature: signature.toLowerCase() }]), [true, false, true]], + ] + for (const [name, f, expected] of cases) { + const r = attempt(f) + test = Array.isArray(r) && Object.isFrozen(r) && r.length === expected.length && expected.every((v, i) => r[i] === v) + check(`verify_blocks with ${name}${test ? '' : ` (returned ${JSON.stringify(r)})`}`, test) + passes += +test + failures += +!test + } +} + +// Every batch size, not only 1, 2 and the cap: this path's bugs have twice been +// invisible below a boundary and appeared only past it. Each block signs its +// own hash, and two blocks per batch are forged, the last one and one that +// moves through the middle, so the answer is a pattern rather than all true. +// The sizes run downward, so every forged block sits where the previous, larger +// batch left a `true` in OUTPUT_VERIFY: a module that wrote only successes over +// a buffer it had not cleared would read that stale `true` here. +{ + const { privateKeyBytes: prv, publicKeyBytes: pub } = NANO_ORG_VECTOR + /** @type {{ hash: Uint8Array, signature: Uint8Array }[]} */ + const blocks = [] + for (let b = 0; b < constants.MAX_VERIFY_BLOCKS; b++) { + const hash = new Uint8Array(constants.BLOCKHASH_BYTELENGTH).map((_, i) => (i * 59 + b * 113 + 7) & 0xff) + const signature = new Uint8Array(constants.SIGNATURE_BYTELENGTH) + attempt(() => sign(hash, prv, pub, signature)) + blocks.push({ hash, signature }) + } + /** @type {string[]} */ + const wrong = [] + for (let n = constants.MAX_VERIFY_BLOCKS; n >= 1; n--) { + const forged = new Set([n - 1, (n * 3) >> 3]) + const batch = blocks.slice(0, n).map((block, b) => { + if (!forged.has(b)) return block + const signature = block.signature.slice() + signature[(b * 7) % constants.SIGNATURE_BYTELENGTH] ^= 1 << (b % 8) + return { hash: block.hash, signature } + }) + const r = attempt(() => verify_blocks(pub, batch)) + const expected = batch.map((_, b) => !forged.has(b)) + if (!Array.isArray(r) || r.length !== n || expected.some((v, b) => r[b] !== v)) { + wrong.push(`${n}: ${JSON.stringify(r)}`) + } + } + // the sweep only asserts patterns that include refusals, so assert an + // all-genuine batch too, or a module refusing everything but the last block + // of each size would read as half right rather than wrong + const all = attempt(() => verify_blocks(pub, blocks)) + test = wrong.length === 0 && Array.isArray(all) && all.length === blocks.length && all.every(v => v === true) + check(`verify_blocks returns exactly the right pattern at every batch size from ${constants.MAX_VERIFY_BLOCKS} down to 1${test ? '' : ` (${wrong.length} sizes wrong, first ${wrong.slice(0, 3).join('; ')}; genuine batch ${JSON.stringify(all)})`}`, test) + passes += +test + failures += +!test +} + // A hostile Uint8Array subclass must not reach input handling. It lies through // Symbol.species, length, byteLength and Symbol.toStringTag, and overrides set; // none of those may be consulted, and none of its code may run inside a call. -- 2.52.0