From: Chris Duncan Date: Fri, 9 Oct 2026 17:56:06 +0000 (-0700) Subject: Update agent file. X-Git-Tag: v2.0.0~2^2~1 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=0e2d2980e617a54e6bf7aef8fbef5d18eaf60ade;p=nano25519.git Update agent file. --- diff --git a/AGENTS.md b/AGENTS.md index 5f9bec5..9967a24 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -39,7 +39,7 @@ the vectors — see **Testing**. The public-key decompression is hoisted into | target | strictest available | ed25519-donna, i.e. what nano_node accepts | | scalar `S` | `S < L` | `S < 2^253` | | public key | canonical, non-small-order | decodable only | -| nonce `R` | decoded, rejected if small order | never decoded | +| nonce `R` | canonical, decoded, rejected if small order | never decoded | | equation | cofactored | cofactorless byte-compare | | small-order key (`PROBLEM_VECTOR`) | rejects | **accepts** | | `R` paired with `S+L` | rejects | **accepts** | @@ -65,52 +65,72 @@ multiplication, which is a different algorithm entirely. **`sign` costs two fixed-base scalar multiplications, deliberately.** It derives the public key from the private key and throws `Invalid public key` if the one passed in disagrees. That is RFC 8032 §5.1.6's definition of signing, and the -comparison buys keypair integrity. It roughly halves signing throughput -(~26 µs → ~49 µs). **This is the committed shape — do not "optimise" it away.** +comparison buys keypair integrity. It roughly halves signing throughput: one +derivation is ~19 µs of a ~39 µs signature. **This is the committed shape — do +not "optimise" it away.** Removing the derivation would break RFC conformance; removing the comparison would silently accept a mismatched keypair. ## Commands ```bash -npm run build # clean + compile + esbuild (dev) -npm run build:prod # clean + compile + esbuild (minified) -npm run compile # asc + tsc only, no bundle -npm test # build, then node ./test/node.mjs -npm run test:prod # build:prod, then the same suite -npm run clean # rm -rf {build,dist,types} +npm run build # clean + compile (asc --debug) + esbuild +npm run build:prod # clean + compile + esbuild (minified) +npm run compile # generate blake2b.ts, then asc + tsc only, no bundle +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 profile # build, then the suite under --cpu-prof into prof/ +npm run clean # rm -rf {build,dist} ``` -`build/`, `dist/`, and `types/` are generated and gitignored. Never edit them. -The test suite imports from `dist/`, so **always build before testing** — a -stale `dist/` will silently test the previous revision. +`build/` and `dist/` are generated and gitignored. Never edit them. The test +suite imports from `dist/`, so **always build before testing** — a stale +`dist/` will silently test the previous revision. The same goes for +`test/index.html`, which loads `dist/browser.js`: `compile` and `asc` alone do +not rewrite it. + +`src/assembly/ed25519/blake2b.ts` is generated by `scripts/blake2b-gen.mjs` on +every compile. Edit the generator, not its output. ## Layout | Path | What it is | | --- | --- | | `src/index.ts` | Public API and its overloads: `derive`, `sign`, `verify`, `verify_blocks` | -| `src/lib/wasm.ts` | Instantiates the module; exports `constants`, the mutex-gated `Pointers`, `Mutex`, `clearMemory()` | +| `src/lib/wasm.ts` | Instantiates the module and checks the error-code contract; exports `constants`, `Mutex`, and the mutex-gated `setInput()` and `getOutput()` | +| `src/lib/errors.ts` | Error classes, the host's error-code table, and the `env.abort` handler that turns codes into messages | | `src/lib/primordials.ts` | Trust root: built-ins captured at load, plus `normalize()`. Imports nothing, by design | | `src/lib/{derive,sign,verify}.ts` | Host-side marshalling, one file per primitive | -| `src/assembly/index.ts` | Wasm entry points, static I/O buffers, exported pointers and byte-length globals | +| `src/assembly/index.ts` | Wasm entry points, static I/O buffers, the byte setters and getters, and exported constant globals | | `src/assembly/crypto_{derive,sign,verify}.ts` | RFC 8032-shaped primitives over BLAKE2b | -| `src/assembly/{fe,ge,p,sc}.ts` | Field element, group element, point, and scalar arithmetic | -| `src/assembly/{base,base2}.ts` | Precomputed base point tables as static data segments | +| `src/assembly/ed25519/{fe,ge,p,sc}.ts` | Field element, group element, point, and scalar arithmetic | +| `src/assembly/ed25519/{base,base2}.ts` | Precomputed base point tables as static data segments | +| `src/assembly/ed25519/blake2b.ts` | Generated by `scripts/blake2b-gen.mjs`; do not edit | +| `src/assembly/ed25519/utils.ts` | `equalbytes` and the other constant-time helpers | +| `src/assembly/ed25519/t.ts` | Shared temporaries `t_fe_0`–`t_fe_6`, imported only by the `crypto_` functions and passed down — see **Gotchas** | | `src/assembly/constants.ts` | Byte lengths and caps; imported by everything, imports nothing | -| `src/assembly/errors.ts` | Error text as a plain array, thrown by index | -| `src/assembly/utils.ts` | `equalbytes` and the other constant-time helpers | -| `src/assembly/tests.ts` | Start-function build guard — see **Testing** | +| `src/assembly/errors.ts` | Error codes and buffer ids, exported as wasm globals | +| `src/assembly/env.ts` | The `abort` replacement and `raise()`: errors cross as four integers | +| `src/assembly/tests.ts` | Start-function build guards — see **Testing** | | `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/vectors/python_ed25519_blake2b.ts` | The bulk vector set, split out to stop crashing the IDE | | `test/index.html` | Browser test and benchmark page | ## The wasm ABI -Nothing crosses the boundary as arguments. The host writes into fixed static -buffers, calls an export that takes only a length or a count, and reads results -back out of the output buffer for that primitive. `src/lib/wasm.ts` resolves -every pointer and byte length once at module load and re-exports them. +Only integers cross the boundary, and the module's memory is neither imported +nor exported, so the host never holds a view of it. The host packs inputs into +little-endian 32-bit words and writes them into fixed static buffers with +`setInputMsg(index, …)`, `setInputPrv`, `setInputPub` and `setInputSig`, calls an +export that takes only a length or a count, and reads results back a byte at a +time with `getOutputDeriveByte`, `getOutputSignByte` and `getOutputVerifyByte`. +`setInputMsg` and the getters check their index first and raise +`ERROR_INDEX_OUT_OF_RANGE`; the other setters always write their whole buffer. `src/lib/wasm.ts` reads the byte-length globals once +at module load and re-exports them. Big-endian hosts take a byte-shifting path +instead of the word view; `test/big-endian.mjs` forces it. | Buffer | Purpose | | --- | --- | @@ -121,9 +141,6 @@ every pointer and byte length once at module load and re-exports them. | `OUTPUT_SIGN` | 64 B, a signature | | `OUTPUT_VERIFY` | 64 B, one result byte per verified block (= `MAX_VERIFY_BLOCKS`) | -Pointer getters are `ptrInputMsg`, `ptrInputPrv`, `ptrInputPub`, `ptrInputSig`, -`ptrOutputDerive`, `ptrOutputSign`, `ptrOutputVerify`. - **One buffer per role, and keep it that way.** These replace a single shared `OUTPUT_BUFFER` that had to satisfy two different constraints — at least one byte per block, *and* at least 64 bytes for a signature. Only the first was ever @@ -162,10 +179,11 @@ These sizes are a **public API**: `nano25519.constants` carries `BLOCKHASH_BYTELENGTH`, `KEY_BYTELENGTH`, `SIGNATURE_BYTELENGTH`, `MAX_VERIFY_BLOCKS`, `MAX_VERIFY_BLOCKS_BYTELENGTH` and `MAX_MESSAGE_BYTELENGTH`. Read them rather than hardcoding, on both sides of the -boundary and in consumers. Buffer **pointers** are the mutex-gated `Pointers` -class in `src/lib`, deliberately not exported from the package — the -buffer-scrub guarantee is a property of the module, not a promise about -callers. +boundary and in consumers. The setters and getters are reached through +`setInput()` and `getOutput()` in `src/lib/wasm.ts`, which throw +`Nano25519MutexError` without the lock, and are deliberately not exported from +the package — the buffer-scrub guarantee is a property of the module, not a +promise about callers. `test/index.html` reads `nano25519.constants.MAX_VERIFY_BLOCKS` for its loop bound, its per-block divisor and its default test size — which is why the 32 → 64 @@ -175,44 +193,56 @@ whose whole job is producing that number. ## Host-side invariants -Three properties the TypeScript layer now enforces rather than assumes. All three -were conventions that held only while every caller behaved. +Three properties the host now enforces rather than assumes. All three were +conventions that held only while every caller behaved. **A mutex guards the shared buffers, and `Mutex.lock()` goes *outside* the -`try`.** Every host entry point locks before it writes, and the `finally` clears -the buffers and releases. Acquiring inside the `try` is the bug this shape avoids: +`try`.** Every host entry point locks before it writes, and the `finally` calls +`Mutex.unlock()`, which runs the module's `clearMemory()` and then releases. Acquiring inside the `try` is the bug this shape avoids: a failed acquisition would run the `finally` and scrub the buffers out from under the call that legitimately holds the lock. `lock()` throws `Nano25519TypeError('Failed to acquire mutex')` rather than waiting — the module is single-threaded and synchronous, so a second acquirer means an async wrapper is interleaving calls, which is exactly what must not happen silently. -**A detached buffer is an error, not something to re-wrap.** After a wasm call -the host asserts `exports.memory.buffer === buffer.buffer` and throws -`Nano25519TypeError('WASM memory buffer detached')`. Re-wrapping the view after -the call — the previous shape — papers over memory growth that should never occur -and hands back results read from a different buffer than the one written. - -**`OUTPUT_VERIFY` is fail-closed at every point it could be read.** It is filled -with `0` at instantiation, again at the top of `verify_blocks` before the count -check, and again by the host's `clearMemory()`. `1` means verified, so a buffer +**There is no buffer view to go stale.** The host used to read results through +`Uint8Array` views of the exported memory, and memory growth during a call would +have detached them, so it asserted the buffer's identity after every call. With +memory no longer exported, that whole class of bug is gone, and secrets are out +of reach of host code too. Do not export memory again to read results faster: +at ~2 ns a call, reading a 64-byte signature byte by byte costs about 0.13 µs +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. ## Wasm error reporting -Error text lives in `src/assembly/errors.ts` as a plain array, and exported -functions throw by index (`throw new Error(errors[2])`). This lets an inner -primitive return a code that an outer function turns into a message: `crypto_sign` -returns `i32` rather than throwing, so `sign()` can scrub `OUTPUT_SIGN` before it -rethrows — a throw from deep inside would otherwise leave a partial signature in -an output buffer. - -Indexing the array does **not** break the message. That is worth stating because -the `throw new Error('literal')` note below makes it look like it should: the -null-pointer failure there is specific to a *hoisted* `Error` object's `.message` -field, not to a runtime string operand. Verified — a wrong public key reaches the -host as `Nano25519WasmError: Invalid public key, src/assembly/index.ts, row 143, -col 3`. +Errors cross the boundary as four integers. `raise(code, a, b)` in +`src/assembly/env.ts` records a code from `src/assembly/errors.ts` and throws; +the `abort` replacement installed by `use: ["abort=src/assembly/env/abort"]` +hands `(code, line, a, b)` to the host's `env.abort`, and `src/lib/errors.ts` +turns them into a `Nano25519WasmError` message. The module never formats a +string — that would pull string handling into the stub runtime — and the host +never reads module memory to report an error. + +The codes are a contract between the two `errors.ts` files. The host keeps its +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. + +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 +it raises `ERROR_INVALID_PUBLIC_KEY` — a throw from deep inside would leave a +partial signature in an output buffer. + +`line` is meaningful only for `ERROR_UNKNOWN`, an abort from the AssemblyScript +runtime itself. Coded errors carry their location in the code and its two +integers; the self-test codes describe their failing input completely. ## Build constraints that break normal assumptions @@ -234,16 +264,15 @@ ordinary AssemblyScript: arithmetic over other constants is fine and still const-folds. - **`enable: ["simd"]`** — field elements are 12 `i32` limbs, not 10. The two trailing limbs are padding; respect the stride. -- **`importMemory: true`** — the **host** creates the `WebAssembly.Memory` and the - module imports it. This is what lets `env.abort` decode a message thrown from - the start function: the handler reads the host's `memory`, which exists before - instantiation, rather than `exports.memory`, which does not. The host's - `initial` is hand-maintained in `src/lib/wasm.ts` but cannot drift silently — - too small is a `LinkError` at instantiation, too large is simply accepted. +- **`importMemory: false`, `noExportMemory: true`** — the module's memory is + invisible to the host; see **The wasm ABI** and **Wasm error reporting**. A + probe that needs to read memory, such as a residue check, must be built with + `noExportMemory: false` from a copy of the sources, never by editing this file. - **`initialMemory: 4`** — pins the module at 4 pages (262,144 B); heap at rest - is 137,792 B. Only the stub allocator's *growth* doubles (1→2→4→8); the setting - itself takes any integer, so it need not be a power of two, and 3 pages do fit - today with 58,816 B spare. **Slack here is nearly free**: measured, the fourth + is 128,752 B (measured 2026-10-09 with an `__alloc(0)` probe whose binary + matched the shipping one). Only the stub allocator's *growth* doubles + (1→2→4→8); the setting itself takes any integer, so it need not be a power of + two, and 3 pages do fit today with 67,856 B spare. **Slack here is nearly free**: measured, the fourth page changes neither throughput nor instantiation time and never becomes resident, because nothing writes to it — it costs address space and V8 accounting, not RAM. Re-derive it whenever a buffer is resized rather than @@ -261,13 +290,12 @@ just a memory one. `equal()`, `negative()`, and `sodium_is_zero()`. Widen to `i32`/`u32` before shifting when porting libsodium idioms. -**`throw new Error('literal')` does not allocate.** With exception handling -disabled, AssemblyScript lowers it straight to `abort(msgPtr, filePtr, line, -col)` against static string data — the wat shows `call $abort` and -`unreachable`, no `__new`. Do **not** hoist it to a module-level -`const ERROR = new Error()`: that costs 96 bytes of permanent heap, adds a dead -store, and makes AssemblyScript pass a null message pointer, so the error text -is lost before it reaches the host. +**Throw only through `raise()`, and never give `Error()` a message.** With +exception handling disabled, AssemblyScript lowers `throw new Error()` straight +to `abort(…)` and `unreachable`, with no allocation. A message argument flags +string support into the stub runtime for a path that runs once and traps. Do +**not** hoist a module-level `const ERROR = new Error()` either: that costs 96 +bytes of permanent heap and adds a dead store. **A comparison function needs a test that makes things unequal.** `equalbytes` shipped comparing **one bit per byte** — the `>> 8` shift above was a no-op on a @@ -292,9 +320,9 @@ before it. **Scrub buffers on every path, unscoped.** Every exported wasm function must leave its input buffers fully zeroed when it returns, including the throw path. -Use whole-buffer `fill(0)`, never a length-scoped fill: the buffer pointers are -public exports, so a caller can write more bytes than the length it then -declares, and a scoped fill leaves the rest behind. A 32 KiB fill costs ~0.1 µs +Use whole-buffer `fill(0)`, never a length-scoped fill: the setters write +anywhere below a buffer's cap, so a caller can write more bytes than the length +it then declares, and a scoped fill leaves the rest behind. A 32 KiB fill costs ~0.1 µs — roughly 0.4% of one signature — so this is never worth optimising away. **Internal scratch holds key material too, and in shapes a scan will miss.** @@ -314,6 +342,29 @@ put a secret into a new buffer, enumerate the form it actually takes there — digit expansion, limb array, precomp entry, negated copy — and add that form to the scan in the same commit. +Better still, **diff rather than search**. Build a probe with +`noExportMemory: false`, run a primitive with two different keys on fresh +instances, call `clearMemory()`, and compare all of memory: every byte that +differs is input-dependent, whatever its representation. That is how the last +leftovers were found — the result point's projective coordinates in +`ge_scalarmult_base_tobytes` and the inversion chain in `ge_p3_tobytes`, twelve +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. + +**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 +set of field elements shared by `crypto_derive`, `crypto_sign` and the +`crypto_verify` functions, and passed down as `t_` parameters. Calls already +nest: `crypto_sign` runs `crypto_derive`, which overwrites all seven, before it +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. + **Establish fail-closed defaults before the first early exit.** `verify_blocks` runs `OUTPUT_VERIFY.fill(0)` *before* validating the public key, so a batch that bails out reports every block as `false` rather than leaving stale bytes. @@ -380,9 +431,23 @@ same-algorithm baseline is `verify_blocks(1)` repeated n times. Keep an n=1 row in every sweep — with nothing to amortise it must read ~0% (it reads 0.04%), and it is the row that tells you whether you measured what you named. -Useful scale anchors: a wasm call boundary is ~2 ns, a 32 KiB `memory.fill` is -~0.1 µs, one `verify` is ~73 µs with `Uint8Array` inputs and ~80 µs with hex -strings, one `sign` is ~49 µs, and the hoisted per-key work is ~6.2 µs. Buffer scrubbing and boundary crossing never +**SIMD results depend on the engine and the CPU, so measure in more than one.** +The vector carry chain in `fe_mul` measured 7–10% slower than the scalar one in +Chromium on a Ryzen 5800X, at parity in Chromium on an i7-11370H, and 1–3% faster +in Firefox on the 5800X. V8 has no AVX-512 code paths, so every x64 chip without +AVX10.1 runs the same emulation sequences for `i64x2.shr_s` and `i64x2.mul`, and +what they cost depends on the core. + +**`test/index.html` times each call**, so it needs a fine timer: run it +cross-origin isolated. Without isolation `performance.now()` steps in 100 µs in +Chromium and 1 ms in Firefox, where the page's per-call scores come out as +`Infinity`. + +Useful scale anchors, measured 2026-10-06 in Node 24 on a Ryzen 5800X: a wasm +call boundary is ~2 ns, a 32 KiB `memory.fill` is ~0.1 µs, one `derive` is +~19 µs, one `sign` is ~39 µs, one `verify` is ~71 µs with `Uint8Array` inputs +and ~74 µs with hex strings, and the hoisted per-key work is ~6.2 µs (measured +earlier). Buffer scrubbing and boundary crossing never show up on the clock; only the point arithmetic does. ## Testing @@ -391,9 +456,10 @@ show up on the clock; only the point arithmetic does. Current state is **6255 passing, 0 failing** in each. There is no expected failure — if anything fails, it is a regression. -`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, +`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` +so it runs at instantiation. Together they cost about 0.6 ms per +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". @@ -461,6 +527,37 @@ also its error detail, so the host prints the exact 32 bytes: ge_is_canonical build error from "max": expected non-canonical [237,255,…,127]; actual returned 0 (byte 0 = 0xed, sign 0) ``` +### The `fe_iszero` guard + +`fe_iszero` decides whether a decoded point is valid, in the square-root checks +of `ge_frombytes` and `ge_frombytes_negate_vartime`, and whether a key or `R` is +small order. Its dangerous failure is reporting zero for a value that is not, +which would let an invalid point decode. cc8fffd rewrote it from a byte loop +into two 16-byte loads ORed together and tested with `v128.any_true`, so the +guard covers every byte of both halves and the reduction in front of them: + +- **zero**, which must read as zero; +- **every single bit of every byte**, which must read as nonzero — catches a + dropped or misread half, and an accumulator that sees only some bits; +- **the same byte at all 496 pairs of positions** — halves combined with xor + instead of or cancel at stride 16 and nowhere else; +- **`p + m` for every byte `m`, written as loose limbs** at their bounds, the + shape `fe_sub` hands it in `ge_frombytes`: only `m = 0` reads as zero. + +The last shape exists because the first version of this guard got it wrong. It +built `p + m` from bytes, but `fe_frombytes` folds `p` to 0 as it decodes, so +those cases reached `fe_iszero` already reduced and the final reduction went +untested; a mutant in `fe_reduce` loaded cleanly and showed it. **A guard's +inputs must reach the function in the shape real callers produce**, not just +represent the same value. + +**1,008 calls per instantiation, about 0.04 ms.** Cases pack into one integer +as for `ge_is_canonical`, and the host prints the value's 32 bytes: + +```text +fe_iszero build error from "pair": expected nonzero [64,0,…,64,0,…]; actual returned 1 (bytes 0 and 16 = 0x40) +``` + ### Mutation tests `npm run test:mutants` (`test/mutants.mjs`, also run by `prepublishOnly`) is @@ -469,7 +566,12 @@ 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. +accepted, and `|` for `&` in `ge_is_canonical`; a dropped half, xor or and for +or, the high half loaded a byte early, and an inverted result in `fe_iszero`, +plus a wrong shift in `fe_reduce`, the reduction it depends on. A mutant can +target a function the guarded one depends on (`in:`). Seventeen builds, about +8 s. **A mutant that loads is a gap until it is shown to behave identically on +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. @@ -520,6 +622,11 @@ alongside the sweep. header and its original copyright line. - Use real mathematical symbols in comments (`≤`, `²⁵⁵`) — the codebase already does, and it reads against the RFC. +- Scratch parameters are named `t_` plus their type, numbered when there are + several (`t_fe_0`, `t_u8x32`, `t_ge_p1p1`), and come last in the parameter + list. A static that only one function uses is named after it + (`ge_frombytes_u`, `ge_scalarmult_base_tobytes_h`), so a shared buffer is + never mistaken for a private one. ## Git