From: Chris Duncan Date: Sat, 10 Oct 2026 09:37:13 +0000 (-0700) Subject: Update agent file and tests. X-Git-Tag: v2.0.0~1^2~33 X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=a7c8ba962c5ba07cbcbe5a328f2b21842e60d5be;p=nano25519.git Update agent file and tests. --- diff --git a/AGENTS.md b/AGENTS.md index 6ef5a83..896441a 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -38,13 +38,14 @@ the vectors — see **Testing**. The public-key decompression is hoisted into | | `verify()` | `verify_blocks()` | | --- | --- | --- | -| target | strictest available | ed25519-donna, i.e. what nano_node accepts | +| target | strict, cofactored | 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` | 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** | +| `R` offset by a small-order point (`TORSION_VECTORS`) | **accepts** | rejects | They will disagree about real cemented Nano blocks. That is the design, not a bug: `verify_blocks` answers *"does the ledger accept this"*, `verify` answers @@ -79,10 +80,13 @@ would silently accept a mismatched keypair. 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 test:module # residue and result polarity below the host; also in prepublishOnly +npm test # build, then all five suites below +npm run test:prod # build:prod, then the same five suites; also prepublishOnly +npm run test:le # test/node.mjs, the public API +npm run test:be # the same, forced down the big-endian marshalling path +npm run test:mutants # guard mutation tests, see Testing +npm run test:module # residue, input scrubbing and result polarity below the host +npm run test:arithmetic # field, scalar and group internals against a BigInt reference npm run profile # build, then the suite under --cpu-prof into prof/ npm run clean # rm -rf {build,dist} ``` @@ -119,8 +123,11 @@ every compile. Edit the generator, not its output. | `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/module.mjs` | Drives the compiled module directly: secret residue by memory diff, input buffers scrubbed on every path, and `OUTPUT_VERIFY` polarity | +| `test/arithmetic.mjs` | Differential tests of the internals over a probe build, against `test/reference.mjs` | +| `test/reference.mjs` | Independent BigInt Ed25519-BLAKE2b, both verification rules; tests only | | `test/vectors/python_ed25519_blake2b.ts` | The bulk vector set, split out to stop crashing the IDE | +| `test/vectors/torsion.ts` | The nano.org signature with `R` offset by each small-order point | | `test/index.html` | Browser test and benchmark page | ## The wasm ABI @@ -197,7 +204,7 @@ whose whole job is producing that number. ## Host-side invariants -Three properties the host now enforces rather than assumes. All three were +Four properties the host now enforces rather than assumes. All four were conventions that held only while every caller behaved. **A mutex guards the shared buffers, and `Mutex.lock()` goes *outside* the @@ -226,6 +233,16 @@ 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. +**Results are defined, never assigned.** `verify_blocks` builds its `boolean[]` +with `slot()` from `primordials.ts`: `Object.defineProperty` with a descriptor +from `Object.create(null)`, both captured at load. Assignment, `push` and `fill` +all store through the prototype chain when the index is not yet the array's own, +so a getter and setter added to `Array.prototype` after load swallowed every +result and answered `true` for a forged block, with a correct `length` under +`push`. The descriptor needs no prototype of its own, or a `get` added to +`Object.prototype` makes it read as an accessor and the call throws. The +hardening list in `test/node.mjs` patches both. + ## Wasm error reporting Errors cross the boundary as four integers. `raise(code, a, b)` in @@ -333,6 +350,9 @@ 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. +`test:module` checks it on all eight success and throw paths before +`clearMemory()` can repeat the job, writing the message buffer past the declared +length too; a scoped fill or a dropped throw-path scrub fails there. **Internal scratch holds key material too, and in shapes a scan will miss.** The gotcha above is about the *input* buffers of exported functions. The harder @@ -364,7 +384,8 @@ point temporaries into shared buffers. **`npm run test:module` now runs this dif 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. +not. The diff runs after `clearMemory()`, so it cannot see an export that leaves +its own input buffers to the host; the input check above covers that. **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 @@ -403,18 +424,33 @@ call against it: - A loop bound of `SIG_LEN` or `KEY_LEN` where the intent was "per item" reads the right number of bytes for the wrong reason. -`crypto_verify.ts:62` used to pass a literal `32` to `equalbytes` where the line +`crypto_verify_donna` used to pass a literal `32` to `equalbytes` where the line above it already read `KEY_BYTELENGTH`. The literal was correct, so it was only cosmetic — but it was a length argument on the one comparison carrying the batch path's whole security property, so it now reads `KEY_BYTELENGTH`. Keep it that -way, including in the staged cofactorless line commented beneath -`crypto_verify_sodium`. +way, including in the staged cofactorless `crypto_verify_strict`. + +**An extended point's `T` is `XY/Z`, and a correct point can carry a wrong +one.** `ge_p2_to_p3` copied `X`, `Y` and `Z` and set `T = X·Y`, which holds only +when `Z = 1`. `crypto_verify_sodium` subtracted that point from `R`, so the +cofactored check accepted `R` offset by order 2 or 4 and rejected every order-8 +offset. Nothing could forge through it, and the suite stayed green, because the +point was right and only its representation was wrong. The code came from +libsodium master, which still has it; releases are cofactorless and unaffected. +The fix converts the final `p1p1` straight to `p3`. Whenever a point leaves a +function in one representation and enters another, check the representation's +own invariant, not just the point: `test:arithmetic` asserts `XY = ZT` on every +`p3` it reads back, and its control recomputes `T` as `X·Y` to prove a point +comparison alone misses it. **Do not add JS-side suspension points.** The safety of hashing straight out of -the shared message buffer rests on there being no `await`, no yield, and no -callback into user code between the host writing the buffer and reading the -result. The only wasm import is `env.abort`, which throws. Preserve both -properties. +the shared message buffer rests on there being no `await` and no yield between +the host writing the buffer and reading the result. User code does run inside +that window: `verify_blocks` reads each block's `signature` and `hash` after it +has written `INPUT_PUB`, and those may be getters. That is safe only because the +mutex refuses any call back into the package, which `test/node.mjs` checks with a +re-entrant getter. The only wasm import is `env.abort`, which throws. Preserve +all of that. ## Benchmarking @@ -466,12 +502,18 @@ show up on the clock; only the point arithmetic does. ## Testing -`npm test` builds, then runs `test/node.mjs` twice, little- and big-endian. -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. +`npm test` builds, then runs five suites: `test/node.mjs` little- and +big-endian, then `test:mutants`, `test:module` and `test:arithmetic`. Current +state is **6288, 6288, 17, 12 and 36 passing, 0 failing**. There is no expected +failure — if anything fails, it is a regression. `test:all` chains them with +`&&`, so the first red suite stops the rest; run them one by one when chasing +more than one failure. Every 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. + +Every public call in `test/node.mjs` goes through `attempt()` or a `try`, so a +regression that makes one throw is a counted failure rather than a crash that +loses the totals. Keep new checks the same. `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` @@ -577,8 +619,8 @@ fe_iszero build error from "pair": expected nonzero [64,0,…,64,0,…]; actual ### 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 +`npm run test:mutants` (`test/mutants.mjs`) 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 @@ -633,13 +675,63 @@ canary at a normal account leaves a test that passes on a forgeable build. `IDENTITY.signatureBytes` is `enc(identity) ‖ 32 zero bytes` — with `S = 0`, `check_r` is the identity, so the baseline verifies for **any** message hash. -⚠️ **The canary asserts only rejections, so it dies quietly.** Nothing asserts -that the unmodified signature is *accepted*. Any future change that stops that -baseline verifying — an `S ≠ 0` check, a degenerate-signature reject, a -small-order-`A` reject on the permissive path — turns all 8,160 iterations into -trivial rejections and the canary goes green forever while testing nothing. -Verified: with a wrong `A`, the sweep still reports PASS. Assert the baseline -alongside the sweep. +⚠️ **The canary asserts only rejections, so it dies quietly without its +baseline.** Any change that stops the unmodified signature verifying — an +`S ≠ 0` check, a degenerate-signature reject, a small-order-`A` reject on the +permissive path — turns all 8,160 iterations into trivial rejections, and the +sweep goes green while testing nothing. Verified: with a wrong `A`, the sweep +still reports PASS. The check just before it asserts that the baseline is +accepted; keep the two together. + +### Small-order offsets of `R` + +`TORSION_VECTORS` is the nano.org key signing the nano.org block hash with the +nonce point offset by each of the eight points of order dividing 8: +`R' = rB + T`, with `S` recomputed for `R'`, which only the key holder can do. +`R' - ([S]B - [k]A) = T`, so these are the only signatures whose final equation +leaves a torsion difference, and the only ones that tell a cofactored check from +a cofactorless one or from a broken one. `verify()` must accept all eight and +`verify_blocks()` only the order-1 row, which is the nano.org signature itself; +neither may accept the same nonces with an `S` that does not match them. The +vectors were generated with `test/reference.mjs`, and the order-1 row +reproducing the nano.org signature checks the generator. Before they existed, +`verify()` rejected every order-8 offset (see **Gotchas**) and nothing noticed. + +### Hardening, re-entrancy and hex input + +The patch list at the end of `test/node.mjs` replaces built-ins after load and +runs every primitive under every patch: `Function.prototype.call`, typed-array +and array methods and accessors, index accessors on `Array.prototype`, and +`get`, `set` and `Symbol.iterator` on `Object.prototype`. The `verify_blocks` +case verifies a valid and a forged block and requires own elements, because a +patch that answers `true` for everything passes a valid-only batch. Errors +raised while the mutex is held — invalid input to `verify`, a bad block or key +in `verify_blocks`, a throwing block getter, and a wasm abort from `sign` — must +each release it, and a getter that calls back in must be refused while the +outer call completes. Hex input is checked against all 256 byte values in lower, +upper and mixed case, and 15 invalid characters at every position of a private +key, including code units above `0xff` whose low byte is a valid digit. + +### Below the API: `test:module` and `test:arithmetic` + +`test:module` builds probes with memory exported and checks three 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: `clear_t()` dropped from `crypto_derive`, and the `INPUT_SIG` +scrub dropped from the length check in `verify`. + +`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 56,000 +results with `test/reference.mjs`: every `fe_*` operation including aliased +operands, limbs at the bounds ref10 documents and `p + m` as loose limbs; the +scalar functions over every bit position, dense `2²⁵² ≤ S < 2²⁵³` and the +neighbourhood of `L`; and decoding, small order, encoding and both scalar +multiplications over torsion, non-canonical and random points, checking `XY = ZT` +and `[0]A + [0]B`. Inputs are tight signed limbs, as real callers produce: the +canonical non-negative form overflows `fe_mul`'s i32 `19·g` lanes on a sum like +`Y + X`, a false mismatch no caller can trigger. It is seeded, so a failure +reproduces, and its two controls drop `ge_p3_0(r)` and recompute `T` as `X·Y`. ## Style diff --git a/package.json b/package.json index 500a8db..e56690e 100644 --- a/package.json +++ b/package.json @@ -41,7 +41,8 @@ "prepublishOnly": "npm run test:prod", "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 && npm run test:mutants && npm run test:module", + "test:all": "npm run test:le && npm run test:be && npm run test:mutants && npm run test:module && npm run test:arithmetic", + "test:arithmetic": "node ./test/arithmetic.mjs", "test:be": "node --import ./test/big-endian.mjs ./test/node.mjs", "test:le": "node ./test/node.mjs", "test:module": "node ./test/module.mjs", diff --git a/src/lib/primordials.ts b/src/lib/primordials.ts index 32737f7..74daa80 100644 --- a/src/lib/primordials.ts +++ b/src/lib/primordials.ts @@ -128,7 +128,14 @@ export function isBytes (a: unknown): a is Bytes { /** Checks system endianness. Returns true if little-endian, else false. */ export const isLE = new Bytes(getBuffer(new Words([1])))[0] === 1 -/** Sets `array[index] = value`. */ +/** + * Sets `array[index] = value` as an element the array owns. Assignment, `push` + * and `fill` all store through the prototype chain when the index is not yet + * defined, and call any setter found there instead, so an accessor added to + * `Array.prototype` after load could swallow the write and answer every read. + * The descriptor has no prototype, so a `get` or `set` added to + * `Object.prototype` cannot make it look like an accessor. + */ export function slot (array: T[], index: number, value: T): void { const descriptor = ObjectCreate(null) descriptor.value = value diff --git a/test/arithmetic.mjs b/test/arithmetic.mjs new file mode 100644 index 0000000..91ccc65 --- /dev/null +++ b/test/arithmetic.mjs @@ -0,0 +1,455 @@ +//! SPDX-FileCopyrightText: 2026 Chris Duncan +//! SPDX-License-Identifier: GPL-3.0-or-later + +/** + * Differential tests of the field, scalar and group arithmetic against the + * independent BigInt reference in `test/reference.mjs`, below the public API. + * + * A probe is compiled from a copy of the sources with memory exported and one + * extra entry file that wraps internal functions over buffers of its own, never + * the shared `t_fe_*`. That reaches inputs no signature can: edge values, loose + * limbs at the bounds ref10 documents, aliased operands, small-order and + * non-canonical points, and zero scalars. + * + * **Points are checked as representations, not only as points.** An extended + * point must satisfy `XY = ZT`. `verify()` once ran its cofactored check on a + * point whose `T` was `X·Y`, which is right only when `Z = 1`; the point itself + * was correct, so comparing points never saw it. + * + * **Inputs are tight signed limbs**, as `fe_frombytes` and `fe_mul` produce + * them. Canonical non-negative limbs push a sum like `Y + X` to 2²⁷ and overflow + * the i32 `19·g` lanes of `fe_mul`. No caller does that, so it would only ever + * show up as a false mismatch. + * + * Positive controls: one probe without the `ge_p3_0(r)` that makes `[0]A + [0]B` + * 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. + * + * Inputs come from a seeded generator, so any failure reproduces. + */ + +import { execFile } from 'node:child_process' +import { createHash } from 'node:crypto' +import { cp, mkdir, readFile, rm, writeFile } from 'node:fs/promises' +import { promisify } from 'node:util' +import { B, D, IDENTITY, L, P, SQRT_M1, TORSION, add, decode, encode, equal, fromLE, isExtended, mod, modinv, mul, negate, order, powmod, toLE } from './reference.mjs' + +const exec = promisify(execFile) +const root = new URL('../', import.meta.url) +const work = new URL('build/arithmetic/', root) +const asc = new URL('node_modules/assemblyscript/bin/asc.js', root).pathname + +/** Wrappers over dedicated buffers, compiled as the probe's entry file. */ +const HARNESS = ` +import './env' +import { fe, fe_add, fe_cmov, fe_dbl, fe_frombytes, fe_invert, fe_isnegative, fe_iszero, fe_mul, fe_neg, fe_pow22523, fe_reduce, fe_sq, fe_sq2, fe_sub, fe_tobytes } from './ed25519/fe' +import { ge_double_scalarmult_vartime_to_p3, ge_frombytes, ge_frombytes_negate_vartime, ge_has_small_order, ge_is_canonical, ge_scalarmult_base_tobytes } from './ed25519/ge' +import { ge_cached, ge_p1p1, ge_p3, ge_p3_tobytes, ge_sub_p3 } from './ed25519/p' +import { sc_is_canonical, sc_muladd, sc_reduce } from './ed25519/sc' + +const FA = fe(), FB = fe(), FH = fe() +const T0 = fe(), T1 = fe(), T2 = fe(), T3 = fe(), T4 = fe(), T5 = fe(), T6 = fe() +const U8A = new StaticArray(32), U8B = new StaticArray(32), U8C = new StaticArray(32), U8D = new StaticArray(32) +const U8T = new StaticArray(32), U8W = new StaticArray(64) +const PA = new ge_p3(), PB = new ge_p3(), PC = new ge_p3() +const CACHED = new ge_cached(), P1P1 = new ge_p1p1() + +export function ptr (id: i32): usize { + switch (id) { + case 0: return changetype(FA) + case 1: return changetype(FB) + case 2: return changetype(FH) + case 3: return changetype(U8A) + case 4: return changetype(U8B) + case 5: return changetype(U8C) + case 6: return changetype(U8D) + case 7: return changetype(U8W) + case 10: return changetype(PA.X) + case 11: return changetype(PA.Y) + case 12: return changetype(PA.Z) + case 13: return changetype(PA.T) + case 20: return changetype(PB.X) + case 21: return changetype(PB.Y) + case 22: return changetype(PB.Z) + case 23: return changetype(PB.T) + case 30: return changetype(PC.X) + case 31: return changetype(PC.Y) + case 32: return changetype(PC.Z) + case 33: return changetype(PC.T) + } + return 0 +} +export function fe_frombytes_ (): void { fe_frombytes(FH, U8A) } +export function fe_tobytes_ (): void { fe_tobytes(U8A, FA, T0) } +export function fe_reduce_ (): void { fe_reduce(FH, FA) } +export function fe_iszero_ (): i32 { return fe_iszero(FA, T0, U8T) } +export function fe_isnegative_ (): i32 { return fe_isnegative(FA, T0) } +export function fe_mul_ (): void { fe_mul(FH, FA, FB) } +export function fe_mul_hf (): void { fe_mul(FA, FA, FB) } +export function fe_mul_hg (): void { fe_mul(FB, FA, FB) } +export function fe_mul_hfg (): void { fe_mul(FA, FA, FA) } +export function fe_sq_ (): void { fe_sq(FH, FA) } +export function fe_sq_hf (): void { fe_sq(FA, FA) } +export function fe_sq2_ (): void { fe_sq2(FH, FA) } +export function fe_add_ (): void { fe_add(FH, FA, FB) } +export function fe_sub_ (): void { fe_sub(FH, FA, FB) } +export function fe_neg_ (): void { fe_neg(FH, FA) } +export function fe_dbl_ (): void { fe_dbl(FH, FA) } +export function fe_cmov_ (b: i32): void { fe_cmov(FA, FB, u64(b)) } +export function fe_invert_ (): void { fe_invert(FH, FA, T0, T1, T2, T3) } +export function fe_pow22523_ (): void { fe_pow22523(FH, FA, T0, T1, T2) } +export function fe_pow22523_hz (): void { fe_pow22523(FA, FA, T0, T1, T2) } +export function sc_reduce_ (): void { sc_reduce(U8W) } +export function sc_muladd_ (): void { sc_muladd(U8D, U8A, U8B, U8C) } +export function sc_is_canonical_ (): i32 { return sc_is_canonical(U8A) ? 1 : 0 } +export function ge_is_canonical_ (): i32 { return ge_is_canonical(U8A) } +export function ge_frombytes_ (): i32 { return ge_frombytes(PA, U8A, T0, T1, T2, U8T) } +export function ge_frombytes_negate_vartime_ (): i32 { return ge_frombytes_negate_vartime(PA, U8A, U8T, T0, T1, T2) } +export function ge_has_small_order_ (): i32 { return ge_has_small_order(PA, T0, U8T) } +export function ge_p3_tobytes_ (): void { ge_p3_tobytes(U8B, PA, T0, T1, T2, T3, T4, T5, T6) } +export function ge_scalarmult_base_tobytes_ (): void { ge_scalarmult_base_tobytes(U8B, U8A, T0, T1, T2, T3, T4, T5, T6) } +export function ge_double_scalarmult_ (): void { ge_double_scalarmult_vartime_to_p3(PB, U8A, PA, U8B, T0) } +export function ge_sub_p3_ (): void { ge_sub_p3(PC, PA, PB, T0, CACHED, P1P1) } +` + +/** Seeded controls: `from` must occur once inside `fn`. */ +const NO_IDENTITY = { file: 'src/assembly/ed25519/ge.ts', fn: 'ge_double_scalarmult_vartime_to_p3', from: '\n\tge_p3_0(r)', to: '' } +const STALE_T = { file: 'src/assembly/ed25519/ge.ts', fn: 'ge_double_scalarmult_vartime_to_p3', from: 'ge_p1p1_to_p3(r, t)', to: 'ge_p1p1_to_p3(r, t)\n\t\t\tfe_mul(r.T, r.X, r.Y)' } + +/** Copies the sources, exports memory, adds the harness, optionally applies one edit, and compiles. */ +async function probe (name, edit) { + 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')) + await writeFile(new URL('src/assembly/harness.ts', dir), HARNESS) + if (edit != null) { + const path = new URL(edit.file, dir) + const source = await readFile(path, 'utf8') + 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(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(edit.from, edit.to) + source.slice(end)) + } + await exec(process.execPath, [asc, 'src/assembly/harness.ts', '--outFile', 'build/harness.wasm'], { cwd: dir.pathname }) + return new WebAssembly.Module(await readFile(new URL('build/harness.wasm', dir))) +} + +/** Deterministic bytes from a seed, so a failure reproduces. */ +function generator (seed) { + let n = 0 + return (length) => { + const out = new Uint8Array(length) + for (let i = 0; i < length; i += 64) { + out.set(createHash('blake2b512').update(`${seed}:${n++}`).digest().subarray(0, Math.min(64, length - i)), i) + } + return out + } +} +const random = generator('nano25519 arithmetic') +const randomInt = (n) => toLE(random(32)) % BigInt(n) +const randomBig = (bytes) => toLE(random(bytes)) + +// limb layout: ten limbs of alternately 26 and 25 bits, then two padding limbs +const WIDTH = [26, 25, 26, 25, 26, 25, 26, 25, 26, 25] +const SHIFT = [0, 26, 51, 77, 102, 128, 153, 179, 204, 230].map(BigInt) +const value = (limbs) => limbs.slice(0, 10).reduce((v, l, i) => v + (BigInt(l) << SHIFT[i]), 0n) +/** Tight signed limbs of `v mod p`, the form `fe_frombytes` produces. */ +function tight (v) { + v = mod(v) + const limbs = WIDTH.map(w => { const l = Number(v & ((1n << BigInt(w)) - 1n)); v >>= BigInt(w); return l }) + for (let i = 0; i < 10; i++) { + if (limbs[i] >= 2 ** (WIDTH[i] - 1)) { + limbs[i] -= 2 ** WIDTH[i] + if (i < 9) limbs[i + 1]++ + else limbs[0] += 19 + } + } + return limbs +} +/** Limbs up to `scale` times their width's half-range, positive or negative. */ +const loose = (scale) => WIDTH.map(w => { const b = Math.floor(scale * 2 ** (w - 1)); return Number(randomInt(2 * b + 1)) - b }) +const within = (limbs, scale) => limbs.slice(0, 10).every((l, i) => Math.abs(l) <= scale * 2 ** (WIDTH[i] - 1)) + +function harness (compiled) { + const x = new WebAssembly.Instance(compiled, { env: { abort (code) { throw new Error(`wasm abort ${code}`) } } }).exports + const limbs = (id) => new Int32Array(x.memory.buffer, x.ptr(id), 12) + const bytes = (id, n = 32) => new Uint8Array(x.memory.buffer, x.ptr(id), n) + return { + x, + bytes, + set: (id, l) => { const a = limbs(id); a.fill(0); a.set(l.slice(0, 10)) }, + get: (id) => Array.from(limbs(id)), + padded: (id) => { const a = limbs(id); return a[10] === 0 && a[11] === 0 }, + setPoint: (base, p) => { const zi = modinv(p[2]), xa = mod(p[0] * zi), ya = mod(p[1] * zi); [xa, ya, 1n, mod(xa * ya)].forEach((c, k) => { const a = limbs(base + k); a.fill(0); a.set(tight(c)) }) }, + setProjective: (base, p) => p.forEach((c, k) => { const a = limbs(base + k); a.fill(0); a.set(tight(c)) }), + getPoint: (base) => [0, 1, 2, 3].map(k => mod(value(Array.from(limbs(base + k))))), + } +} +const [FA, FB, FH, U8A, U8B, U8C, U8D, U8W, PA, PB, PC] = [0, 1, 2, 3, 4, 5, 6, 7, 10, 20, 30] + +/** Runs `[a]A + [b]B` and the subtraction `verify()` makes of it, collecting results under `note`. */ +function doubleScalarmult (h, note, count) { + const { x, bytes, setPoint, getPoint } = h + for (let k = 0; k < count; k++) { + const A = k < 16 ? TORSION[k % 8] : mul(B, randomInt(L)) + const a = k < 48 ? [0n, 1n, L - 1n][k % 3] : randomInt(L) + const b = k % 5 === 0 ? (1n << 253n) - 1n - BigInt(k) : randomInt(1n << 253n) + setPoint(PA, A) + bytes(U8A).set(fromLE(a)) + bytes(U8B).set(fromLE(b)) + x.ge_double_scalarmult_() + const got = getPoint(PB) + const want = add(mul(A, a), mul(B, b)) + note('ge_double_scalarmult_vartime_to_p3: point', equal(got, want), k) + note('ge_double_scalarmult_vartime_to_p3: XY = ZT', isExtended(got), k) + // R - ([a]A + [b]B), as verify() computes it, with R decoded so Z = 1 + const R = mul(B, randomInt(L)) + setPoint(PA, R) + x.ge_sub_p3_() + note('ge_sub_p3 of the double scalar multiplication', equal(getPoint(PC), add(R, negate(want))), k) + } + // both scalars zero right after a call that left a point in r + setPoint(PA, mul(B, 12345n)) + bytes(U8A).set(fromLE(7n)) + bytes(U8B).set(fromLE(9n)) + x.ge_double_scalarmult_() + bytes(U8A).set(fromLE(0n)) + bytes(U8B).set(fromLE(0n)) + x.ge_double_scalarmult_() + const zero = getPoint(PB) + note('ge_double_scalarmult_vartime_to_p3: [0]A + [0]B is the identity', equal(zero, IDENTITY) && isExtended(zero), 0) +} + +function collector () { + const results = {} + const note = (name, ok, input) => { + const r = results[name] ??= { n: 0, bad: 0, first: null } + r.n++ + if (!ok) { + r.bad++ + r.first ??= input + } + } + return { results, note } +} + +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 { + const [clean, noIdentity, staleT] = await Promise.all([ + probe('clean'), + probe('no-identity', NO_IDENTITY).catch((err) => err), + probe('stale-t', STALE_T).catch((err) => err), + ]) + + // positive controls + for (const [name, compiled, expect] of [ + ['sees [0]A + [0]B left as the previous result without ge_p3_0(r)', noIdentity, { 'ge_double_scalarmult_vartime_to_p3: [0]A + [0]B is the identity': false }], + ['sees T recomputed as X·Y, which the point comparison alone does not', staleT, { 'ge_double_scalarmult_vartime_to_p3: point': true, 'ge_double_scalarmult_vartime_to_p3: XY = ZT': false }], + ]) { + if (!(compiled instanceof WebAssembly.Module)) { + check(`control ${name}`, false, String(compiled?.message ?? compiled)) + continue + } + const { results, note } = collector() + doubleScalarmult(harness(compiled), note, 60) + const seen = Object.entries(expect).every(([key, ok]) => results[key] != null && (results[key].bad === 0) === ok) + check(`control ${name}`, seen, Object.entries(results).map(([k, r]) => `${k}: ${r.bad}/${r.n} bad`).join('; ')) + } + + const h = harness(clean) + const { x, bytes, set, get, padded, setPoint, setProjective, getPoint } = h + const { results, note } = collector() + + // field: values, then limb shapes at the bounds ref10 documents + const values = [0n, 1n, 2n, P - 1n, P, P + 1n, (1n << 255n) - 1n, D, SQRT_M1, mod(-D), mod(-SQRT_M1), (P - 1n) / 2n, (P + 1n) / 2n] + for (let k = 0n; k < 255n; k++) values.push(1n << k) + for (let k = 0n; k < 19n; k++) values.push(P + k) + for (let k = 0; k < 400; k++) values.push(randomBig(32) & ((1n << 255n) - 1n)) + const encodings = values.map(v => fromLE(v)) + for (const b of [0x00, 0x7f, 0x80, 0xff]) encodings.push(new Uint8Array(32).fill(b)) + const tightInputs = [] + for (const e of encodings) { + bytes(U8A).set(e) + x.fe_frombytes_() + const l = get(FH) + note('fe_frombytes', mod(value(l)) === mod(toLE(e) & ((1n << 255n) - 1n)) && padded(FH) && within(l, 1.01), e) + tightInputs.push(l.slice(0, 10)) + } + const shapes = [] + for (const scale of [1.1, 1.65]) { + const max = WIDTH.map(w => Math.floor(scale * 2 ** (w - 1))) + shapes.push([scale, max], [scale, max.map(v => -v)], [scale, max.map((v, i) => i & 1 ? -v : v)], [scale, max.map((v, i) => i & 1 ? v : -v)]) + } + for (let k = 0; k < 400; k++) shapes.push([1.65, loose(1.65)], [1.1, loose(1.1)]) + // p + m with every limb at its maximum: only the final reduction brings it below p + for (let m = 0; m < 256; m++) shapes.push([1.1, WIDTH.map((w, i) => i === 0 ? 2 ** 26 - 19 + m : 2 ** w - 1)]) + + for (const l of [...tightInputs, ...shapes.filter(([s]) => s <= 1.1).map(([, l]) => l)]) { + const v = mod(value(l)) + set(FA, l); x.fe_tobytes_() + note('fe_tobytes', toLE(bytes(U8A)) === v, l) + set(FA, l); x.fe_reduce_() + const r = get(FH) + note('fe_reduce', value(r) === v && r.slice(0, 10).every((q, i) => q >= 0 && q < 2 ** WIDTH[i]) && padded(FH), l) + set(FA, l) + note('fe_iszero', x.fe_iszero_() === (v === 0n ? 1 : 0), l) + set(FA, l) + note('fe_isnegative', x.fe_isnegative_() === Number(v & 1n), l) + } + + const operands = [...tightInputs, ...shapes.map(([, l]) => l)] + const pick = () => operands[Number(randomInt(operands.length))] + for (let k = 0; k < 3000; k++) { + const f = k < operands.length ? operands[k] : pick() + const g = pick() + const vf = value(f) + const vg = value(g) + set(FA, f); set(FB, g); x.fe_mul_() + note('fe_mul', mod(value(get(FH))) === mod(vf * vg) && padded(FH) && within(get(FH), 1.1), [f, g]) + set(FA, f); set(FB, g); x.fe_mul_hf() + note('fe_mul with h = f', mod(value(get(FA))) === mod(vf * vg) && padded(FA), [f, g]) + set(FA, f); set(FB, g); x.fe_mul_hg() + note('fe_mul with h = g', mod(value(get(FB))) === mod(vf * vg) && padded(FB), [f, g]) + set(FA, f); x.fe_mul_hfg() + note('fe_mul with h = f = g', mod(value(get(FA))) === mod(vf * vf) && padded(FA), f) + set(FA, f); x.fe_sq_() + note('fe_sq', mod(value(get(FH))) === mod(vf * vf) && padded(FH) && within(get(FH), 1.1), f) + set(FA, f); x.fe_sq_hf() + note('fe_sq with h = f', mod(value(get(FA))) === mod(vf * vf) && padded(FA), f) + set(FA, f); x.fe_sq2_() + note('fe_sq2', mod(value(get(FH))) === mod(2n * vf * vf) && padded(FH) && within(get(FH), 1.1), f) + set(FA, f); set(FB, g); x.fe_add_() + note('fe_add', value(get(FH)) === vf + vg && padded(FH), [f, g]) + set(FA, f); set(FB, g); x.fe_sub_() + note('fe_sub', value(get(FH)) === vf - vg && padded(FH), [f, g]) + set(FA, f); x.fe_neg_() + note('fe_neg', value(get(FH)) === -vf && padded(FH), f) + set(FA, f); x.fe_dbl_() + note('fe_dbl', value(get(FH)) === 2n * vf && padded(FH), f) + set(FA, f); set(FB, g); x.fe_cmov_(k & 1) + note('fe_cmov', value(get(FA)) === (k & 1 ? vg : vf) && padded(FA), [f, g]) + if (k < 600) { + set(FA, f); x.fe_invert_() + const inverse = mod(value(get(FH))) + note('fe_invert', mod(vf) === 0n ? inverse === 0n : mod(inverse * vf) === 1n, f) + const e = (1n << 252n) - 3n + set(FA, f); x.fe_pow22523_() + note('fe_pow22523', mod(value(get(FH))) === powmod(vf, e), f) + set(FA, f); x.fe_pow22523_hz() + note('fe_pow22523 with out = z', mod(value(get(FA))) === powmod(vf, e), f) + } + } + + // scalars + const wide = [0n, 1n, L - 1n, L, L + 1n, 2n * L, L * L, (1n << 512n) - 1n, (1n << 256n) - 1n, (1n << 253n) - 1n] + for (let k = 0n; k < 512n; k++) wide.push(1n << k) + for (let k = 0; k < 500; k++) wide.push(randomBig(64)) + for (const s of wide) { + bytes(U8W, 64).set(fromLE(s, 64)) + x.sc_reduce_() + note('sc_reduce', toLE(bytes(U8W, 32)) === s % L, s) + } + const narrow = [0n, 1n, L - 1n, L, L + 1n, (1n << 252n) - 1n, 1n << 252n, (1n << 253n) - 1n, 1n << 253n, (1n << 255n) - 1n, (1n << 256n) - 1n] + for (let k = 0n; k < 256n; k++) narrow.push(1n << k) + for (let k = 0n; k < 300n; k++) narrow.push(L - 150n + k) + for (let k = 0; k < 2000; k++) narrow.push((1n << 252n) + randomInt(1n << 252n)) + for (let k = 0; k < 300; k++) narrow.push(randomBig(32)) + for (const s of narrow) { + bytes(U8A).set(fromLE(s)) + note('sc_is_canonical', x.sc_is_canonical_() === (s < L ? 1 : 0), s) + } + for (let k = 0; k < 2000; k++) { + const [a, b, c] = [narrow[k % narrow.length], narrow[(k * 7) % narrow.length], narrow[(k * 13) % narrow.length]] + bytes(U8A).set(fromLE(a)); bytes(U8B).set(fromLE(b)); bytes(U8C).set(fromLE(c)) + x.sc_muladd_() + note('sc_muladd', toLE(bytes(U8D)) === (a * b + c) % L, [a, b, c]) + } + + // encodings: torsion with both sign bits, the 19 non-canonical y with both, + // zeros with the sign bit set, valid points and random bytes + const points = [] + for (const T of TORSION) { + const e = encode(T) + points.push(e, Uint8Array.from(e, (v, i) => i === 31 ? v ^ 0x80 : v)) + } + for (let k = 0n; k < 19n; k++) { + points.push(fromLE(P + k)) + const e = fromLE(P + k) + e[31] |= 0x80 + points.push(e) + } + for (const v of [0n, 1n, P - 1n]) { + points.push(fromLE(v)) + const e = fromLE(v) + e[31] |= 0x80 + points.push(e) + } + for (let k = 0; k < 300; k++) points.push(encode(mul(B, randomInt(L))), random(32)) + const isSmall = (p) => order(p) !== 0 + for (const e of points) { + const y = toLE(e) & ((1n << 255n) - 1n) + bytes(U8A).set(e) + note('ge_is_canonical', x.ge_is_canonical_() === (y < P ? 0 : -1), e) + const want = decode(e) + bytes(U8A).set(e) + const rc = x.ge_frombytes_() + const got = getPoint(PA) + note('ge_frombytes', want == null ? rc === -1 : rc === 0 && equal(got, want) && isExtended(got), e) + if (rc === 0) note('ge_has_small_order on decoded points', x.ge_has_small_order_() === (isSmall(want) ? 1 : 0), e) + bytes(U8A).set(e) + const rn = x.ge_frombytes_negate_vartime_() + const gn = getPoint(PA) + note('ge_frombytes_negate_vartime', want == null ? rn === -1 : rn === 0 && equal(gn, negate(want)) && isExtended(gn), e) + } + // projective representations with Z ≠ 1, including small-order and mixed points + for (let k = 0; k < 400; k++) { + const p = k < 64 ? add(TORSION[k % 8], k % 2 ? TORSION[(k >> 1) % 8] : IDENTITY) : k < 128 ? add(mul(B, randomInt(L)), TORSION[k % 8]) : mul(B, randomInt(L)) + const lambda = randomInt(P - 1n) + 1n + setProjective(PA, p.map(c => mod(c * lambda))) + note('ge_has_small_order on projective points', x.ge_has_small_order_() === (isSmall(p) ? 1 : 0), k) + setProjective(PA, p.map(c => mod(c * lambda))) + x.ge_p3_tobytes_() + note('ge_p3_tobytes', toLE(bytes(U8B)) === toLE(encode(p)), k) + } + // fixed-base multiplication over every signed radix-16 digit at every position + const scalars = [0n, 1n, 2n, L - 1n, L, L + 1n, (1n << 255n) - 1n, 1n << 254n, 1n << 252n] + for (const v of [0x88, 0x77, 0x08, 0x80, 0x7f, 0x11]) scalars.push(toLE(new Uint8Array(32).fill(v)) & ((1n << 255n) - 1n)) + for (let k = 0; k < 1500; k++) scalars.push(randomBig(32) & ((1n << 255n) - 1n)) + for (let k = 0; k < 200; k++) scalars.push(((randomBig(32) & ((1n << 254n) - 8n)) | (1n << 254n))) + for (const a of scalars) { + bytes(U8A).set(fromLE(a)) + x.ge_scalarmult_base_tobytes_() + note('ge_scalarmult_base_tobytes', toLE(bytes(U8B)) === toLE(encode(mul(B, a))), a) + } + doubleScalarmult(h, note, 400) + + let comparisons = 0 + for (const [name, r] of Object.entries(results)) { + comparisons += r.n + check(`${name} (${r.n} input${r.n === 1 ? '' : 's'})`, r.bad === 0, r.bad ? `${r.bad} disagree, first ${String(r.first).slice(0, 160)}` : '') + } + console.log(`${comparisons} comparisons`) +} finally { + await rm(work, { recursive: true, force: true }) +} + +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`) +process.exitCode = failures > 0 ? 1 : 0 diff --git a/test/node.mjs b/test/node.mjs index 4e1f8e6..baad5b8 100644 --- a/test/node.mjs +++ b/test/node.mjs @@ -187,20 +187,20 @@ passes += +test failures += +!test // Check verification of live cemented block from small-order public key -result = verify(PROBLEM_VECTOR.signature, PROBLEM_VECTOR.blockHash, PROBLEM_VECTOR.publicKey) +result = attempt(() => verify(PROBLEM_VECTOR.signature, PROBLEM_VECTOR.blockHash, PROBLEM_VECTOR.publicKey)) test = result === false check(`verify strict check fails for problematic signature string ${PROBLEM_VECTOR.signature}`, test) passes += +test failures += +!test -result = verify_blocks(PROBLEM_VECTOR.publicKey, [{ signature: PROBLEM_VECTOR.signature, hash: PROBLEM_VECTOR.blockHash }])[0] +result = attempt(() => verify_blocks(PROBLEM_VECTOR.publicKey, [{ signature: PROBLEM_VECTOR.signature, hash: PROBLEM_VECTOR.blockHash }])[0]) test = result === true check(`verify_blocks relaxed check passes problematic signature string ${PROBLEM_VECTOR.signature}`, test) passes += +test failures += +!test // Check identity signature verifies -result = verify_blocks(IDENTITY.publicKeyBytes, [{ signature: IDENTITY.signatureBytes, hash: new Uint8Array(32) }]) +result = attempt(() => verify_blocks(IDENTITY.publicKeyBytes, [{ signature: IDENTITY.signatureBytes, hash: new Uint8Array(32) }])) test = result[0] === true check(`verify identity signature bytes ${IDENTITY.signature}`, test) passes += +test @@ -212,7 +212,7 @@ const accepted = [] for (let i = 0; i < constants.KEY_BYTELENGTH; i++) { for (let j = 1; j < 256; j++) { forgery[i] ^= j - result = verify_blocks(IDENTITY.publicKeyBytes, [{ signature: forgery, hash: new Uint8Array(32) }])[0] + result = attempt(() => verify_blocks(IDENTITY.publicKeyBytes, [{ signature: forgery, hash: new Uint8Array(32) }])[0]) forgery[i] = IDENTITY.signatureBytes[i] if (result !== false) { accepted.push({ byte: i, mask: `0x${j.toString(16).padStart(2, '0')}` }) @@ -233,7 +233,7 @@ failures += +!test const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR // 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 + test = attempt(() => verify(sig, hash, pub)) === true && attempt(() => 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 @@ -268,7 +268,7 @@ failures += +!test const otherPrv = prv.slice() otherPrv[0] ^= 1 const otherPub = new Uint8Array(constants.KEY_BYTELENGTH) - derive(otherPrv, otherPub) + attempt(() => 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) @@ -310,8 +310,8 @@ failures += +!test // the checks below are only as good as the vectors, so pin what they cover test = signatures.map(({ order }) => order).join() === '1,2,4,4,8,8,8,8' && signatures[0].signature === NANO_ORG_VECTOR.signature - && verify(signatures[0].signature, blockHash, publicKey) === true - && verify_blocks(publicKey, [{ signature: signatures[0].signature, hash: blockHash }])[0] === true + && attempt(() => verify(signatures[0].signature, blockHash, publicKey)) === true + && attempt(() => verify_blocks(publicKey, [{ signature: signatures[0].signature, hash: blockHash }])[0]) === true check('torsion vectors cover all eight small-order points, and the order-1 row is the verified nano.org signature', test) passes += +test failures += +!test @@ -393,7 +393,7 @@ failures += +!test const { privateKey, privateKeyBytes, publicKeyBytes } = NANO_ORG_VECTOR const message = Uint8Array.from({ length: 256 }, (_, i) => i) const lower = [...message].map(b => b.toString(16).padStart(2, '0')).join('') - const expected = sign(message, privateKeyBytes, publicKeyBytes) + const expected = attempt(() => sign(message, privateKeyBytes, publicKeyBytes)) /** @type {Record} */ const cases = { lower, upper: lower.toUpperCase(), mixed: [...lower].map((c, i) => i & 1 ? c.toUpperCase() : c).join('') } const wrong = Object.entries(cases).filter(([, hex]) => attempt(() => sign(hex, privateKeyBytes, publicKeyBytes)) !== expected).map(([name]) => name) @@ -453,45 +453,45 @@ passes += +test failures += +!test // Check string inputs -result = derive(NANO_ORG_VECTOR.privateKey) +result = attempt(() => derive(NANO_ORG_VECTOR.privateKey)) test = result.toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() check(`derive from private key string ${NANO_ORG_VECTOR.privateKey}`, test) passes += +test failures += +!test -result = sign(NANO_ORG_VECTOR.blockHash, NANO_ORG_VECTOR.privateKey, NANO_ORG_VECTOR.publicKey) +result = attempt(() => sign(NANO_ORG_VECTOR.blockHash, NANO_ORG_VECTOR.privateKey, NANO_ORG_VECTOR.publicKey)) test = result.toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase() check(`sign message string ${NANO_ORG_VECTOR.blockHash}`, test) passes += +test failures += +!test -result = verify(NANO_ORG_VECTOR.signature, NANO_ORG_VECTOR.blockHash, NANO_ORG_VECTOR.publicKey) +result = attempt(() => verify(NANO_ORG_VECTOR.signature, NANO_ORG_VECTOR.blockHash, NANO_ORG_VECTOR.publicKey)) test = result === true check(`verify signature string ${NANO_ORG_VECTOR.signature}`, test) passes += +test failures += +!test // Check byte inputs -result = derive(NANO_ORG_VECTOR.privateKeyBytes) +result = attempt(() => derive(NANO_ORG_VECTOR.privateKeyBytes)) test = result.toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() check(`derive from private key bytes ${NANO_ORG_VECTOR.privateKey}`, test) passes += +test failures += +!test outbuf = new Uint8Array(32) -derive(NANO_ORG_VECTOR.privateKeyBytes, outbuf) +attempt(() => derive(NANO_ORG_VECTOR.privateKeyBytes, outbuf)) test = [...outbuf].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() check(`derive from private key bytes to output buffer`, test) passes += +test failures += +!test -result = sign(NANO_ORG_VECTOR.blockHashBytes, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes) +result = attempt(() => sign(NANO_ORG_VECTOR.blockHashBytes, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes)) test = result.toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase() check(`sign message bytes ${NANO_ORG_VECTOR.blockHash}`, test) passes += +test failures += +!test -result = verify(NANO_ORG_VECTOR.signatureBytes, NANO_ORG_VECTOR.blockHashBytes, NANO_ORG_VECTOR.publicKeyBytes) +result = attempt(() => verify(NANO_ORG_VECTOR.signatureBytes, NANO_ORG_VECTOR.blockHashBytes, NANO_ORG_VECTOR.publicKeyBytes)) test = result === true check(`verify signature bytes ${NANO_ORG_VECTOR.signature}`, test) passes += +test @@ -501,7 +501,7 @@ failures += +!test inbuf = new Uint8Array(bigBuf.buffer.slice(), 0, 32) inbuf.set(NANO_ORG_VECTOR.privateKeyBytes) outbuf = new Uint8Array(32) -derive(inbuf, outbuf) +attempt(() => derive(inbuf, outbuf)) test = [...outbuf].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() check(`derive from private key bytes ${NANO_ORG_VECTOR.privateKey} and allocate result to output buffer`, test) passes += +test @@ -510,7 +510,7 @@ failures += +!test inbuf = new Uint8Array(bigBuf.buffer.slice(), 0, 32) inbuf.set(NANO_ORG_VECTOR.privateKeyBytes) outbuf = new Uint8Array(64) -sign(NANO_ORG_VECTOR.blockHashBytes, inbuf, NANO_ORG_VECTOR.publicKeyBytes, outbuf) +attempt(() => sign(NANO_ORG_VECTOR.blockHashBytes, inbuf, NANO_ORG_VECTOR.publicKeyBytes, outbuf)) test = [...outbuf].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase() check(`sign message bytes ${NANO_ORG_VECTOR.blockHash} and allocate result to output buffer`, test) passes += +test @@ -519,7 +519,7 @@ failures += +!test inbuf = new Uint8Array(bigBuf.buffer.slice(), 1, 32) inbuf.set(NANO_ORG_VECTOR.privateKeyBytes) outbuf = new Uint8Array(bigBuf.buffer.slice(), 0, 32) -derive(inbuf, outbuf) +attempt(() => derive(inbuf, outbuf)) test = [...outbuf].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() test &&= [...new Uint8Array(outbuf.buffer, 0, 32)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() test &&= [...new Uint8Array(outbuf.buffer, 32, 32)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === 'ff'.repeat(32) @@ -530,7 +530,7 @@ failures += +!test inbuf = new Uint8Array(bigBuf.buffer.slice(), 1, 32) inbuf.set(NANO_ORG_VECTOR.privateKeyBytes) outbuf = new Uint8Array(bigBuf.buffer.slice(), 0, 64) -sign(NANO_ORG_VECTOR.blockHashBytes, inbuf, NANO_ORG_VECTOR.publicKeyBytes, outbuf) +attempt(() => sign(NANO_ORG_VECTOR.blockHashBytes, inbuf, NANO_ORG_VECTOR.publicKeyBytes, outbuf)) test = [...outbuf].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase() test &&= [...new Uint8Array(outbuf.buffer, 0, 64)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase() test &&= [...new Uint8Array(outbuf.buffer, 64, 64)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === 'ff'.repeat(64) @@ -540,7 +540,7 @@ failures += +!test // Check byte inputs and offset output buffer outbuf = new Uint8Array(new ArrayBuffer(128), 32, 32) -derive(NANO_ORG_VECTOR.privateKeyBytes, outbuf) +attempt(() => derive(NANO_ORG_VECTOR.privateKeyBytes, outbuf)) test = [...outbuf].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() test &&= [...new Uint8Array(outbuf.buffer, 0, 32)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === '00'.repeat(32) test &&= [...new Uint8Array(outbuf.buffer, 32, 32)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase() @@ -549,7 +549,7 @@ passes += +test failures += +!test outbuf = new Uint8Array(new ArrayBuffer(128), 64, 64) -sign(NANO_ORG_VECTOR.blockHashBytes, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes, outbuf) +attempt(() => sign(NANO_ORG_VECTOR.blockHashBytes, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes, outbuf)) test = [...outbuf].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase() test &&= [...new Uint8Array(outbuf.buffer, 0, 64)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === '00'.repeat(64) test &&= [...new Uint8Array(outbuf.buffer, 64, 64)].map(b => b.toString(16).padStart(2, '0')).join('').toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase() @@ -858,7 +858,7 @@ class HostileBytes extends Uint8Array { } speciesRan = 0 //@ts-expect-error -result = derive(new HostileBytes(NANO_ORG_VECTOR.privateKeyBytes)) +result = attempt(() => derive(new HostileBytes(NANO_ORG_VECTOR.privateKeyBytes))) test = result === NANO_ORG_VECTOR.publicKey.toLowerCase() && speciesRan === 0 check(`derive ignores a hostile Uint8Array subclass`, test) passes += +test @@ -870,9 +870,9 @@ failures += +!test // whatever a patched %TypedArray%.prototype.buffer or DataView getUint32 handed // them. The message is 65 bytes so it crosses as two whole chunks plus a // one-byte tail, exercising both marshalling paths. -const truth = derive(NANO_ORG_VECTOR.privateKeyBytes) +const truth = attempt(() => derive(NANO_ORG_VECTOR.privateKeyBytes)) const patchedMessage = new Uint8Array(65).map((_, i) => (i * 37 + 11) & 255) -const truthSignature = sign(patchedMessage, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes) +const truthSignature = attempt(() => sign(patchedMessage, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes)) // one valid and one forged block: a patch that answers `true` for every result // passes a valid-only batch, so the forged block is what exposes it const patchedForgery = NANO_ORG_VECTOR.signatureBytes.slice() diff --git a/test/reference.mjs b/test/reference.mjs new file mode 100644 index 0000000..e2c6c8b --- /dev/null +++ b/test/reference.mjs @@ -0,0 +1,291 @@ +//! SPDX-FileCopyrightText: 2026 Chris Duncan +//! SPDX-License-Identifier: GPL-3.0-or-later + +/** + * An independent BigInt implementation of Ed25519 over BLAKE2b, written from + * the curve's definitions rather than from this project's code, so that it can + * arbitrate a disagreement without trusting either side. It is slow and + * variable-time, and is for tests only. + * + * Points are extended coordinates `[X, Y, Z, T]` with `x = X/Z`, `y = Y/Z` and + * `XY = ZT`. Byte strings are `Uint8Array`, little-endian. + */ + +import { createHash } from 'node:crypto' + +/** The field prime `p = 2²⁵⁵ - 19`. */ +export const P = (1n << 255n) - 19n + +/** The order of the base point, `L = 2²⁵² + 27742317777372353535851937790883648493`. */ +export const L = (1n << 252n) + 27742317777372353535851937790883648493n + +/** + * @param {bigint} a + * @param {bigint} [m] + */ +export function mod (a, m = P) { + const r = a % m + return r < 0n ? r + m : r +} + +/** + * Inverse by the extended Euclidean algorithm. The inverse of 0 is 0. + * @param {bigint} a + * @param {bigint} [m] + */ +export function modinv (a, m = P) { + let r0 = mod(a, m) + let r1 = m + let s0 = 1n + let s1 = 0n + while (r1 !== 0n) { + const q = r0 / r1 + const r = r0 - q * r1 + r0 = r1 + r1 = r + const s = s0 - q * s1 + s0 = s1 + s1 = s + } + return r0 === 1n ? mod(s0, m) : 0n +} + +/** + * @param {bigint} b + * @param {bigint} e + * @param {bigint} [m] + */ +export function powmod (b, e, m = P) { + let r = 1n + b = mod(b, m) + while (e > 0n) { + if (e & 1n) r = r * b % m + b = b * b % m + e >>= 1n + } + return r +} + +/** `d = -121665 / 121666` */ +export const D = mod(-121665n * modinv(121666n)) + +/** `√-1` */ +export const SQRT_M1 = powmod(2n, (P - 1n) / 4n) + +/** The neutral element. */ +export const IDENTITY = [0n, 1n, 1n, 0n] + +/** + * Unified addition in extended coordinates, add-2008-hwcd-3 with `a = -1`. + * @param {bigint[]} p + * @param {bigint[]} q + */ +export function add (p, q) { + const [X1, Y1, Z1, T1] = p + const [X2, Y2, Z2, T2] = q + const A = mod((Y1 - X1) * (Y2 - X2)) + const B = mod((Y1 + X1) * (Y2 + X2)) + const C = mod(T1 * 2n * D * T2) + const E = mod(Z1 * 2n * Z2) + const [F, G, H, J] = [B - A, E - C, E + C, B + A] + return [mod(F * G), mod(H * J), mod(G * H), mod(F * J)] +} + +/** @param {bigint[]} p */ +export function negate (p) { + return [mod(-p[0]), p[1], p[2], mod(-p[3])] +} + +/** + * `[k]p` by double-and-add, for any `k ≥ 0`. + * @param {bigint[]} p + * @param {bigint} k + */ +export function mul (p, k) { + let r = IDENTITY + for (; k > 0n; k >>= 1n) { + if (k & 1n) r = add(r, p) + p = add(p, p) + } + return r +} + +/** + * True when `p` and `q` are the same point, whatever their representations. + * @param {bigint[]} p + * @param {bigint[]} q + */ +export function equal (p, q) { + return mod(p[0] * q[2] - q[0] * p[2]) === 0n && mod(p[1] * q[2] - q[1] * p[2]) === 0n +} + +/** + * True when `p` is a well-formed extended representation of a curve point: + * `Z ≠ 0`, `XY = ZT`, and `-X² + Y² = Z² + dT²`, the curve equation scaled by `Z²`. + * @param {bigint[]} p + */ +export function isExtended (p) { + const [X, Y, Z, T] = p + return mod(Z) !== 0n && mod(X * Y - Z * T) === 0n && mod(Y * Y - X * X - Z * Z - D * T * T) === 0n +} + +/** @param {Uint8Array} b */ +export function toLE (b) { + let n = 0n + for (let i = b.length - 1; i >= 0; i--) n = (n << 8n) | BigInt(b[i]) + return n +} + +/** + * @param {bigint} n + * @param {number} [length] + */ +export function fromLE (n, length = 32) { + const b = new Uint8Array(length) + for (let i = 0; i < length; i++, n >>= 8n) b[i] = Number(n & 0xffn) + return b +} + +/** @param {Uint8Array} b */ +export function hex (b) { + return [...b].map(v => v.toString(16).padStart(2, '0')).join('') +} + +/** @param {string} s */ +export function bytes (s) { + return Uint8Array.from(s.match(/../g) ?? [], v => parseInt(v, 16)) +} + +/** `y` with the sign of `x` in bit 255. @param {bigint[]} p */ +export function encode (p) { + const zi = modinv(p[2]) + const x = mod(p[0] * zi) + const y = mod(p[1] * zi) + return fromLE(y | ((x & 1n) << 255n)) +} + +/** + * Decodes as ref10 and ed25519-donna do: `y` is the low 255 bits reduced mod `p`, + * so the 19 non-canonical encodings decode too, and `x = 0` is accepted with + * either sign bit. Returns `null` when no `x` exists. + * @param {Uint8Array} s + */ +export function decode (s) { + const y = mod(toLE(s) & ((1n << 255n) - 1n)) + const sign = BigInt(s[31] >> 7) + // v = dy² + 1 is never 0, because -1/d is not a square + const x2 = mod((y * y - 1n) * modinv(D * y * y + 1n)) + if (x2 === 0n) return [0n, y, 1n, 0n] + if (powmod(x2, (P - 1n) / 2n) !== 1n) return null + let x = powmod(x2, (P + 3n) / 8n) + if (mod(x * x) !== x2) x = mod(x * SQRT_M1) + if ((x & 1n) !== sign) x = mod(-x) + return [x, y, 1n, mod(x * y)] +} + +/** The base point `(x, 4/5)` with `x` even. */ +export const B = /** @type {bigint[]} */ (decode(fromLE(mod(4n * modinv(5n))))) + +/** + * The order of `p` if it divides 8, else 0. + * @param {bigint[]} p + */ +export function order (p) { + let q = p + for (let n = 1; n <= 8; n++, q = add(q, p)) { + if (equal(q, IDENTITY)) return n + } + return 0 +} + +/** + * The eight points of order dividing 8: `[L]Q` for decodable `Q` until all are + * found, since `[L]` kills the prime-order part and leaves the torsion part. + */ +export const TORSION = (() => { + const found = [] + for (let y = 2n; found.length < 8; y++) { + for (const sign of [0, 0x80]) { + const s = fromLE(y) + s[31] |= sign + const Q = decode(s) + if (Q == null) continue + const T = mul(Q, L) + if (!found.some(t => equal(t, T))) found.push(T) + } + } + return found +})() + +/** @param {...Uint8Array} parts */ +export function blake2b (...parts) { + const h = createHash('blake2b512') + for (const part of parts) h.update(part) + return new Uint8Array(h.digest()) +} + +/** + * Public key, clamped secret scalar and nonce prefix of a 32-byte private key. + * @param {Uint8Array} prv + */ +export function derive (prv) { + const h = blake2b(prv) + const s = h.slice(0, 32) + s[0] &= 248 + s[31] &= 127 + s[31] |= 64 + const a = toLE(s) + return { A: encode(mul(B, a)), a, prefix: h.slice(32) } +} + +/** + * Deterministic signature, with its intermediate values. + * @param {Uint8Array} prv + * @param {Uint8Array} msg + */ +export function sign (prv, msg) { + const { A, a, prefix } = derive(prv) + const r = toLE(blake2b(prefix, msg)) % L + const R = encode(mul(B, r)) + const k = toLE(blake2b(R, A, msg)) % L + const signature = new Uint8Array(64) + signature.set(R) + signature.set(fromLE(mod(r + k * a, L)), 32) + return { signature, A, a, r, k } +} + +/** + * ed25519-donna's `ed25519_sign_open`, the rule `verify_blocks()` follows: + * `S < 2²⁵³`, any decodable key, and `R` compared as bytes with the encoding of + * `[S]B - [k]A`. + * @param {Uint8Array} sig + * @param {Uint8Array} msg + * @param {Uint8Array} pk + */ +export function verifyDonna (sig, msg, pk) { + if (sig[63] & 224) return false + const A = decode(pk) + if (A == null) return false + const k = toLE(blake2b(sig.subarray(0, 32), pk, msg)) % L + const S = toLE(sig.subarray(32)) + return hex(encode(add(mul(B, S), mul(negate(A), k)))) === hex(sig.subarray(0, 32)) +} + +/** + * The rule `verify()` follows: `S < L`; key and `R` canonical, decodable and + * not of small order; and the cofactored equation `[8](R - [S]B + [k]A) = O`. + * @param {Uint8Array} sig + * @param {Uint8Array} msg + * @param {Uint8Array} pk + */ +export function verifyCofactored (sig, msg, pk) { + const canonical = (s) => (toLE(s) & ((1n << 255n) - 1n)) < P + const S = toLE(sig.subarray(32)) + if (S >= L) return false + const A = canonical(pk) ? decode(pk) : null + if (A == null || order(A) !== 0) return false + const R = canonical(sig.subarray(0, 32)) ? decode(sig.subarray(0, 32)) : null + if (R == null || order(R) !== 0) return false + const k = toLE(blake2b(sig.subarray(0, 32), pk, msg)) % L + return order(add(R, add(mul(A, k), negate(mul(B, S))))) !== 0 +}