]> git.codecow.com Git - nano25519.git/commitdiff
Overhaul testing modules.
authorChris Duncan <chris@codecow.com>
Tue, 6 Oct 2026 06:45:56 +0000 (23:45 -0700)
committerChris Duncan <chris@codecow.com>
Tue, 6 Oct 2026 06:45:56 +0000 (23:45 -0700)
AGENTS.md
package.json
src/assembly/env.ts
src/assembly/errors.ts
src/assembly/index.ts
src/assembly/tests.ts
src/lib/errors.ts
src/lib/wasm.ts
test/mutants.mjs [new file with mode: 0644]

index 0a8beb059034667c8d9b19853211365076924978..5f9bec5baf0c1b1a91219afb573c7a3c48bc1709 100644 (file)
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -387,15 +387,16 @@ show up on the clock; only the point arithmetic does.
 
 ## Testing
 
-`node ./test/node.mjs` after a build. Current state is **6194 passing, 0
-failing**. There is no longer an expected failure — if anything fails, it is a
-regression.
+`npm test` builds, then runs `test/node.mjs` twice, little- and big-endian.
+Current state is **6255 passing, 0 failing** in each. There is no expected
+failure — if anything fails, it is a regression.
 
-`equalbytes` additionally self-tests in the module's **start function**, in
-`src/assembly/tests.ts`, imported by `index.ts` so it runs at instantiation. A
-regression there makes the module fail to instantiate, so the package becomes
-unimportable rather than silently weakening signature verification. Keep that
-pattern for anything whose failure mode is "quietly accepts too much".
+`equalbytes` and `ge_is_canonical` additionally self-test in the module's
+**start function**, in `src/assembly/tests.ts`, imported by `index.ts` so it
+runs at instantiation. A regression there makes the module fail to instantiate,
+so the package becomes unimportable rather than silently weakening signature
+verification. Keep that pattern for anything whose failure mode is "quietly
+accepts too much".
 
 Three key vectors — all-zero, all-ones, and `spread` (32 distinct bytes from
 `i * 37 + 11`; 37 is odd, so it is a bijection mod 256, and the multiplier is
@@ -410,7 +411,7 @@ Each is compared against itself, then corrupted in **two shapes**:
   cancels under both `^=` and `+=`.
 
 **25,971 comparisons per instantiation**, all but three of which must report
-unequal, at a cost of **0.565 ms**.
+unequal, at a cost of about **0.40 ms**.
 
 ⚠️ **The two-byte shape is not optional, and nothing else catches what it
 catches.** `b |= d` has no inverse, but `b ^= d` and `b += d` are each one
@@ -423,11 +424,54 @@ entirely. Only the full pairwise sweep covers every stride.
 The guard reports which vector and which bytes:
 
 ```text
-equalbytes build error from "zeros": expected fail [0,0,…]; actual pass [128,128,0,…]
+equalbytes build error from "zeros": expected fail [0,0,…]; actual pass [128,128,0,…] (bytes 0 and 1 ^ 0x80)
 ```
 
-That message survives instantiation only because of `importMemory: true` — see
-**Build constraints**.
+The module never formats that text. A failing check raises a code and two
+integers that describe its input completely, and `src/lib/errors.ts` rebuilds
+the bytes from them, so **every vector and case in `tests.ts` is mirrored
+there**. Change one side and you must change the other.
+
+### The `ge_is_canonical` guard
+
+`ge_is_canonical` gates strict `verify()` for both the public key and `R`. **No
+end-to-end test can reach it.** Non-canonical encodings exist only for the 19
+values `p ≤ y < 2²⁵⁵`, which decode to points with `y < 19`, and nobody knows a
+discrete log for those, so no valid signature can carry one. fc46ae5 shipped
+`c |= s[i]` for `c |= s[i] ^ 0xff`, which accepted all 38 non-canonical
+encodings and rejected some canonical ones, and the suite stayed green.
+
+The 19 values share every bit above byte 0, so byte 0 decides only when the
+247 bits above it are all set, and those bits decide otherwise. The guard
+enumerates both sides of that boundary, each with the sign bit clear and set:
+
+- **every byte 0** under all-set high bits — exhaustive over the only slice where
+  the answer turns on byte 0, so all 38 non-canonical encodings are rejected;
+- **each of the 247 high bits cleared alone**, which must accept — catches a
+  loop bound or mask that skips a byte or a bit;
+- **the same bit cleared at all 465 pairs of positions** — the `^=` shape again;
+- **every byte 0** under three high patterns far from `p`, including byte 31
+  set over clear bytes 1 to 30, the shape fc46ae5's bug rejected.
+
+**4,896 calls per instantiation, about 0.14 ms.** A case packs into one integer
+(byte 0, sign, high pattern, up to two flipped positions and the bit), which is
+also its error detail, so the host prints the exact 32 bytes:
+
+```text
+ge_is_canonical build error from "max": expected non-canonical [237,255,…,127]; actual returned 0 (byte 0 = 0xed, sign 0)
+```
+
+### Mutation tests
+
+`npm run test:mutants` (`test/mutants.mjs`, also run by `prepublishOnly`) is
+what shows the guards work rather than merely pass. It builds copies of the
+module, each with one historical or plausible defect in a guarded function, and
+requires every copy to be **refused at instantiation by its own guard**, through
+the real host handler: `^=`, `+=`, a `u8` accumulator and a short loop in
+`equalbytes`; fc46ae5's bug, `^=`, a skipped byte, an unmasked sign bit, `p`
+accepted, and `|` for `&` in `ge_is_canonical`. Eleven builds, about 5 s.
+**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
index 2a988a07dbec804acdb59aefca941b81687cc760..fdb9c4144d535e11eb2130b01eeb38062b874842 100644 (file)
                "clean": "rm -rf {build,dist}",
                "compile": "node scripts/blake2b-gen.mjs && npm run asc",
                "compile:prod": "node scripts/blake2b-gen.mjs && npm run asc:prod",
-               "prepublishOnly": "npm run test:prod",
+               "prepublishOnly": "npm run test:prod && npm run test:mutants",
                "profile": "npm run build && node --cpu-prof --cpu-prof-interval 50 --cpu-prof-dir prof test/node.mjs",
                "test": "npm run build && npm run test:all",
                "test:all": "npm run test:le && npm run test:be",
                "test:be": "node --import ./test/big-endian.mjs ./test/node.mjs",
                "test:le": "node ./test/node.mjs",
+               "test:mutants": "node ./test/mutants.mjs",
                "test:prod": "npm run build:prod && npm run test:all"
        },
        "devDependencies": {
index e2b22db9e38da0faa41d526f3eb440a3ecf44248..cbb09dccf84f0f5cf2c8d1cb04584fd178e3e3a0 100644 (file)
@@ -5,7 +5,7 @@ import { ERROR_UNKNOWN, } from './errors'
 
 /**
  * The module's only import, installed as AssemblyScript's `abort` by
- * `use: ["abort=src/assembly/abort/abort"]` in `asconfig.json`.
+ * `use: ["abort=src/assembly/env/abort"]` in `asconfig.json`.
  *
  * It takes four integers and no pointers so the host never reads WASM memory
  * to report an error unlike the default `abort` which decodes a UTF-16 string
@@ -18,7 +18,6 @@ declare function env_abort (code: i32, line: i32, detail: i32, context: i32): vo
 let errorCode: i32 = ERROR_UNKNOWN
 let errorDetail: i32 = 0
 let errorContext: i32 = 0
-let errorLine: i32 = 0
 
 /**
  * Reads the pending code, resets it, and hands it to the host. Resetting
@@ -29,12 +28,10 @@ export function abort (message: usize, fileName: usize, row: u32, col: u32): voi
        const code = errorCode
        const detail = errorDetail
        const context = errorContext
-       const line = errorLine || row
        errorCode = ERROR_UNKNOWN
        errorDetail = 0
        errorContext = 0
-       errorLine = 0
-       env_abort(code, i32(line), detail, context)
+       env_abort(code, i32(row), detail, context)
 }
 
 /**
@@ -48,10 +45,9 @@ export function abort (message: usize, fileName: usize, row: u32, col: u32): voi
  */
 //@ts-expect-error
 @inline
-export function raise (code: i32, detail: i32 = 0, context: i32 = 0, line: i32 = 0): void {
+export function raise (code: i32, detail: i32 = 0, context: i32 = 0): void {
        errorCode = code
        errorDetail = detail
        errorContext = context
-       errorLine = line
        throw new Error()
 }
index 9103112c334049d65664ab3ff2745a9af8df7396..425598263699c129fb21b4485451ba5dd6c86f24 100644 (file)
@@ -34,25 +34,25 @@ export const BUFFER_OUTPUT_SIGN: i32 = 5
 export const BUFFER_OUTPUT_VERIFY: i32 = 6
 
 /**
- * `equalbytes` start-function guard. `a` is the vector index (0 `zeros`,
- * 1 `ones`, 2 `spread`); `b` encodes the corruption the comparison failed to
- * detect with 0 for `SELFTEST_XPASS`.
+ * `equalbytes` start-function guard in `tests.ts`. `a` is the vector index
+ * (0 `zeros`, 1 `ones`, 2 `spread`) and `b` the corruption that went
+ * undetected, so the host can rebuild both inputs.
  *
- * - `SELFTEST_XFAIL_ONE`: `b` is `(position << 8) | mask`
- * - `SELFTEST_XFAIL_PAIR`: `b` is `(position << 8) | position`, both `^= 0x80`
+ * - `XPASS`: a vector compared unequal to itself; `b` is 0
+ * - `XFAIL_ONE`: `b` is `(position << 8) | mask`, one byte `^= mask`
+ * - `XFAIL_PAIR`: `b` is `(i << 8) | j`, both bytes `^= 0x80`
  */
 export const ERROR_EQUALBYTES_SELFTEST_XPASS: i32 = 6
 export const ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE: i32 = 7
 export const ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: i32 = 8
 
 /**
- * `ge_is_canonical` start-function guard. `a` is the vector index (0 `zeros`,
- * 1 `ones`, 2 `spread`); `b` encodes the corruption the comparison failed to
- * detect with 0 for `SELFTEST_XPASS`.
+ * `ge_is_canonical` start-function guard in `tests.ts`. `a` is the packed case
+ * that failed, which rebuilds the exact 32 input bytes (see `ge_case` there and
+ * `canonicalCase` in `src/lib/errors.ts`); `b` is what the function returned.
  *
- * - `SELFTEST_XFAIL_ONE`: `b` is `(position << 8) | mask`
- * - `SELFTEST_XFAIL_PAIR`: `b` is `(position << 8) | position`, both `^= 0x80`
+ * - `XPASS`: a canonical encoding (`y < p`) was rejected
+ * - `XFAIL`: a non-canonical encoding (`p ≤ y`) was accepted
  */
 export const ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: i32 = 9
 export const ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: i32 = 10
-export const ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL_PAIR: i32 = 11
index 82f42c8906961d46785c51d5cfc36316b19ddf3d..4a4d2c80ccdec2f4ee8a78a043258e729d59bedf 100644 (file)
@@ -6,10 +6,10 @@ import { crypto_derive, } from './crypto_derive'
 import { crypto_sign, } from './crypto_sign'
 import { crypto_verify_decodepubkey, crypto_verify_donna, crypto_verify_sodium, } from './crypto_verify'
 import { raise, } from './env'
-import { BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_UNKNOWN, } from './errors'
+import { BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_UNKNOWN, } from './errors'
 import './tests'
 
-export { BLOCKHASH_BYTELENGTH, BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE as ERROR_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR as ERROR_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS as ERROR_SELFTEST_XPASS, ERROR_UNKNOWN, KEY_BYTELENGTH, MAX_MESSAGE_BYTELENGTH, MAX_VERIFY_BLOCKS, MAX_VERIFY_BLOCKS_BYTELENGTH, SIGNATURE_BYTELENGTH }
+export { BLOCKHASH_BYTELENGTH, BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, ERROR_UNKNOWN, KEY_BYTELENGTH, MAX_MESSAGE_BYTELENGTH, MAX_VERIFY_BLOCKS, MAX_VERIFY_BLOCKS_BYTELENGTH, SIGNATURE_BYTELENGTH }
 
 // Static I/O buffers
 const INPUT_MSG = new StaticArray<u8>(MAX_MESSAGE_BYTELENGTH)
index 0175179d10c9a3e6390a05cc6718fded2bb69dbd..ad69e0b70e77497896b6aee695fe191621744f16 100644 (file)
@@ -5,36 +5,21 @@ import { KEY_BYTELENGTH } from './constants'
 import { ge_is_canonical } from './ed25519/ge'
 import { equalbytes } from './ed25519/utils'
 import { raise, } from './env'
-import { ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL_PAIR, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS } from './errors'
+import { ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, } from './errors'
 
 /**
- * Tests run on initialization to ensure build is correct.
+ * Build guards, run from the module's start function. A failure aborts
+ * instantiation, so a build that would quietly accept too much cannot be
+ * imported at all.
  *
  * Failures report a code and two integers rather than a message: building the
  * message here would pull String#join and the whole itoa path into the module
- * for a path that runs once and then traps. The host reconstructs the text
- * from `vector` and `detail` — see `src/lib/errors.ts`.
+ * for a path that runs once and then traps. The integers describe the failing
+ * input completely, and the host rebuilds the bytes from them — see
+ * `src/lib/errors.ts`, which must mirror every vector and case defined here.
  */
-function xpass_equalbytes (vector: i32, expected: StaticArray<u8>, actual: StaticArray<u8>, line: i32 = 0): void {
-       if (!equalbytes(expected, actual, KEY_BYTELENGTH)) {
-               raise(ERROR_EQUALBYTES_SELFTEST_XPASS, vector, 0, line)
-       }
-}
-
-function xfail_equalbytes_one (vector: i32, position: i32, mask: i32, expected: StaticArray<u8>, actual: StaticArray<u8>, line: i32 = 0): void {
-       if (equalbytes(expected, actual, KEY_BYTELENGTH)) {
-               raise(ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, vector, (position << 8) | mask, line)
-       }
-}
-
-function xfail_equalbytes_pair (vector: i32, i: i32, j: i32, expected: StaticArray<u8>, actual: StaticArray<u8>, line: i32 = 0): void {
-       if (equalbytes(expected, actual, KEY_BYTELENGTH)) {
-               raise(ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, vector, (i << 8) | j, line)
-       }
-}
 
 /**
- * equalbytes must report "unequal" for every difference regardless of shape
  * - `zeros`: lower boundary with every bit cleared
  * - `ones`: upper boundary with every bit set
  * - `spread`: all bytes distinct from each other and setting each bit to 0 or 1
@@ -49,20 +34,41 @@ for (let i = 0; i < KEY_BYTELENGTH; i++) {
 
 const actual = new StaticArray<u8>(KEY_BYTELENGTH)
 
-// Vector index is the error detail: 0 zeros, 1 ones, 2 spread
+/**
+ * `equalbytes` must report "unequal" for every difference regardless of shape.
+ * Vector index is the error detail: 0 zeros, 1 ones, 2 spread.
+ */
+function xpass_equalbytes (vector: i32, expected: StaticArray<u8>): void {
+       if (!equalbytes(expected, actual, KEY_BYTELENGTH)) {
+               raise(ERROR_EQUALBYTES_SELFTEST_XPASS, vector, 0)
+       }
+}
+
+function xfail_equalbytes_one (vector: i32, position: i32, mask: i32, expected: StaticArray<u8>): void {
+       if (equalbytes(expected, actual, KEY_BYTELENGTH)) {
+               raise(ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, vector, (position << 8) | mask)
+       }
+}
+
+function xfail_equalbytes_pair (vector: i32, i: i32, j: i32, expected: StaticArray<u8>): void {
+       if (equalbytes(expected, actual, KEY_BYTELENGTH)) {
+               raise(ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, vector, (i << 8) | j)
+       }
+}
+
 const expecteds = [zeros, ones, spread,]
 
 for (let v = 0; v < expecteds.length; v++) {
        const expected = expecteds[v]
        memory.copy(changetype<usize>(actual), changetype<usize>(expected), KEY_BYTELENGTH)
-       xpass_equalbytes(v, expected, actual)
+       xpass_equalbytes(v, expected)
 
        for (let i = 0; i < KEY_BYTELENGTH; i++) {
 
                // verify any individual bit difference fails
                for (let j = 1; j < 256; j++) {
                        actual[i] ^= u8(j)
-                       xfail_equalbytes_one(v, i, j, expected, actual)
+                       xfail_equalbytes_one(v, i, j, expected)
                        actual[i] = expected[i]
                }
 
@@ -71,69 +77,94 @@ for (let v = 0; v < expecteds.length; v++) {
                for (let j = i + 1; j < KEY_BYTELENGTH; j++) {
                        actual[i] ^= 128
                        actual[j] ^= 128
-                       xfail_equalbytes_pair(v, i, j, expected, actual)
+                       xfail_equalbytes_pair(v, i, j, expected)
                        actual[i] = expected[i]
                        actual[j] = expected[j]
                }
        }
 }
 
-function xpass_ge_is_canonical (vector: i32, data: StaticArray<u8>, line: i32 = 0): void {
-       if (ge_is_canonical(data) != 0) {
-               raise(ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, vector, 0, line)
-       }
-}
+/**
+ * `ge_is_canonical` must accept every encoding whose `y`, the low 255 bits, is
+ * below `p = 2²⁵⁵ - 19`, and reject the 19 values from `p` to `2²⁵⁵ - 1`,
+ * whatever the sign bit. Those 19 share every bit above byte 0, so byte 0
+ * decides only when the 247 bits above it are all set, and those bits decide
+ * otherwise. The cases enumerate both sides of that boundary.
+ *
+ * A case packs into one integer, which is also its error detail, so the host
+ * can rebuild the exact bytes that failed:
+ * - bits 0-7: byte 0
+ * - bit 8: the sign bit, bit 255
+ * - bits 9-10: bits 8 to 254 as one of the `GE_*` patterns below
+ * - bits 11-15 and 16-20: up to two byte positions in [1, 31] to flip, 0 for none
+ * - bits 21-23: the bit flipped at those positions
+ */
+const GE_MAX: i32 = 0 // all set, as in `p`
+const GE_ZEROS: i32 = 1 // all clear
+const GE_SPREAD: i32 = 2 // the bytes of `spread`
+const GE_TOP: i32 = 3 // byte 31 set, bytes 1 to 30 clear
 
-function xfail_ge_is_canonical (vector: i32, position: i32, t: i32, data: StaticArray<u8>, line: i32 = 0): void {
-       if (ge_is_canonical(data) != -1) {
-               raise(ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, vector, (position << 8) | t, line)
-       }
+function ge_case (low: i32, sign: i32, high: i32, i: i32 = 0, j: i32 = 0, bit: i32 = 0): i32 {
+       return low | (sign << 8) | (high << 9) | (i << 11) | (j << 16) | (bit << 21)
 }
 
-function xfail_ge_is_canonical_pair (vector: i32, i: i32, j: i32, data: StaticArray<u8>, line: i32 = 0): void {
-       if (ge_is_canonical(data) != -1) {
-               raise(ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL_PAIR, vector, (i << 8) | j, line)
+function check_ge_is_canonical (c: i32, canonical: bool): void {
+       const high = (c >> 9) & 3
+       for (let k = 1; k < KEY_BYTELENGTH; k++) {
+               actual[k] = high == GE_MAX ? 0xff : high == GE_SPREAD ? spread[k] : 0
+       }
+       actual[31] = high == GE_TOP ? 0x7f : actual[31] & 0x7f
+       actual[31] |= u8(((c >> 8) & 1) << 7)
+       actual[0] = u8(c)
+
+       const i = (c >> 11) & 31
+       const j = (c >> 16) & 31
+       const flip = u8(<i32>1 << ((c >> 21) & 7))
+       if (i != 0) actual[i] ^= flip
+       if (j != 0) actual[j] ^= flip
+
+       const result = ge_is_canonical(actual)
+       if (canonical && result != 0) {
+               raise(ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, c, result)
+       }
+       if (!canonical && result != -1) {
+               raise(ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, c, result)
        }
 }
 
-/**
- * ge_is_canonical must report "canonical" for every `s` less than `p` and
- * "non-canonical" for every `s` equal to or greater than `p`.
- */
-memory.copy(changetype<usize>(actual), changetype<usize>(zeros), KEY_BYTELENGTH)
-xpass_ge_is_canonical(0, actual, 104)
-
-memory.copy(changetype<usize>(actual), changetype<usize>(ones), KEY_BYTELENGTH)
-xfail_ge_is_canonical(1, 31, 0, actual, 107)
+for (let sign = 0; sign < 2; sign++) {
 
-// verify all 19 non-canonical encodings fail
-for (let i = 1; i <= 19; i++) {
-       actual[0] = u8(0x100 - i)
-       xfail_ge_is_canonical(1, 0, i, actual, 112)
-}
+       // Bits 8 to 254 all set: byte 0 alone decides, so try all 256 values. The 19
+       // from 0xed are `p` to `2²⁵⁵ - 1`, the only non-canonical encodings.
+       for (let low = 0; low < 256; low++) {
+               check_ge_is_canonical(ge_case(low, sign, GE_MAX), low < 0xed)
+       }
 
-// verify canonical encodings per byte
-for (let v = 0; v < expecteds.length; v++) {
-       const expected = expecteds[v]
-       memory.copy(changetype<usize>(actual), changetype<usize>(expected), KEY_BYTELENGTH)
-       for (let i = 0; i < KEY_BYTELENGTH; i++) {
+       // Clearing any one of those 247 bits puts `y` below `p` whatever byte 0 is.
+       // Checked at both ends of the byte 0 values that would otherwise be
+       // rejected, this catches a loop bound or mask that skips a byte or a bit.
+       for (let i = 1; i < 32; i++) {
+               for (let bit = 0; bit < (i < 31 ? 8 : 7); bit++) {
+                       check_ge_is_canonical(ge_case(0xed, sign, GE_MAX, i, 0, bit), true)
+                       check_ge_is_canonical(ge_case(0xff, sign, GE_MAX, i, 0, bit), true)
+               }
+       }
 
-               for (let j = 1; j < 256; j++) {
-                       actual[i] ^= u8(j)
-                       if (i === 0) actual[i] &= 0xec
-                       xpass_ge_is_canonical(v, actual, 124)
-                       actual[i] = expected[i]
+       // Clearing the same bit at two positions. An accumulator built with `^=`
+       // rather than `|=` cancels here and nowhere else.
+       for (let i = 1; i < 32; i++) {
+               for (let j = i + 1; j < 32; j++) {
+                       check_ge_is_canonical(ge_case(0xed, sign, GE_MAX, i, j), true)
+                       check_ge_is_canonical(ge_case(0xff, sign, GE_MAX, i, j), true)
                }
+       }
 
-               // verify |= was not replaced by ^= or += due to a typo
-               // invisible to single byte checks, caught only by comparing byte pairs
-               for (let j = i + 1; j < KEY_BYTELENGTH; j++) {
-                       actual[i] ^= 128
-                       actual[j] ^= 128
-                       if (i === 0) actual[i] &= 0xec
-                       xpass_ge_is_canonical(v, actual, 134)
-                       actual[i] = expected[i]
-                       actual[j] = expected[j]
+       // Far from `p`, every byte 0 is canonical. `GE_TOP` is the shape that an
+       // accumulator testing for 0x00 instead of 0xff would reject, and `GE_ZEROS`
+       // catches `c | d` in place of `c & d`.
+       for (let high = GE_ZEROS; high <= GE_TOP; high++) {
+               for (let low = 0; low < 256; low++) {
+                       check_ge_is_canonical(ge_case(low, sign, high), true)
                }
        }
 }
index d62f91a1c0f14f3cf1875146a872bbd73573f895..80217ec83cdeb5a40c12fecea3db3b5d7320a511 100644 (file)
@@ -13,8 +13,8 @@ Object.defineProperty(Nano25519WasmError, 'name', { value: 'Nano25519WasmError'
 /**
  * Message text for the codes in `src/assembly/errors.ts`. The numbers are the
  * contract between the two files; `wasm.ts` asserts after instantiation that
- * every `ERROR_*` global the module exports still matches the key used here,
- * so the two cannot drift silently.
+ * the `ERROR_*` globals the module exports and the keys used here are the same
+ * set with the same values, so the two cannot drift silently.
  *
  * The table is keyed by number rather than read from the module because the
  * handler has to exist *before* instantiation: the guards run in the start
@@ -32,45 +32,86 @@ export const errorCodes: Record<string, number> = {
        ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: 8,
        ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: 9,
        ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: 10,
-       ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL_PAIR: 11
 }
 
-const VECTORS = ['zeros', 'ones', 'spread']
-
 /** Buffer ids from `src/assembly/errors.ts`, in value order. */
 const BUFFERS = ['INPUT_MSG', 'INPUT_PRV', 'INPUT_PUB', 'INPUT_SIG', 'OUTPUT_DERIVE', 'OUTPUT_SIGN', 'OUTPUT_VERIFY']
 
 /**
- * Rebuilds a self-test vector. These are the same three definitions as
- * `src/assembly/tests.ts`; keeping them here is what lets the host report the
- * failing bytes without the module ever formatting a string.
+ * Everything below rebuilds a failing self-test input from the integers the
+ * module reported. It mirrors `src/assembly/tests.ts` definition for
+ * definition; that is what lets the host print the failing bytes without the
+ * module ever formatting a string.
  */
-function vector (index: number, length: number): number[] {
+const ENCODING_BYTELENGTH = 32
+
+const hex = (n: number): string => n.toString(16).padStart(2, '0')
+
+/** `spread` from `tests.ts`: 32 distinct bytes balancing every bit position. */
+const spread = (i: number): number => (i * 37 + 11) & 0xff
+
+/** The `equalbytes` vectors, by index. */
+const VECTORS = ['zeros', 'ones', 'spread']
+
+function vector (index: number): number[] {
        const bytes: number[] = []
-       for (let i = 0; i < length; i++) {
-               bytes[i] = index === 0 ? 0 : index === 1 ? 255 : (i * 37 + 11) & 0xff
+       for (let i = 0; i < ENCODING_BYTELENGTH; i++) {
+               bytes[i] = index === 0 ? 0 : index === 1 ? 255 : spread(i)
        }
        return bytes
 }
 
-function selftest (code: number, line: number, v: number, detail: number, length: number): string {
+function equalbytesFailure (code: number, v: number, detail: number): string {
        const name = VECTORS[v] ?? `vector ${v}`
-       const expected = vector(v, length)
-       const actual = vector(v, length)
-       if (code === errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE || code === errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL) {
+       const expected = vector(v)
+       const actual = vector(v)
+       if (code === errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE) {
                const position = (detail >> 8) & 0xff
                const mask = detail & 0xff
                actual[position] ^= mask
-               return `line ${line}: code ${code} build error from "${name}": expected fail [${expected}]; actual pass [${actual}] (byte ${position} ^ 0x${mask.toString(16).padStart(2, '0')})`
+               return `equalbytes build error from "${name}": expected fail [${expected}]; actual pass [${actual}] (byte ${position} ^ 0x${hex(mask)})`
        }
-       if (code === errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR || code === errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL_PAIR) {
+       if (code === errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR) {
                const i = (detail >> 8) & 0xff
                const j = detail & 0xff
                actual[i] ^= 0x80
                actual[j] ^= 0x80
-               return `line ${line}: code ${code} build error from "${name}": expected fail [${expected}]; actual pass [${actual}] (bytes ${i} and ${j} ^ 0x80)`
+               return `equalbytes build error from "${name}": expected fail [${expected}]; actual pass [${actual}] (bytes ${i} and ${j} ^ 0x80)`
        }
-       return `line ${line}: code ${code} build error from "${name}": expected pass [${expected}]; actual fail`
+       return `equalbytes build error from "${name}": expected pass [${expected}]; actual fail`
+}
+
+/** The `ge_is_canonical` patterns for bits 8 to 254, by `GE_*` value. */
+const HIGH = ['max', 'zeros', 'spread', 'top']
+
+/**
+ * Rebuilds the 32 bytes of a packed `ge_is_canonical` case. Mirrors
+ * `check_ge_is_canonical` in `tests.ts`.
+ */
+function canonicalCase (c: number): number[] {
+       const high = (c >> 9) & 3
+       const bytes: number[] = new Array(ENCODING_BYTELENGTH).fill(0)
+       for (let k = 1; k < ENCODING_BYTELENGTH; k++) {
+               bytes[k] = high === 0 ? 0xff : high === 2 ? spread(k) : 0
+       }
+       bytes[31] = high === 3 ? 0x7f : bytes[31] & 0x7f
+       bytes[31] |= ((c >> 8) & 1) << 7
+       bytes[0] = c & 0xff
+
+       const i = (c >> 11) & 31
+       const j = (c >> 16) & 31
+       const flip = 1 << ((c >> 21) & 7)
+       if (i !== 0) bytes[i] ^= flip
+       if (j !== 0) bytes[j] ^= flip
+       return bytes
+}
+
+function canonicalFailure (code: number, c: number, result: number): string {
+       const expected = code === errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XPASS ? 'canonical' : 'non-canonical'
+       const i = (c >> 11) & 31
+       const j = (c >> 16) & 31
+       const flipped = i === 0 ? '' : `, bit ${(c >> 21) & 7} flipped at byte ${i}${j === 0 ? '' : ` and ${j}`}`
+       return `ge_is_canonical build error from "${HIGH[(c >> 9) & 3]}": expected ${expected} [${canonicalCase(c)}]; actual returned ${result} (byte 0 = 0x${hex(c & 0xff)}, sign ${(c >> 8) & 1}${flipped})`
 }
 
 /**
@@ -82,7 +123,7 @@ function selftest (code: number, line: number, v: number, detail: number, length
 function describe (code: number, line: number, detail: number, context: number): string {
        switch (code) {
                case errorCodes.ERROR_INVALID_PUBLIC_KEY:
-                       return `Invalid public key ${line} ${detail} ${context}`
+                       return 'Invalid public key'
                case errorCodes.ERROR_INVALID_MESSAGE_LENGTH:
                        return `Invalid message length: ${detail} is not in [0, ${context}]`
                case errorCodes.ERROR_INVALID_BLOCK_COUNT:
@@ -94,10 +135,10 @@ function describe (code: number, line: number, detail: number, context: number):
                case errorCodes.ERROR_EQUALBYTES_SELFTEST_XPASS:
                case errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE:
                case errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR:
+                       return equalbytesFailure(code, detail, context)
                case errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XPASS:
                case errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL:
-               case errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL_PAIR:
-                       return selftest(code, line, detail, context, 32)
+                       return canonicalFailure(code, detail, context)
                default:
                        return `Unrecognized wasm abort (code ${code}, a ${detail}, b ${context}), row ${line}`
        }
index 9d5578eb851bd0503c5e43c90902c2f9cca634e5..5ccc6f00f09ecb0cf6c044371fc28f9cc90deb0f 100644 (file)
@@ -37,9 +37,11 @@ type Exports = WebAssembly.Instance['exports'] & {
        ERROR_INVALID_BLOCK_COUNT: WebAssembly.Global<'i32'>
        ERROR_INVALID_MESSAGE_LENGTH: WebAssembly.Global<'i32'>
        ERROR_INVALID_PUBLIC_KEY: WebAssembly.Global<'i32'>
-       ERROR_SELFTEST_XFAIL_ONE: WebAssembly.Global<'i32'>
-       ERROR_SELFTEST_XFAIL_PAIR: WebAssembly.Global<'i32'>
-       ERROR_SELFTEST_XPASS: WebAssembly.Global<'i32'>
+       ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE: WebAssembly.Global<'i32'>
+       ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: WebAssembly.Global<'i32'>
+       ERROR_EQUALBYTES_SELFTEST_XPASS: WebAssembly.Global<'i32'>
+       ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: WebAssembly.Global<'i32'>
+       ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: WebAssembly.Global<'i32'>
        ERROR_UNKNOWN: WebAssembly.Global<'i32'>
 }
 
@@ -71,18 +73,23 @@ const exports = instance.exports as Exports
 /**
  * The error codes are a contract between `src/assembly/errors.ts` and
  * `src/lib/errors.ts`. The host table cannot be read from the module, because
- * the handler has to exist before instantiation, so it is checked that it
- * matches against the module here instead.
+ * the handler has to exist before instantiation, so it is checked against the
+ * module here instead, in both directions: a code the host names must exist in
+ * the module with the same value, and a code the module exports must have host
+ * text, or its failures would surface as "Unrecognized wasm abort".
  */
 for (const errorCode of Object.keys(errorCodes)) {
-       if (errorCode.startsWith('ERROR_')) {
-               const wasmErrorCode = exports[errorCode]
-               if (wasmErrorCode == null || !('value' in wasmErrorCode)) {
-                       throw new Nano25519TypeError(`Missing WASM error code ${errorCode}`)
-               }
-               if (wasmErrorCode.value !== errorCodes[errorCode]) {
-                       throw new Nano25519TypeError(`Error code ${errorCode} is ${wasmErrorCode.value} in wasm, ${(errorCodes as Record<string, unknown>)[errorCode]} in host`)
-               }
+       const wasmErrorCode = exports[errorCode]
+       if (wasmErrorCode == null || !('value' in wasmErrorCode)) {
+               throw new Nano25519TypeError(`Missing WASM error code ${errorCode}`)
+       }
+       if (wasmErrorCode.value !== errorCodes[errorCode]) {
+               throw new Nano25519TypeError(`Error code ${errorCode} is ${wasmErrorCode.value} in wasm, ${errorCodes[errorCode]} in host`)
+       }
+}
+for (const errorCode of Object.keys(exports)) {
+       if (errorCode.startsWith('ERROR_') && !(errorCode in errorCodes)) {
+               throw new Nano25519TypeError(`Missing host error code ${errorCode}`)
        }
 }
 
diff --git a/test/mutants.mjs b/test/mutants.mjs
new file mode 100644 (file)
index 0000000..45a8343
--- /dev/null
@@ -0,0 +1,139 @@
+//! SPDX-FileCopyrightText: 2026 Chris Duncan <chris@codecow.com>
+//! SPDX-License-Identifier: GPL-3.0-or-later
+
+/**
+ * Mutation tests for the start-function guards in `src/assembly/tests.ts`.
+ *
+ * Each mutant is a copy of the module with one historical or plausible defect
+ * in a guarded function. The guard holds if that copy refuses to instantiate
+ * with one of its own self-test codes. A mutant that loads, or that fails some
+ * other way, means the guard no longer covers that defect, and the suite would
+ * stay green on a build that quietly accepts too much.
+ *
+ * Every copy is compiled from `build/mutants/` with the project's own
+ * `asconfig.json`, and fails through the real host handler in
+ * `src/lib/errors.ts`, so the messages it prints are the ones a user would see.
+ */
+
+import { execFile } from 'node:child_process'
+import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { availableParallelism } from 'node:os'
+import { promisify } from 'node:util'
+import { abort } from '../src/lib/errors.ts'
+
+const exec = promisify(execFile)
+const root = new URL('../', import.meta.url)
+const work = new URL('build/mutants/', root)
+const asc = new URL('node_modules/assemblyscript/bin/asc.js', root).pathname
+
+const EQUALBYTES = { fn: 'equalbytes', file: 'src/assembly/ed25519/utils.ts', codes: 'ERROR_EQUALBYTES_SELFTEST_' }
+const GE_IS_CANONICAL = { fn: 'ge_is_canonical', file: 'src/assembly/ed25519/ge.ts', codes: 'ERROR_GE_IS_CANONICAL_SELFTEST_' }
+
+/** `from` must occur exactly once inside the named function. */
+const mutants = [
+       { guard: EQUALBYTES, from: 'b |= f[i] ^ g[i]', to: 'b ^= f[i] ^ g[i]', why: 'accumulates with ^=, so equal deltas cancel' },
+       { guard: EQUALBYTES, from: 'b |= f[i] ^ g[i]', to: 'b += f[i] ^ g[i]', why: 'accumulates with +=, so 0x80 pairs cancel in the byte mask' },
+       { guard: EQUALBYTES, from: 'let b: i32 = 0', to: 'let b: u8 = 0', why: 'narrows the accumulator to u8, the historical one-bit-per-byte bug' },
+       { guard: EQUALBYTES, from: 'i < n;', to: 'i < n - 1;', why: 'never compares the last byte' },
+       { guard: GE_IS_CANONICAL, from: 'c |= s[i] ^ 0xff', to: 'c |= s[i]', why: 'tests bytes 1 to 30 for 0x00 instead of 0xff (fc46ae5)' },
+       { guard: GE_IS_CANONICAL, from: 'c |= s[i] ^ 0xff', to: 'c ^= s[i] ^ 0xff', why: 'accumulates with ^=, so equal deltas cancel' },
+       { guard: GE_IS_CANONICAL, from: 'i > 0;', to: 'i > 1;', why: 'never checks byte 1' },
+       { guard: GE_IS_CANONICAL, from: '(s[31] & 0x7f) ^ 0x7f', to: 's[31] ^ 0x7f', why: 'does not mask the sign bit' },
+       { guard: GE_IS_CANONICAL, from: '(0xec - s[0]) >> 8', to: '(0xed - s[0]) >> 8', why: 'accepts p itself' },
+       { guard: GE_IS_CANONICAL, from: 'c & d & 1', to: '(c | d) & 1', why: 'combines its two conditions with | instead of &' },
+]
+
+/** Copies the sources, applies one replacement inside one function, and compiles. */
+async function build (name, mutant) {
+       const dir = new URL(`${name}/`, work)
+       await mkdir(dir, { recursive: true })
+       await cp(new URL('src/', root), new URL('src/', dir), { recursive: true })
+       await cp(new URL('asconfig.json', root), new URL('asconfig.json', dir))
+       if (mutant != null) {
+               const { guard: { fn, file }, from, to } = mutant
+               const path = new URL(file, dir)
+               const source = await readFile(path, 'utf8')
+               const start = source.indexOf(`export function ${fn} (`)
+               const end = source.indexOf('\n}\n', start)
+               const body = source.slice(start, end)
+               if (start < 0 || end < 0 || body.split(from).length !== 2) {
+                       throw new Error(`mutant "${to}" no longer applies: "${from}" must occur once in ${fn}()`)
+               }
+               await writeFile(path, source.slice(0, start) + body.replace(from, to) + source.slice(end))
+       }
+       await exec(process.execPath, [asc, 'src/assembly/index.ts'], { cwd: dir.pathname })
+       return readFile(new URL('build/nano25519.wasm', dir))
+}
+
+/** Instantiates, recording the raw abort as well as the host's message. */
+function load (bytes) {
+       let raised = null
+       const env = {
+               abort (code, line, detail, context) {
+                       raised = { code, detail, context }
+                       return abort(code, line, detail, context)
+               }
+       }
+       try {
+               return { exports: new WebAssembly.Instance(new WebAssembly.Module(bytes), { env }).exports }
+       } catch (err) {
+               return { raised, message: err?.message ?? String(err) }
+       }
+}
+
+/** Runs `fn` over `items` with at most `limit` in flight, keeping order. */
+async function pool (items, limit, fn) {
+       const results = []
+       let next = 0
+       await Promise.all(Array.from({ length: Math.min(limit, items.length) }, async () => {
+               while (next < items.length) {
+                       const i = next++
+                       results[i] = await fn(items[i], i)
+               }
+       }))
+       return results
+}
+
+let passes = 0, failures = 0
+function check (name, test, detail = '') {
+       console.log(`${test ? '\x1b[32mPASS' : '\x1b[31mFAIL'}\x1b[0m: ${name}${detail ? `\n      ${detail}` : ''}`)
+       passes += +test
+       failures += +!test
+}
+
+const p = (1n << 255n) - 19n
+const started = performance.now()
+await rm(work, { recursive: true, force: true })
+try {
+       const [control, ...builds] = await pool([null, ...mutants], availableParallelism(), (m, i) =>
+               build(i === 0 ? 'control' : `mutant-${i}`, m).catch(err => ({ error: err?.stderr || err?.message || String(err) })))
+
+       // The unmodified copy must load, or every result below is meaningless.
+       const base = control.error == null ? load(control) : { message: control.error }
+       check('unmodified module instantiates', base.exports != null, base.message)
+       const names = new Map(Object.entries(base.exports ?? {}).filter(([k]) => k.startsWith('ERROR_')).map(([k, g]) => [g.value, k]))
+
+       for (let i = 0; i < mutants.length && base.exports != null; i++) {
+               const { guard, why } = mutants[i]
+               const result = builds[i].error == null ? load(builds[i]) : { message: `did not compile: ${builds[i].error.trim().split('\n')[0]}` }
+               const code = names.get(result.raised?.code) ?? 'none'
+               let test = result.exports == null && code.startsWith(guard.codes) && result.message.startsWith(`${guard.fn} build error`)
+
+               // The host rebuilds the failing bytes from the reported case. They must be
+               // on the side of `p` that the guard says it expected, or the two files'
+               // definitions of the cases have drifted apart.
+               if (test && guard === GE_IS_CANONICAL) {
+                       const bytes = JSON.parse(result.message.match(/\[[\d,]+\]/)[0])
+                       const y = bytes.reduceRight((n, b) => (n << 8n) | BigInt(b), 0n) & ((1n << 255n) - 1n)
+                       test = (y < p) === result.message.includes('expected canonical')
+               }
+               check(`${guard.fn} guard rejects a build that ${why}`, test, `${code}: ${result.message ?? 'instantiated'}`)
+       }
+} finally {
+       await rm(work, { recursive: true, force: true })
+}
+
+console.log(`${passes} \x1b[32mPASSED\x1b[0m`)
+console.log(`${failures} \x1b[31mFAILED\x1b[0m`)
+console.log(`${mutants.length + 1} builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
+if (failures > 0) process.exit(1)