]> git.codecow.com Git - nano25519.git/commitdiff
Update tests and agent file.
authorChris Duncan <chris@codecow.com>
Fri, 6 Nov 2026 22:38:57 +0000 (14:38 -0800)
committerChris Duncan <chris@codecow.com>
Fri, 6 Nov 2026 22:38:57 +0000 (14:38 -0800)
AGENTS.md
test/arithmetic.mjs
test/module.mjs
test/node.mjs

index 70423739e20c30d5472ea846f1c8932f18c7aeca..28e0e1d804747dfda234a018eb08048c3b377fb6 100644 (file)
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -155,7 +155,8 @@ code is not yet optimized, which is every process's first calls, and nothing
 can clear that object: words of 2³¹ or more on Node, 2³⁰ or more in Chromium.
 Packed as 32-bit words, every such word of the key was left behind; a 16-bit
 value is small on every engine. `setInputPrv` masks each parameter to 16 bits,
-so a caller passing more cannot bleed into the next half. Do not "optimise" the
+so a caller passing more cannot bleed into the next half; `test:module` passes
+wider values and checks the key derived. Do not "optimise" the
 key back onto the word view; `test:heap` fails if anything does.
 
 | Buffer | Purpose |
@@ -640,7 +641,7 @@ 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 **6368, 6368, 6228, 17, 12,
+`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
 prototype and static patches, since frozen intrinsics cannot be patched, but
 keeps the 15 under global replacements. `test:heap` reports SKIP and passes
@@ -791,6 +792,15 @@ built, and both passed the suite as it then stood. `test/node.mjs` now signs a d
 `MAX_VERIFY_BLOCKS` blocks and gives some records the next block's genuine
 signature, which only a record read against its own hash rejects.
 
+**A key that does not decode must not reach the last key's table.** The table
+of odd multiples is module-level and survives the call that built it, and the
+type of `crypto_verify_decodepubkey` only forces the caller to check for
+`null`, not the function to return it. Built to return the stale table instead,
+it passed all seven suites, and a batch under an undecodable key run right after
+one under `IDENTITY` accepted the identity signature on every block: under the
+identity's table `[k]A` is the identity whatever `k` is. `test/node.mjs` now runs
+exactly that sequence and requires every block to be refused.
+
 **Most rejections are decided before the final equation** — a small-order key,
 a non-canonical scalar, a malformed block, or the identity key that pins `R`.
 So `test/node.mjs` also forges signatures that pass every precondition, under a
@@ -914,12 +924,19 @@ skipped byte 31, or bytes 1 to 31, passed every suite.
 
 ### Below the API: `test:module` and `test:arithmetic`
 
-`test:module` builds probes with memory exported and checks three things the
+`test:module` builds probes with memory exported and checks four things the
 public API cannot show: no input-dependent bytes after `clearMemory()` (see
 **Gotchas**), every export leaving its own input buffers zeroed on all eight
-success and throw paths, and `OUTPUT_VERIFY` holding only `0` and `1`. Each has
-a seeded control: `z_0()` dropped from `fe_invert`, and the `INPUT_SIG`
-scrub dropped from the length check in `verify`.
+success and throw paths, `OUTPUT_VERIFY` holding only `0` and `1`, and the ABI's
+own guards. The host validates every index and length before the module sees
+it, so no public call reaches the checks in `setInputMsg`, the three getters,
+and the length and count checks of `sign`, `verify` and `verify_blocks`; with
+bounds checks compiled out they are all that keeps a write inside its buffer.
+Each must accept up to its boundary and refuse one past it on either side, with
+its own code and details, and `setInputPrv` must ignore everything above each
+16-bit half. Each has a seeded control: `z_0()` dropped from `fe_invert`, the
+`INPUT_SIG` scrub dropped from the length check in `verify`, and one probe with
+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
index 57104a6b38822e2ceb7c7e16e003fa18aa25eddc..641f3c36844f355006007f06d9d434702ba9923b 100644 (file)
@@ -40,8 +40,8 @@
  * over it. `fe_invert` is the exception; it writes `out` before its last read
  * of `z`, and no caller passes the same buffer for both.
  *
- * Positive controls: one probe without the `p3_0(r)` that makes `[0]A + [0]B`
- * the identity, and one that recomputes `T` as `X·Y` after the final conversion
+ * Positive controls: one probe whose `p1p1_0` leaves `T = 0`, so `[0]A + [0]B`
+ * is not the identity, and one that recomputes `T` as `X·Y` after the final conversion
  * of the double scalar multiplication, must each be seen, and the second must
  * pass the point comparison while failing the representation check. A third
  * probe drops both canonicity checks and the malformed-point term from each of
index 1f2161eb78c323a5bb67bd333d878dee84a9a179..c63cb654d9dd1c6e2fc980553cb1670732124a53 100644 (file)
@@ -3,7 +3,7 @@
 
 /**
  * Tests that drive the compiled module directly through its integer ABI, below
- * the host layer, for three properties the public API cannot observe.
+ * the host layer, for four properties the public API cannot observe.
  *
  * **No secret residue.** After `derive`, `sign` and a failed `sign`, followed
  * by the `clearMemory()` the host runs on every unlock, linear memory must not
  * buffer is also written past the length the call declares, and every success
  * and throw path is read back before `clearMemory()`.
  *
+ * **Guards at their boundaries.** With bounds checks compiled out, the index
+ * checks in `setInputMsg` and the getters and the length and count checks in
+ * the primitives are all that keep the module inside its buffers, and the host
+ * validates first, so no public call reaches them. Each must accept up to its
+ * boundary and refuse one past it on either side, with its own code and
+ * details. `setInputPrv` must keep each half to 16 bits, so a wider value
+ * cannot bleed into the next half.
+ *
  * Positive controls prove each check can fire: the search finds the public key
  * before `clearMemory()`, the diff sees the public key output, a second probe
  * with `z_0()` removed from `fe_invert` must show residue, a third with
  * the `INPUT_SIG` scrub removed from the length check in `verify` must fail the
- * input check there and nowhere else, and both result values must actually
- * occur.
+ * input check there and nowhere else, a fourth with the `setInputMsg` guard
+ * moved 32 bytes late and the key halves widened to 32 bits must fail both ABI
+ * checks, and both result values must actually occur.
  *
  * Probes are compiled under `build/module/` with the project's own
  * `asconfig.json`, changed only in the copy.
@@ -46,36 +55,46 @@ const root = new URL('../', import.meta.url)
 const work = new URL('build/module/', root)
 const asc = new URL('node_modules/assemblyscript/bin/asc.js', root).pathname
 
-/** The line a dropped scrub removes; `from` must occur once inside `fn`. */
-const DROPPED_SCRUB = { file: 'src/assembly/ed25519/z.ts', fn: 'fe_invert', from: '\n\tz_0()' }
+/** Seeded controls: each `from` must occur once inside its `fn`, and is replaced by `to`, or removed. */
+const DROPPED_SCRUB = [{ file: 'src/assembly/ed25519/z.ts', fn: 'fe_invert', from: '\n\tz_0()' }]
 
 /** A throw-path scrub that only the input-buffer check can see. */
-const DROPPED_INPUT_SCRUB = { file: 'src/assembly/index.ts', fn: 'verify', from: '\n\t\tINPUT_SIG.fill(0)' }
+const DROPPED_INPUT_SCRUB = [{ file: 'src/assembly/index.ts', fn: 'verify', from: '\n\t\tINPUT_SIG.fill(0)' }]
+
+/**
+ * One guard moved past its boundary, and the private key halves widened to 32
+ * bits, which the ABI checks must each see: the first lets `setInputMsg` write
+ * up to 32 bytes past `INPUT_MSG`, and the second lets a half bleed into the next.
+ */
+const LOOSE_ABI = [
+       { file: 'src/assembly/index.ts', fn: 'setInputMsg', from: 'MAX_MESSAGE_BYTELENGTH - 32 < index', to: 'MAX_MESSAGE_BYTELENGTH < index' },
+       { file: 'src/assembly/index.ts', fn: 'setInputPrv', from: 'v0: u16, v1: u16, v2: u16, v3: u16, v4: u16, v5: u16, v6: u16, v7: u16, v8: u16, v9: u16, v10: u16, v11: u16, v12: u16, v13: u16, v14: u16, v15: u16', to: 'v0: u32, v1: u32, v2: u32, v3: u32, v4: u32, v5: u32, v6: u32, v7: u32, v8: u32, v9: u32, v10: u32, v11: u32, v12: u32, v13: u32, v14: u32, v15: u32' },
+]
 
-/** Copies the sources, exports memory, optionally drops one line, and compiles. */
-async function probe (name, drop) {
+/** Copies the sources, exports memory, applies any edits, and compiles. */
+async function probe (name, edits = []) {
        const dir = new URL(`${name}/`, work)
        await mkdir(dir, { recursive: true })
        await cp(new URL('src/', root), new URL('src/', dir), { recursive: true })
        const config = JSON.parse(await readFile(new URL('asconfig.json', root), 'utf8'))
        config.options.noExportMemory = false
        await writeFile(new URL('asconfig.json', dir), JSON.stringify(config, null, '\t'))
-       if (drop != null) {
-               const path = new URL(drop.file, dir)
+       for (const edit of edits) {
+               const path = new URL(edit.file, dir)
                const source = await readFile(path, 'utf8')
-               const start = source.indexOf(`export function ${drop.fn} (`)
+               const start = source.indexOf(`export function ${edit.fn} (`)
                const end = source.indexOf('\n}\n', start)
                const body = source.slice(start, end)
-               if (start < 0 || end < 0 || body.split(drop.from).length !== 2) {
-                       throw new Error(`control no longer applies: "${drop.from.trim()}" must occur once in ${drop.fn}()`)
+               if (start < 0 || end < 0 || body.split(edit.from).length !== 2) {
+                       throw new Error(`control no longer applies: "${edit.from.trim()}" must occur once in ${edit.fn}()`)
                }
-               await writeFile(path, source.slice(0, start) + body.replace(drop.from, '') + source.slice(end))
+               await writeFile(path, source.slice(0, start) + body.replace(edit.from, edit.to ?? '') + source.slice(end))
        }
        await exec(process.execPath, [asc, 'src/assembly/index.ts'], { cwd: dir.pathname })
        return new WebAssembly.Module(await readFile(new URL('build/nano25519.wasm', dir)))
 }
 
-const instance = (mod) => new WebAssembly.Instance(mod, { env: { abort (code) { throw new Error(`wasm abort ${code}`) } } }).exports
+const instance = (mod) => new WebAssembly.Instance(mod, { env: { abort (code, line, a, b) { throw Object.assign(new Error(`wasm abort ${code}`), { abort: [code, a, b] }) } } }).exports
 const words = (b) => Array.from({ length: b.length >> 2 }, (_, i) => new DataView(b.buffer, b.byteOffset).getUint32(4 * i, true))
 /** `setInputPrv` takes the private key as sixteen little-endian 16-bit halves, so the host never holds a word of it. */
 const halves = (b) => Array.from({ length: b.length >> 1 }, (_, i) => b[2 * i] | (b[2 * i + 1] << 8))
@@ -230,6 +249,65 @@ function unscrubbed (mod) {
        return left
 }
 
+/**
+ * Every index and length guard of the ABI, from both sides of its boundary: the
+ * first and last values it accepts and the first it refuses on each side, with
+ * the code and two integers it reports. Bounds checks are compiled out, so these
+ * guards are all that keeps a setter or getter inside its buffer, and the host
+ * validates first, so no public call ever reaches one.
+ */
+function abiGuards (mod) {
+       const x = instance(mod)
+       const g = (name) => x[name].value
+       const [max, blocks] = [g('MAX_MESSAGE_BYTELENGTH'), g('MAX_VERIFY_BLOCKS')]
+       const [index, length, count] = [g('ERROR_INDEX_OUT_OF_RANGE'), g('ERROR_INVALID_MESSAGE_LENGTH'), g('ERROR_INVALID_BLOCK_COUNT')]
+       const prv = keyOf(1)
+       const pub = derive(x, prv)
+       x.clearMemory()
+       const zeros = new Array(8).fill(0)
+       const cases = [
+               ...[[-1, true], [0, false], [max - 32, false], [max - 31, true]].map(([i, refused]) =>
+                       [`setInputMsg(${i})`, () => x.setInputMsg(i, ...zeros), refused ? [index, g('BUFFER_INPUT_MSG'), i] : null]),
+               ...[['getOutputDeriveByte', 'BUFFER_OUTPUT_DERIVE', 32], ['getOutputSignByte', 'BUFFER_OUTPUT_SIGN', 64], ['getOutputVerifyByte', 'BUFFER_OUTPUT_VERIFY', blocks]].flatMap(([fn, buffer, n]) =>
+                       [[-1, true], [0, false], [n - 1, false], [n, true]].map(([i, refused]) => [`${fn}(${i})`, () => x[fn](i), refused ? [index, g(buffer), i] : null])),
+               ...[[-1, true], [0, false], [max, false], [max + 1, true]].flatMap(([n, refused]) => [
+                       [`sign(${n})`, () => { x.setInputPrv(...halves(prv)); x.setInputPub(...words(pub)); x.sign(n) }, refused ? [length, n, max] : null],
+                       [`verify(${n})`, () => x.verify(n), refused ? [length, n, max] : null],
+               ]),
+               ...[[0, true], [1, false], [blocks, false], [blocks + 1, true]].map(([n, refused]) =>
+                       [`verify_blocks(${n})`, () => x.verify_blocks(n), refused ? [count, n, blocks] : null]),
+       ]
+       const wrong = []
+       for (const [name, call, expected] of cases) {
+               let got = null
+               try { call() } catch (err) { got = err?.abort ?? String(err) }
+               x.clearMemory()
+               if (JSON.stringify(got) !== JSON.stringify(expected)) {
+                       wrong.push(`${name}: expected ${expected == null ? 'accepted' : `abort ${expected}`}, got ${got == null ? 'accepted' : `abort ${got}`}`)
+               }
+       }
+       return wrong
+}
+
+/**
+ * `setInputPrv` must keep each half to 16 bits whatever the caller passes above
+ * them, so a wide value cannot bleed into the next half: the key derived must be
+ * the one its low 16 bits describe.
+ */
+function keyHalves (mod) {
+       const x = instance(mod)
+       const prv = keyOf(1)
+       const want = derive(x, prv).join()
+       const wrong = []
+       for (const [name, widen] of [['high bits set', (v) => v | 0xffff0000], ['bit 16 set', (v) => v + 0x10000], ['negative', (v) => v - 0x10000]]) {
+               x.clearMemory()
+               x.setInputPrv(...halves(prv).map(widen))
+               x.derive()
+               if (Array.from({ length: 32 }, (_, i) => x.getOutputDeriveByte(i)).join() !== want) wrong.push(name)
+       }
+       return wrong
+}
+
 let passes = 0
 let failures = 0
 function check (name, test, detail = '') {
@@ -243,10 +321,11 @@ await rm(work, { recursive: true, force: true })
 try {
        // a control that cannot be seeded is a failed check, not a crash, so the
        // residue checks below still run and report
-       const [clean, dropped, droppedInput] = await Promise.all([
+       const [clean, dropped, droppedInput, looseAbi] = await Promise.all([
                probe('clean'),
                probe('dropped-scrub', DROPPED_SCRUB).catch((err) => err),
                probe('dropped-input-scrub', DROPPED_INPUT_SCRUB).catch((err) => err),
+               probe('loose-abi', LOOSE_ABI).catch((err) => err),
        ])
 
        // positive controls: the search and the diff can both fire
@@ -274,6 +353,17 @@ try {
        const left = unscrubbed(clean)
        check(`every export leaves its input buffers zeroed on all ${Object.keys(inputPaths(clean)).length} success and throw paths`, left.length === 0, left.join('; '))
 
+       // index and length guards, and the width of the private key halves
+       const loose = looseAbi instanceof WebAssembly.Module ? { abi: abiGuards(looseAbi), halves: keyHalves(looseAbi) } : null
+       const failed = String(looseAbi?.message ?? looseAbi)
+       check('ABI check sees a setInputMsg guard that accepts an index past the end of INPUT_MSG',
+               loose != null && loose.abi.some(w => w.startsWith('setInputMsg(')), loose == null ? failed : loose.abi.join('; ') || 'nothing seen')
+       check('key half check sees a setInputPrv that takes 32-bit halves', loose != null && loose.halves.length > 0, loose == null ? failed : 'nothing seen')
+       const abi = abiGuards(clean)
+       check('every index and length guard accepts up to its boundary and refuses past it, with its code and details', abi.length === 0, abi.join('; '))
+       const bled = keyHalves(clean)
+       check('setInputPrv keeps each private key half to 16 bits', bled.length === 0, bled.join(', '))
+
        // OUTPUT_VERIFY must only ever hold 0 or 1, across valid, forged, malformed,
        // undecodable and degenerate inputs on both verification paths
        const x = instance(clean)
@@ -324,5 +414,5 @@ try {
 
 console.log(`${passes} \x1b[32mPASSED\x1b[0m`)
 console.log(`${failures} \x1b[31mFAILED\x1b[0m`)
-console.log(`3 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
+console.log(`4 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
 process.exitCode = failures > 0 ? 1 : 0
index d1506906b303fc86e93737f6338444a70e63d82b..cb802aea31f1a50e5f16880c8fd12f40198f92ed 100644 (file)
@@ -266,6 +266,23 @@ check(`verify_blocks rejects R xor mask${test ? '' : ` (failed to reject ${accep
 passes += +test
 failures += +!test
 
+// The table of odd multiples of the key outlives the call that built it, so a
+// key that does not decode must refuse the whole batch rather than reach the
+// table left by the previous one. Under the identity's table [k]A is the identity
+// whatever k is, so the identity signature would verify under any key at all:
+// the stale table turns an undecodable account into one whose every block passes.
+{
+       const undecodable = new Uint8Array(constants.KEY_BYTELENGTH)
+       undecodable[0] = 2
+       const block = { signature: IDENTITY.signatureBytes, hash: new Uint8Array(32) }
+       const warm = attempt(() => verify_blocks(IDENTITY.publicKeyBytes, [block])[0])
+       const stale = attempt(() => verify_blocks(undecodable, [block, block]))
+       test = warm === true && Array.isArray(stale) && stale.join() === 'false,false'
+       check(`verify_blocks refuses every block under a key that does not decode, right after a batch under one that does${test ? '' : ` (warm ${warm}, stale ${stale})`}`, test)
+       passes += +test
+       failures += +!test
+}
+
 // Every rejection asserted above is decided before the final equation: a
 // small-order key, a non-canonical scalar, a malformed block, or the identity
 // key that pins R. Forge signatures that pass the preconditions, under a normal