verify_blocks(pub, blocks) // { hash, signature }[], up to 64 -> boolean[]
```
-Inputs are `Uint8Array`, `ArrayBuffer`, or hex strings. `derive` and `sign`
-**always return a hex string**, unless the optional preallocated output buffer
-is passed as a trailing argument — then the bytes are written there and the
-return is `undefined`.
+Inputs are hex strings or a `Uint8Array` backed by a non-shared `ArrayBuffer`;
+subclasses and views with a `byteOffset` are fine. A bare `ArrayBuffer`, a view
+over a `SharedArrayBuffer` and a `DataView` are rejected with a `TypeError`.
+`derive` and `sign` **always return a hex string**, unless the optional
+preallocated output buffer is passed as a trailing argument — then the bytes
+are written there and the return is `undefined`.
`verify_blocks` is the Nano account-chain case — many block hashes against one
public key. It has vector coverage, but do **not** read that as verified correct
npm test # build, then test/node.mjs little- and big-endian
npm run test:prod # build:prod, then the same suite
npm run test:mutants # guard mutation tests, see Testing; also in prepublishOnly
+npm run test:module # residue and result polarity below the host; also in prepublishOnly
npm run profile # build, then the suite under --cpu-prof into prof/
npm run clean # rm -rf {build,dist}
```
| `test/node.mjs`, `test/vectors.mjs` | Suite, and the vectors it is built from |
| `test/big-endian.mjs` | Preloaded by `test:be` to force the big-endian marshalling path |
| `test/mutants.mjs` | Mutation tests for the start-function guards |
+| `test/module.mjs` | Drives the compiled module directly: secret residue by memory diff, and `OUTPUT_VERIFY` polarity |
| `test/vectors/python_ed25519_blake2b.ts` | The bulk vector set, split out to stop crashing the IDE |
| `test/index.html` | Browser test and benchmark page |
of a 39 µs signature.
**`OUTPUT_VERIFY` is fail-closed at every point it could be read.** It is zero
-at instantiation, filled with `0` again at the top of `verify_blocks` before the
-count check, and again by `clearMemory()` on every `Mutex.unlock()`. `1` means verified, so a buffer
-that was never written must read as zero.
+at instantiation, filled with `0` again at the top of `verify` and of
+`verify_blocks` before the count check, and again by `clearMemory()` on every
+`Mutex.unlock()`. `1` means verified, so a buffer that was never written must
+read as zero. The host reads it with a strict `=== 1`. No black-box test can
+tell that from `!== 0`, because the module only ever writes `0` or `1`; that
+property is what makes the strict comparison redundant, so `test:module` asserts
+it directly. Keep both.
## Wasm error reporting
own table because the handler must exist before instantiation, and `wasm.ts`
checks after instantiation that the table and the module's exported `ERROR_*`
globals match **in both directions**: a code without host text would surface as
-"Unrecognized wasm abort". `ERROR_BYTE_OUT_OF_RANGE` is currently defined but
-never raised.
+"Unrecognized wasm abort". Codes are numbered sequentially from 0. Removing one
+means renumbering every code after it in both files at once; a mismatch makes
+the module refuse to load rather than misreport, because of that check.
An inner primitive returns a code instead of raising when the caller has cleanup
to do first: `crypto_sign` returns `i32`, so `sign()` scrubs `OUTPUT_SIGN` before
leaving it stale, but note *stale* means smaller than the statics. Too large is
cheap; too small grows memory at init.
-Memory growth *during* a call would detach every `Uint8Array` view the host
-holds, so keeping call paths allocation-free is a correctness requirement, not
-just a memory one.
+The host holds no views of wasm memory, so growth can no longer detach one; it
+would still be a defect, because nothing on a call path is meant to allocate,
+and under the stub runtime every allocation is a permanent leak.
## Gotchas
field elements a byte search could never have named — and, after 53a72ed,
verified gone: memory after `derive` and after `sign` was byte-identical across
different keys on 2026-10-06, and again on 2026-10-09 after 3c9d8e6 moved the
-point temporaries into shared buffers. Re-run it whenever scratch buffers move.
+point temporaries into shared buffers. **`npm run test:module` now runs this diff**
+after `derive`, `sign` and a failed `sign`, and proves it can fire by building a
+second probe with `clear_t()` removed from `crypto_derive`: that leaves 248
+input-dependent bytes, which the diff sees and the representation search does
+not. Nothing else in the project notices a dropped scrub.
**Shared temporaries are safe only while nothing holds a value across a call
that uses them.** `t_fe_0` to `t_fe_6` in `src/assembly/ed25519/t.ts` are one
uses them for `[r]B`. That is correct today only because `crypto_sign` keeps
nothing in them across that call. A value parked in a `t_` buffer across any
call that also takes `t_` buffers is silently clobbered, so pass them down
-explicitly and keep each one's use between calls. The callee that finishes a
-secret computation clears them: `ge_scalarmult_base_tobytes` zeroes all seven
-before it returns.
+explicitly and keep each one's use between calls. Each `crypto_` function
+clears all seven with `clear_t()` when it is done with them, including on its
+early-return paths; the lower functions that use them, such as
+`ge_scalarmult_base_tobytes`, do not.
**Establish fail-closed defaults before the first early exit.** `verify_blocks`
runs `OUTPUT_VERIFY.fill(0)` *before* validating the public key, so a batch
## Testing
`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.
+Current state is **6260 passing, 0 failing** in each. There is no expected
+failure — if anything fails, it is a regression. The suite sets
+`process.exitCode` rather than calling `process.exit()`, which could cut off
+output still draining to a pipe, and exits `1` for any failures, since an exit
+status is only 8 bits wide.
`equalbytes`, `ge_is_canonical` and `fe_iszero` additionally self-test in the
module's **start function**, in `src/assembly/tests.ts`, imported by `index.ts`
in the batch — the bug this feature has actually shipped is reporting invalid
signatures as valid, which an all-valid batch cannot catch.
+**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
+normal key and a 32-byte hash: every single-bit corruption of a valid signature,
+a valid signature over a different hash and under a different key, and a full
+batch with every fifth block corrupted, which must reject exactly those blocks.
+Each of `verify` and `verify_blocks` must reject all of them, and the
+unmodified signature must verify. Without these, an always-accepting equation in
+`verify()` failed only the two 64 KiB message sweeps, and an always-accepting
+`crypto_verify_donna` failed only the canary.
+
`PROBLEM_VECTOR` is a live cemented Nano block from a small-order account
(`nano_11a11…`, public key `0100…00`) that network consensus accepted and strict
Ed25519 rejects. It is now asserted **twice**, once per path: `verify()` must
export const ERROR_INVALID_MESSAGE_LENGTH: i32 = 2
export const ERROR_INVALID_BLOCK_COUNT: i32 = 3
/**
- * Raised by the byte accessors. `a` is the buffer id below, `b` the offending
- * index or value. The buffer id is what identifies the site: `line` cannot,
- * because AssemblyScript fixes it at the `throw` inside `raise`, so every
- * coded abort reports that one line. `line` is only meaningful for
+ * Raised by `setInputMsg` and the output getters. `a` is the buffer id below,
+ * `b` the offending index. The buffer id is what identifies the site: `line`
+ * cannot, because AssemblyScript fixes it at the `throw` inside `raise`, so
+ * every coded abort reports that one line. `line` is only meaningful for
* `ERROR_UNKNOWN`, where it points into the AssemblyScript runtime.
*/
export const ERROR_INDEX_OUT_OF_RANGE: i32 = 4
-export const ERROR_BYTE_OUT_OF_RANGE: i32 = 5
export const BUFFER_INPUT_MSG: i32 = 0
export const BUFFER_INPUT_PRV: i32 = 1
* - `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
+export const ERROR_EQUALBYTES_SELFTEST_XPASS: i32 = 5
+export const ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE: i32 = 6
+export const ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: i32 = 7
/**
* `ge_is_canonical` start-function guard in `tests.ts`. `a` is the packed case
* - `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_XPASS: i32 = 8
+export const ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: i32 = 9
/**
* `fe_iszero` start-function guard in `tests.ts`. `a` is the packed case that
* - `XPASS`: a value that is 0 mod `p` was reported nonzero
* - `XFAIL`: a nonzero value was reported zero
*/
-export const ERROR_FE_ISZERO_SELFTEST_XPASS: i32 = 11
-export const ERROR_FE_ISZERO_SELFTEST_XFAIL: i32 = 12
+export const ERROR_FE_ISZERO_SELFTEST_XPASS: i32 = 10
+export const ERROR_FE_ISZERO_SELFTEST_XFAIL: i32 = 11
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_FE_ISZERO_SELFTEST_XFAIL, ERROR_FE_ISZERO_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 { BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_FE_ISZERO_SELFTEST_XFAIL, ERROR_FE_ISZERO_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, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_FE_ISZERO_SELFTEST_XFAIL, ERROR_FE_ISZERO_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 }
+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_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_FE_ISZERO_SELFTEST_XFAIL, ERROR_FE_ISZERO_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)
// Clear signature output buffer if signing failed
if (result != 0) {
OUTPUT_SIGN.fill(0)
- raise(ERROR_INVALID_PUBLIC_KEY, result)
+ raise(ERROR_INVALID_PUBLIC_KEY)
}
}
ERROR_INVALID_MESSAGE_LENGTH: 2,
ERROR_INVALID_BLOCK_COUNT: 3,
ERROR_INDEX_OUT_OF_RANGE: 4,
- ERROR_BYTE_OUT_OF_RANGE: 5,
- ERROR_EQUALBYTES_SELFTEST_XPASS: 6,
- ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE: 7,
- ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: 8,
- ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: 9,
- ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: 10,
- ERROR_FE_ISZERO_SELFTEST_XPASS: 11,
- ERROR_FE_ISZERO_SELFTEST_XFAIL: 12,
+ ERROR_EQUALBYTES_SELFTEST_XPASS: 5,
+ ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE: 6,
+ ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: 7,
+ ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: 8,
+ ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: 9,
+ ERROR_FE_ISZERO_SELFTEST_XPASS: 10,
+ ERROR_FE_ISZERO_SELFTEST_XFAIL: 11,
}
/** Buffer ids from `src/assembly/errors.ts`, in value order. */
return `Invalid block count: ${detail} is not in [1, ${context}]`
case errorCodes.ERROR_INDEX_OUT_OF_RANGE:
return `Buffer index out of range for ${BUFFERS[detail] ?? `buffer ${detail}`}: ${context}`
- case errorCodes.ERROR_BYTE_OUT_OF_RANGE:
- return `Byte value out of range for ${BUFFERS[detail] ?? `buffer ${detail}`}: ${context} is not in [0, 255]`
case errorCodes.ERROR_EQUALBYTES_SELFTEST_XPASS:
case errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE:
case errorCodes.ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR:
BUFFER_OUTPUT_DERIVE: WebAssembly.Global<'i32'>
BUFFER_OUTPUT_SIGN: WebAssembly.Global<'i32'>
BUFFER_OUTPUT_VERIFY: WebAssembly.Global<'i32'>
- ERROR_BYTE_OUT_OF_RANGE: WebAssembly.Global<'i32'>
ERROR_INDEX_OUT_OF_RANGE: WebAssembly.Global<'i32'>
ERROR_INVALID_BLOCK_COUNT: WebAssembly.Global<'i32'>
ERROR_INVALID_MESSAGE_LENGTH: WebAssembly.Global<'i32'>
--- /dev/null
+//! SPDX-FileCopyrightText: 2026 Chris Duncan <chris@codecow.com>
+//! SPDX-License-Identifier: GPL-3.0-or-later
+
+/**
+ * Tests that drive the compiled module directly through its integer ABI, below
+ * the host layer, for two 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
+ * depend on the key. Memory is not exported, so this builds a probe from a copy
+ * of the sources with `noExportMemory: false`, runs each primitive with two
+ * different keys on fresh instances, and compares all of memory. A diff sees a
+ * secret in any representation; a search only finds the forms it was told
+ * about, so the search runs too, as a cross-check, never as the verdict.
+ *
+ * **Result polarity.** `OUTPUT_VERIFY` must only ever hold `0` or `1`. The host
+ * reads it with a strict `=== 1`; this is the property that keeps a looser
+ * comparison there from ever mattering.
+ *
+ * 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 `clear_t()` removed from `crypto_derive` must show residue, 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.
+ */
+
+import { execFile } from 'node:child_process'
+import { createHash, getRandomValues } from 'node:crypto'
+import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises'
+import { promisify } from 'node:util'
+import { IDENTITY, PROBLEM_VECTOR } from './vectors.mjs'
+
+const exec = promisify(execFile)
+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/crypto_derive.ts', fn: 'crypto_derive', from: '\n\tclear_t()' }
+
+/** Copies the sources, exports memory, optionally drops one line, and compiles. */
+async function probe (name, drop) {
+ 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)
+ const source = await readFile(path, 'utf8')
+ const start = source.indexOf(`export function ${drop.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}()`)
+ }
+ await writeFile(path, source.slice(0, start) + body.replace(drop.from, '') + 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 words = (b) => Array.from({ length: b.length >> 2 }, (_, i) => new DataView(b.buffer, b.byteOffset).getUint32(4 * i, true))
+const memory = (x) => new Uint8Array(x.memory.buffer).slice()
+const differing = (a, b) => { let n = 0; for (let i = 0; i < a.length; i++) n += +(a[i] !== b[i]); return n }
+const keyOf = (n) => Uint8Array.from({ length: 32 }, (_, i) => (i * 37 + 11 + n * 101) & 255)
+const MESSAGE = new Uint8Array(32).fill(0x11)
+
+function derive (x, prv) {
+ x.setInputPrv(...words(prv))
+ x.derive()
+ return Uint8Array.from({ length: 32 }, (_, i) => x.getOutputDeriveByte(i))
+}
+
+function sign (x, prv, pub, msg = MESSAGE) {
+ x.setInputMsg(0, ...words(msg))
+ x.setInputPrv(...words(prv))
+ x.setInputPub(...words(pub))
+ x.sign(msg.length)
+ return Uint8Array.from({ length: 64 }, (_, i) => x.getOutputSignByte(i))
+}
+
+/**
+ * Runs one primitive on fresh instances, the way the host would, and returns
+ * memory before and after `clearMemory()`. A failed `sign` is one given a public
+ * key that does not match: it aborts after deriving, before its own scrub.
+ */
+function run (mod, op, prv) {
+ const x = instance(mod)
+ const pub = derive(x, prv)
+ const before = memory(x)
+ x.clearMemory()
+ if (op === 'derive') return { before, after: memory(x), pub }
+ const y = instance(mod)
+ try {
+ sign(y, prv, op === 'sign' ? pub : new Uint8Array(32))
+ } catch { }
+ const raw = memory(y)
+ y.clearMemory()
+ return { before: raw, after: memory(y), pub }
+}
+
+/** Every representation of a key's secrets that the search looks for. */
+function secrets (prv) {
+ const L = (1n << 252n) + 27742317777372353535851937790883648493n
+ const blake2b = (...parts) => { const h = createHash('blake2b512'); for (const p of parts) h.update(p); return new Uint8Array(h.digest()) }
+ const le = (b) => b.reduceRight((n, v) => (n << 8n) | BigInt(v), 0n)
+ const bytes = (n) => Uint8Array.from({ length: 32 }, (_, i) => Number((n >> BigInt(8 * i)) & 255n))
+ const digits = (a) => {
+ const e = new Int8Array(64)
+ for (let i = 0; i < 32; i++) { e[2 * i] = a[i] & 15; e[2 * i + 1] = a[i] >> 4 }
+ let c = 0
+ for (let i = 0; i < 63; i++) { e[i] += c; c = (e[i] + 8) >> 4; e[i] -= c << 4 }
+ e[63] += c
+ return new Uint8Array(e.buffer)
+ }
+ const az = blake2b(prv)
+ const a = az.slice(0, 32)
+ a[0] &= 248
+ a[31] &= 127
+ a[31] |= 64
+ const z = az.slice(32)
+ const nonce = blake2b(z, MESSAGE)
+ const r = bytes(le(nonce) % L)
+ return { 'private key': prv, 'scalar a': a, 'prefix z': z, 'digits of a': digits(a), 'nonce hash': nonce, 'nonce r': r, 'digits of r': digits(r) }
+}
+
+/** Positions where any 8-byte window of `s` with 4 informative bytes occurs. */
+function copies (mem, s) {
+ const buf = Buffer.from(mem)
+ const hits = new Set()
+ for (let w = 0; w + 8 <= s.length; w++) {
+ const needle = Buffer.from(s.subarray(w, w + 8))
+ if (needle.filter(v => v !== 0 && v !== 255).length < 4) continue
+ for (let p = buf.indexOf(needle); p >= 0; p = buf.indexOf(needle, p + 1)) hits.add(p - w)
+ }
+ return hits.size
+}
+
+/** Input-dependent bytes left after `clearMemory()`, by memory diff. */
+const residue = (mod, op) => differing(run(mod, op, keyOf(1)).after, run(mod, op, keyOf(2)).after)
+
+let passes = 0
+let failures = 0
+function check (name, test, detail = '') {
+ console.log(`${test ? '\x1b[32mPASS' : '\x1b[31mFAIL'}\x1b[0m: ${name}${!test && detail ? ` (${detail})` : ''}`)
+ passes += +test
+ failures += +!test
+}
+
+const started = performance.now()
+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] = await Promise.all([probe('clean'), probe('dropped-scrub', DROPPED_SCRUB).catch((err) => err)])
+
+ // positive controls: the search and the diff can both fire
+ const control = run(clean, 'derive', keyOf(1))
+ check('search finds the public key in memory before clearMemory()', copies(control.before, control.pub) > 0)
+ check('diff sees the public key output before clearMemory()',
+ differing(run(clean, 'derive', keyOf(1)).before, run(clean, 'derive', keyOf(2)).before) > 0)
+ const seeded = dropped instanceof WebAssembly.Module ? residue(dropped, 'derive') : 0
+ check('diff sees the residue left by a crypto_derive without clear_t()', seeded > 0,
+ dropped instanceof WebAssembly.Module ? `${seeded} bytes` : String(dropped?.message ?? dropped))
+
+ const sec = secrets(keyOf(1))
+ for (const op of ['derive', 'sign', 'failed sign']) {
+ const n = residue(clean, op)
+ check(`no input-dependent bytes after ${op} and clearMemory()`, n === 0, `${n} bytes differ`)
+ const { before, after } = run(clean, op, keyOf(1))
+ const found = Object.entries(sec).filter(([, v]) => copies(before, v) + copies(after, v) > 0).map(([k]) => k)
+ check(`no copy of any secret representation after ${op}`, found.length === 0, found.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)
+ const seen = new Map()
+ const note = (v) => seen.set(v, (seen.get(v) ?? 0) + 1)
+ const verify = (sig, msg, pub) => {
+ x.setInputMsg(0, ...words(msg))
+ x.setInputPub(...words(pub))
+ x.setInputSig(...words(sig))
+ x.verify(msg.length)
+ note(x.getOutputVerifyByte(0))
+ x.clearMemory()
+ }
+ const verifyBlocks = (pub, blocks) => {
+ x.setInputPub(...words(pub))
+ blocks.forEach(([sig, hash], b) => {
+ x.setInputMsg(b * 96, ...words(sig.subarray(0, 32)))
+ x.setInputMsg(b * 96 + 32, ...words(sig.subarray(32)))
+ x.setInputMsg(b * 96 + 64, ...words(hash))
+ })
+ x.verify_blocks(blocks.length)
+ for (let i = 0; i < 64; i++) note(x.getOutputVerifyByte(i))
+ x.clearMemory()
+ }
+ for (let n = 0; n < 100; n++) {
+ const prv = getRandomValues(new Uint8Array(32))
+ const msg = getRandomValues(new Uint8Array(32))
+ const pub = derive(x, prv)
+ x.clearMemory()
+ const sig = sign(x, prv, pub, msg)
+ x.clearMemory()
+ const forged = sig.slice()
+ forged[n % 64] ^= 1 << (n & 7)
+ const junk = getRandomValues(new Uint8Array(64))
+ const badKey = getRandomValues(new Uint8Array(32))
+ for (const [s, k] of [[sig, pub], [forged, pub], [junk, pub], [sig, badKey]]) verify(s, msg, k)
+ verifyBlocks(pub, [[sig, msg], [forged, msg], [junk, msg]])
+ verifyBlocks(badKey, [[sig, msg]])
+ }
+ verify(PROBLEM_VECTOR.signatureBytes, PROBLEM_VECTOR.blockHashBytes, PROBLEM_VECTOR.publicKeyBytes)
+ verifyBlocks(PROBLEM_VECTOR.publicKeyBytes, [[PROBLEM_VECTOR.signatureBytes, PROBLEM_VECTOR.blockHashBytes]])
+ verifyBlocks(IDENTITY.publicKeyBytes, [[IDENTITY.signatureBytes, new Uint8Array(32)]])
+ const values = [...seen.keys()].sort((a, b) => a - b)
+ check('OUTPUT_VERIFY holds only 0 and 1, and both occur', values.join() === '0,1', `values seen: ${values.join(', ')}`)
+} finally {
+ await rm(work, { recursive: true, force: true })
+}
+
+console.log(`${passes} \x1b[32mPASSED\x1b[0m`)
+console.log(`${failures} \x1b[31mFAILED\x1b[0m`)
+console.log(`2 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
+process.exitCode = failures > 0 ? 1 : 0
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)
+process.exitCode = failures > 0 ? 1 : 0
}
}
test = accepted.length === 0
-check(`verify_blocks rejects R xor mask${test ? '' : ` (failed to reject ${JSON.stringify(accepted)})`}`, test)
+check(`verify_blocks rejects R xor mask${test ? '' : ` (failed to reject ${accepted.length}, first ${JSON.stringify(accepted.slice(0, 8))})`}`, 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
+// key and a 32-byte hash, so that an equation which stops rejecting fails here
+// and not only in the 64 KiB message sweeps further down.
+{
+ const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
+ /** @param {() => unknown} f */
+ const attempt = (f) => {
+ try {
+ return f()
+ } catch (err) {
+ return `threw ${typeof err === 'object' && err != null && 'message' in err ? err.message : err}`
+ }
+ }
+
+ // the checks below only assert rejections, so assert the baseline too or they die quietly
+ test = verify(sig, hash, pub) === true && verify_blocks(pub, [{ hash, signature: sig }])[0] === true
+ check('verify and verify_blocks accept the unmodified signature under a normal key', test)
+ passes += +test
+ failures += +!test
+
+ /** @type {{ byte: number, bit: number, verify: unknown, verify_blocks: unknown }[]} */
+ const missed = []
+ const forged = sig.slice()
+ for (let i = 0; i < constants.SIGNATURE_BYTELENGTH; i++) {
+ for (let bit = 0; bit < 8; bit++) {
+ forged[i] ^= 1 << bit
+ const strict = attempt(() => verify(forged, hash, pub))
+ const relaxed = attempt(() => verify_blocks(pub, [{ hash, signature: forged }])[0])
+ forged[i] = sig[i]
+ if (strict !== false || relaxed !== false) {
+ missed.push({ byte: i, bit, verify: strict, verify_blocks: relaxed })
+ }
+ }
+ }
+ test = missed.length === 0
+ check(`verify and verify_blocks reject every single-bit corruption of a valid signature${test ? '' : ` (${missed.length} not rejected, first ${JSON.stringify(missed.slice(0, 4))})`}`, test)
+ passes += +test
+ failures += +!test
+
+ const otherHash = hash.slice()
+ otherHash[0] ^= 1
+ test = attempt(() => verify(sig, otherHash, pub)) === false
+ && attempt(() => verify_blocks(pub, [{ hash: otherHash, signature: sig }])[0]) === false
+ check('verify and verify_blocks reject a valid signature over a different hash', test)
+ passes += +test
+ failures += +!test
+
+ const otherPrv = prv.slice()
+ otherPrv[0] ^= 1
+ const otherPub = new Uint8Array(constants.KEY_BYTELENGTH)
+ derive(otherPrv, otherPub)
+ test = attempt(() => verify(sig, hash, otherPub)) === false
+ && attempt(() => verify_blocks(otherPub, [{ hash, signature: sig }])[0]) === false
+ check('verify and verify_blocks reject a valid signature under a different key', test)
+ passes += +test
+ failures += +!test
+
+ // a full batch with every fifth block corrupted must reject exactly those blocks
+ const blocks = []
+ const corrupted = new Set()
+ for (let b = 0; b < constants.MAX_VERIFY_BLOCKS; b++) {
+ const signature = sig.slice()
+ if (b % 5 === 0) {
+ signature[(b * 7) % constants.SIGNATURE_BYTELENGTH] ^= 1 << (b & 7)
+ corrupted.add(b)
+ }
+ blocks.push({ hash, signature })
+ }
+ result = attempt(() => verify_blocks(pub, blocks))
+ test = Array.isArray(result) && result.length === blocks.length && result.every((v, b) => v === !corrupted.has(b))
+ check(`verify_blocks rejects exactly the ${corrupted.size} corrupted blocks of a full batch`, test)
+ passes += +test
+ failures += +!test
+}
+
// Check output buffer offset handling
try {
outbuf = new Uint8Array(33)
console.log(`${passes} \x1b[32mPASSED\x1b[0m`)
console.log(`${failures} \x1b[31mFAILED\x1b[0m`)
-process.exit(failures)
+// Not process.exit(): it can cut off output still draining to a pipe, and an
+// exit status is 8 bits wide, so a count of 256 failures would read as success.
+process.exitCode = failures > 0 ? 1 : 0