]> git.codecow.com Git - nano25519.git/commitdiff
Update tests, agent file, and README.
authorChris Duncan <chris@codecow.com>
Fri, 16 Oct 2026 18:52:24 +0000 (11:52 -0700)
committerChris Duncan <chris@codecow.com>
Fri, 16 Oct 2026 18:52:24 +0000 (11:52 -0700)
AGENTS.md
README.md
test/node.mjs
test/vectors.mjs
test/vectors/index.ts
test/vectors/nano_org.ts
test/vectors/torsion.ts

index 544ec5d4433e37c90b00b613ee07dedb1d9ef442..b8ab2a03d47fe258eedb79d017ad56cfb8d5e1d8 100644 (file)
--- a/AGENTS.md
+++ b/AGENTS.md
@@ -108,8 +108,8 @@ every compile. Edit the generator, not its output.
 | `src/index.ts` | Public API and its overloads: `derive`, `sign`, `verify`, `verify_blocks` |
 | `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/bytes.ts` | Prototype methods and accessors captured at load, the helpers built on them, `normalize()`, and hex encoding and constant-time decoding. Imports only `errors.ts`, which imports nothing |
-| `src/lib/{derive,sign,verify}.ts` | Host-side marshalling, one file per primitive |
+| `src/lib/bytes.ts` | Prototype methods, accessors, the typed array constructors and `String.fromCharCode` captured at load, the helpers built on them, `normalize()`, and hex encoding and constant-time decoding. Imports only `errors.ts`, which imports nothing |
+| `src/lib/{derive,sign,verify}.ts` | Host-side marshalling, one file per primitive. `verify.ts` captures the static functions `verify_blocks` uses |
 | `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/ed25519/{fe,ge,p,sc}.ts` | Field element, group element, point, and scalar arithmetic |
@@ -128,7 +128,7 @@ every compile. Edit the generator, not its output.
 | `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/vectors/torsion.ts` | The nano.org signature with `R` offset by each small-order point, and with `R` at the identity |
 | `test/index.html` | Browser test and benchmark page |
 
 ## The wasm ABI
@@ -245,33 +245,42 @@ Use `isBytes()`, `byteLength()`, `copy()` and `fill()` on every typed array,
 the caller's and the package's own alike, because they are also the captures
 below.
 
-**Prototype methods are captured at load; global constructors and static
-functions are not.** Every prototype method and accessor the host calls on a
-call path is taken from its prototype once, when `bytes.ts` is evaluated, and
-called through a bound `Function.prototype.call`: the `%TypedArray%.prototype`
-getters, `set` and `fill`, the `ArrayBuffer.prototype.byteLength` getter, and
+**Everything a call path uses to reach a key or a result is captured at
+load.** Every prototype method and accessor the host calls on a call path is
+taken from its prototype once, when `bytes.ts` is evaluated, and called through
+a bound `Function.prototype.call`: the `%TypedArray%.prototype` getters, `set`
+and `fill`, the `ArrayBuffer.prototype.byteLength` getter, and
 `String.prototype.charCodeAt`. Code that patches a prototype after the package
 loads therefore cannot change what is validated, copied, scrubbed or decoded.
-Global constructors and static functions such as `Uint8Array`, `Uint32Array`,
-`Array.isArray`, `Object.create` and `Object.defineProperty` are looked up at
-call time. Replacing them is out of scope, as is anything that runs before the
-package loads: such code shares the caller's realm and can take the key wherever
-the caller handles it. An application that needs its realm intact should freeze
-it, with SES `lockdown()` or Node's `--frozen-intrinsics`, before loading this
-package. A new prototype method or accessor on a call path must be captured in
-`bytes.ts` and added to the patch list in `test/node.mjs`; a new global or
-static function need not be.
+The `Uint8Array` and `Uint32Array` constructors are captured there too, because
+key bytes pass through both: `words()` builds a `Uint32Array` over the private
+key's own buffer, so a global replaced after load was handed every key, and it
+still would be under `--frozen-intrinsics` and SES `lockdown()`, which freeze
+intrinsics but leave global bindings writable. Allocate with `allocate()`,
+never `new Uint8Array`, on a call path. `verify.ts` captures `Array.isArray`,
+`Object.create`, `Object.defineProperty` and `Object.freeze`, which build
+`verify_blocks`'s result: replacing `Object.defineProperty` after load once
+made a forged block read `true`. `bytes.ts` captures `String.fromCharCode`,
+which `bytesToHex()` encodes every returned key and signature with. Nothing on
+a call path is looked up at call time. Code that runs before the package loads
+is out of scope: it shares the caller's realm and can replace the package's
+exports outright. A new prototype method, constructor or static function on a
+call path must be captured at load and added to the patch list in
+`test/node.mjs`; that is also why the batch-length check compares against
+`Infinity` instead of calling `Number.isFinite`.
 
 `test:frozen` runs the suite under `--frozen-intrinsics`, so the package must
 never write to a built-in, at load or later: a polyfill would make it
 unloadable in a locked-down realm. Node tames some assignments that would trip
 over a frozen prototype, such as an `Error` subclass assigning its own
 `prototype.name`, so the run catches writes to built-ins themselves, not every
-assignment a stricter lockdown might refuse. SES itself is not tested.
+assignment a stricter lockdown might refuse. SES itself is not part of the
+suite; `test/node.mjs` passed after `lockdown()` from `ses` 2.3.0 on 2026-10-16,
+6220 / 0, with the same patches skipped as under frozen intrinsics.
 
 **Results are defined, never assigned.** `verify_blocks` defines each element
-of its `boolean[]` with `Object.defineProperty` and a descriptor from
-`Object.create(null)`. Assignment, `push` and `fill` all store through the
+of its `boolean[]` with the captured `Object.defineProperty` and a descriptor
+from the captured `Object.create(null)`. 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
@@ -280,15 +289,16 @@ descriptor needs no prototype of its own, or a `get` added to
 list in `test/node.mjs` patches both. The array is then frozen and returned as
 `readonly boolean[]`: assigning a result, `push`, `pop`, `sort` and truncating
 `length` all throw in strict mode and fail silently otherwise, while reads,
-`map` and `slice` work. Nothing in the suite asserts the freeze.
+`map` and `slice` work. The single-block `verify_blocks` check in
+`test/node.mjs` asserts the freeze, and so does every patched run.
 
 **Host code that carries a secret is constant time.** A hex private key is
 decoded in `hexToBytes` by arithmetic on each character code, with no table
 lookup and no early exit: validity accumulates and is checked once at the end,
 and the error never names the character. A `NIBBLE[char]` lookup measured
 fixed-vs-random |t| 5.5–8.6 against a null control ≤ 0.56. The arithmetic
-decoder read 0.80–2.23 over four runs on 2026-10-15, against a random-vs-random
-null of 1.18–3.49, all under the 4.5 alarm. Byte keys move only through
+decoder read 0.36–1.39 over four runs on 2026-10-16, against a random-vs-random
+null of 0.21–1.29, all under the 4.5 alarm. Byte keys move only through
 `copy()`, `fill()` and the word packing in `wasm.ts`. Keep anything a private key passes through free of secret-dependent
 branches, indexing and lookups. A hex string cannot be scrubbed, because
 JavaScript strings are immutable; a caller who cares passes bytes and clears
@@ -555,14 +565,16 @@ show up on the clock; only the point arithmetic does.
 
 `npm test` builds, then runs six suites: `test/node.mjs` little-endian,
 big-endian and under `--frozen-intrinsics`, then `test:mutants`, `test:module`
-and `test:arithmetic`. Current state is **6300, 6300, 6205, 17, 12 and 36
-passing, 0 failing**; the frozen run skips the 95 patch-list checks, since its
-prototypes cannot be patched. 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.
+and `test:arithmetic`. Current state is **6340, 6340, 6220, 17, 12 and 36
+passing, 0 failing**; the frozen run skips the 120 checks under prototype and
+static patches, since frozen intrinsics cannot be patched, but keeps the 10
+under global replacements. 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
@@ -750,6 +762,21 @@ 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.
 
+### Rules applied before the equation
+
+The checks each path makes before its final equation need signatures that
+satisfy the equation, or a dropped check stays invisible: each of these was
+removed once and all six suites stayed green. `test/node.mjs` takes the nano.org
+signature with `S + L`, which is `NANO_ORG_VECTOR.badSignature` and is pinned
+to that, and with `S + 2L`, both of which give the same `[S]B`, and
+`IDENTITY_NONCE_VECTOR` from `test/vectors/torsion.ts`, the nano.org key
+signing with `R` at the identity and `S = ka`, so `[S]B - [k]A = R` exactly.
+`verify()` must reject all three, through `S < L` and its small-order check on
+`R`. `verify_blocks()` must accept `S + L` and the identity nonce, as nano_node
+does, which also shows they satisfy the equation, and reject `S + 2L` through
+`S < 2²⁵³`. The canonicity checks on the key and on `R` have no such vector,
+since no valid signature can carry a non-canonical encoding.
+
 ### Hostile arguments, patched prototypes, re-entrancy and hex input
 
 A `Uint8Array` subclass that lies through `Symbol.species`, `length`,
@@ -757,20 +784,28 @@ A `Uint8Array` subclass that lies through `Symbol.species`, `length`,
 byte argument of every primitive and as both output buffers. Each call must
 return what plain bytes return, and the subclass's code must never run. Views
 over a `SharedArrayBuffer`, a bare `SharedArrayBuffer`, a `Uint16Array` and an
-output buffer that lies about its `byteLength` must each be rejected.
+output buffer that lies about its `byteLength` must each be rejected. A Proxy
+over a blocks array, which passes `Array.isArray`, reporting a length of `'1'`,
+`NaN` or an infinity must be refused as an invalid length, and `1.5` by the
+missing second block.
 
 The patch list at the end of `test/node.mjs` replaces 19 prototype methods and
-accessors after load and runs every primitive under every patch, `derive` once
+accessors, and the 5 static functions the host captures, after load and
+runs every primitive under every patch, `derive` once
 from bytes and once from hex: `Function.prototype.call`,
 `String.prototype.charCodeAt`, typed-array and array methods and accessors,
 index accessors on `Array.prototype`, and `get`, `set` and `Symbol.iterator` on
 `Object.prototype`. Some patch methods the host never calls, such as `slice`,
 `padStart` and `DataView.prototype.getUint32`, so that starting to call one
 uncaptured is caught. 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. Global constructors and static functions
-are not patched (see **Host-side invariants**). `test:frozen` skips the list,
-since frozen prototypes cannot be patched.
+block and requires own elements and a frozen array, because a patch that
+answers `true` for everything passes a valid-only batch. `verify` takes its message as hex and
+`sign` as bytes, so both copies `normalize()` allocates are made under every
+patch. After those patches, `globalThis.Uint8Array` and
+`globalThis.Uint32Array` are replaced with constructors that throw, and every
+primitive runs again. `test:frozen` skips the prototype and static patches, since
+frozen intrinsics cannot be patched, but runs the two replacements, since
+frozen intrinsics leave global bindings writable.
 
 Errors raised while the mutex is held — invalid input to `derive`, `sign` and
 `verify`, a bad block or key in `verify_blocks`, a throwing block getter, and a
index 4e884e801758b2b7bad597e94246cbd05bdb2d9b..3c459784bfc4f4dbdac4e9cc05cac0f851fed7f5 100644 (file)
--- a/README.md
+++ b/README.md
@@ -203,16 +203,17 @@ const blocks = [
   }
 ];
 
-// `v` is an array of booleans, one per block in the same order, 'true' where
-// the Nano network would accept the signature for that block
+// `v` is a frozen array of booleans, one per block in the same order, 'true'
+// where the Nano network would accept the signature for that block
 const v = nano25519.verify_blocks(pub, blocks);
 ```
 
 `verify_blocks()` checks up to `nano25519.constants.MAX_VERIFY_BLOCKS` (64)
 blocks from one account per call, decoding the public key once for the whole
 batch. It throws a `RangeError` for an empty or oversized batch and a
-`TypeError` for a malformed block. A public key that cannot be decoded makes
-every result `false`.
+`TypeError` for a malformed batch or block. A public key that cannot be decoded
+makes every result `false`. The returned array is frozen, so it must be copied
+with `slice()` before changing it.
 
 `verify()` and `verify_blocks()` deliberately answer different questions, and
 they disagree on some real blocks cemented in the Nano ledger:
@@ -242,13 +243,14 @@ the API functions.
 
 ## Security
 
-Arguments are validated and copied before use, and prototype methods are
-captured on load, so monkey patching them afterwards cannot alter results.
-However, it does **not** defend against code that runs before it nor any code
-that replaces global objects like `Uint8Array`; that kind of conflict is not
-preventable, so if that is a concern,
-[HardenedJavaScript](https://hardenedjs.org/) and/or the NodeJS
-`--frozen-intrinsics` flag should be used.
+Arguments are validated and copied before use. Prototype methods, `Uint8Array`
+and `Uint32Array` constructors, and `Object`, `Array` and `String` functions are
+captured on load, so patching or replacing them afterwards cannot alter results
+or expose a key. `nano25519` does **not** defend against code that runs before
+it loads. [HardenedJavaScript](https://hardenedjs.org/) `lockdown()` and the
+NodeJS `--frozen-intrinsics` flag prevent patching of built-ins, but they leave
+global variables writable, so code must run in its own compartment or realm to
+truly avoid conflicts.
 
 While effort has been applied to secure this code base, it has not been audited
 by a third-party, so it provides no guarantee of security, fitness, or accuracy.
@@ -266,23 +268,27 @@ optimized to take advantage of SIMD parallelism using WebAssembly vector types.
 
 ## Tests
 
-A few basic tests are available in the source repository under `test/`.
+Tests are available in the source repository under `test/`.
 
-- `index.html` is a web interface to test browser execution and compare
-  performance with other browser-based implementations.
-- `node.mjs` is a test for NodeJS to check result validity. It runs a
-  derive-sign-verify sequence for public test vectors obtained from the
-  python-ed25519-blake2b library.
-- `big-endian.mjs` runs the NodeJS test again but replaces the global
-  `Uint32Array` before loading the package to emulate toggled endianness.
-- `vectors.mjs` is generated by `esbuild` using the files found in
-  `test/vectors`.
+- `node.mjs` tests the public API in NodeJS: the python-ed25519-blake2b test
+  vectors, forged and malleated signatures, small-order points, hostile
+  arguments, and built-ins patched after loading.
+- `big-endian.mjs` runs `node.mjs` again but replaces the global `Uint32Array`
+  before loading the package to emulate toggled endianness.
 - `mutants.mjs` builds copies of the module with known defects and checks that
   the self-tests built into the module refuse to load every one of them.
+- `module.mjs` drives the WebAssembly module directly to check that no secret
+  is left in its memory and that every input buffer is cleared.
+- `arithmetic.mjs` compares the field, scalar and group arithmetic against
+  `reference.mjs`, an independent implementation used only by the tests.
+- `vectors.mjs` is generated by `esbuild` using the files found in
+  `test/vectors`.
+- `index.html` is a web interface to test browser execution and compare
+  performance with other browser-based implementations.
 
-Tests are run with a debug build using `npm t` and a production build with
-`npm run test:prod`. Mutation tests are run with `npm run test:mutants`, and the
-NodeJS test under frozen built-ins with `npm run test:frozen`.
+`npm test` runs every suite against a debug build, and `npm run test:prod`
+against a production build. `node.mjs` runs three times: as is, big-endian, and
+under NodeJS `--frozen-intrinsics`.
 
 ## Building
 
index 8655932d3117641c92bb6f2014be33abe933926e..a78fc58855fafd8522d64bd88488f1e42f7f97dc 100644 (file)
@@ -2,7 +2,7 @@
 //! SPDX-License-Identifier: GPL-3.0-or-later
 
 import { constants, derive, sign, verify, verify_blocks } from 'nano25519'
-import { IDENTITY, NANO_ORG_VECTOR, PROBLEM_VECTOR, PYTHON_ED25519_BLAKE2B_VECTORS, TORSION_VECTORS } from './vectors.mjs'
+import { IDENTITY, IDENTITY_NONCE_VECTOR, NANO_ORG_VECTOR, PROBLEM_VECTOR, PYTHON_ED25519_BLAKE2B_VECTORS, TORSION_VECTORS } from './vectors.mjs'
 
 /**
  * @param {string} name
@@ -347,6 +347,47 @@ failures += +!test
        failures += +!test
 }
 
+// Rules each path applies before its equation, tested with signatures that
+// satisfy the equation, since nothing else can tell a dropped rule apart. S + L
+// (badSignature) and S + 2L give the same [S]B as S, and a nonce at the
+// identity with S = ka gives [S]B - [k]A = R. verify() must reject all three,
+// through S < L and its small-order check on R. verify_blocks() must accept
+// S + L and the identity nonce, as nano_node does, which also shows they
+// satisfy the equation, and reject S + 2L, which is not below 2²⁵³.
+{
+       const { badSignature, blockHashBytes: hash, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
+       const L = (1n << 252n) + 27742317777372353535851937790883648493n
+       let S = 0n
+       for (let i = 63; i >= 32; i--) S = (S << 8n) | BigInt(sig[i])
+       /** @param {bigint} s */
+       const withS = (s) => {
+               const out = sig.slice()
+               for (let i = 32; i < 64; i++, s >>= 8n) out[i] = Number(s & 0xffn)
+               return out
+       }
+
+       // the check below is only as good as the vector, so pin what it is
+       test = [...withS(S + L)].map(b => b.toString(16).padStart(2, '0')).join('') === badSignature.toLowerCase()
+       check('badSignature is the nano.org signature with S + L', test)
+       passes += +test
+       failures += +!test
+
+       /** @type {[string, Uint8Array | string, boolean][]} */
+       const cases = [
+               ['S + L', badSignature, true],
+               ['S + 2L, not below 2²⁵³', withS(S + 2n * L), false],
+               ['a nonce at the identity, signed by the key holder', IDENTITY_NONCE_VECTOR.signature, true],
+       ]
+       for (const [name, signature, relaxed] of cases) {
+               const strict = attempt(() => verify(signature, hash, pub))
+               const batch = attempt(() => verify_blocks(pub, [{ signature, hash }])[0])
+               test = strict === false && batch === relaxed
+               check(`verify rejects and verify_blocks ${relaxed ? 'accepts' : 'rejects'} ${name}${test ? '' : ` (verify ${strict}, verify_blocks ${batch})`}`, test)
+               passes += +test
+               failures += +!test
+       }
+}
+
 // An error raised while the mutex is held must release it. derive() and sign()
 // check their output buffers, and verify_blocks() its block count, before taking
 // the lock, so those throws never reach the finally that unlocks; these do.
@@ -499,13 +540,13 @@ check(`verify signature bytes ${NANO_ORG_VECTOR.signature}`, test)
 passes += +test
 failures += +!test
 
-// Check byte inputs and preallocated output buffer
+// Check byte inputs that are views, and preallocated output buffers
 inbuf = new Uint8Array(bigBuf.buffer.slice(), 0, 32)
 inbuf.set(NANO_ORG_VECTOR.privateKeyBytes)
 outbuf = new Uint8Array(32)
 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)
+check(`derive from a private key view over a larger buffer to output buffer`, test)
 passes += +test
 failures += +!test
 
@@ -514,7 +555,7 @@ inbuf.set(NANO_ORG_VECTOR.privateKeyBytes)
 outbuf = new Uint8Array(64)
 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)
+check(`sign with a private key view over a larger buffer to output buffer`, test)
 passes += +test
 failures += +!test
 
@@ -525,7 +566,7 @@ 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)
-check(`derive from private key bytes ${NANO_ORG_VECTOR.privateKey} and allocate result to output buffer`, test)
+check(`derive from a private key at byteOffset 1 to an output view, leaving the rest of its buffer untouched`, test)
 passes += +test
 failures += +!test
 
@@ -536,7 +577,7 @@ attempt(() => sign(NANO_ORG_VECTOR.blockHashBytes, inbuf, NANO_ORG_VECTOR.public
 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)
-check(`sign message bytes ${NANO_ORG_VECTOR.blockHash} and allocate result to output buffer`, test)
+check(`sign with a private key at byteOffset 1 to an output view, leaving the rest of its buffer untouched`, test)
 passes += +test
 failures += +!test
 
@@ -800,6 +841,30 @@ check(`verify_blocks missing signature`, test)
 passes += +test
 failures += +!test
 
+// A Proxy over an array passes Array.isArray and reports whatever length it
+// likes. A non-number, NaN or an infinity is refused by the host as an invalid
+// length; a fraction slips past it and must still be refused, by the missing
+// block. Each must leave the lock released.
+{
+       const block = { hash: NANO_ORG_VECTOR.blockHashBytes, signature: NANO_ORG_VECTOR.signatureBytes }
+       /** @type {[unknown, string | null][]} */
+       const lengths = [['1', 'threw Invalid blocks length'], [NaN, 'threw Invalid blocks length'], [Infinity, 'threw Invalid blocks length'], [-Infinity, 'threw Invalid blocks length'], [1.5, null]]
+       /** @type {string[]} */
+       const wrong = []
+       for (const [length, expected] of lengths) {
+               const blocks = new Proxy([block], { get: (t, k) => k === 'length' ? length : Reflect.get(t, k) })
+               const r = attempt(() => verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, blocks))
+               if (expected == null ? (typeof r !== 'string' || !r.startsWith('threw') || r.includes('mutex')) : r !== expected) {
+                       wrong.push(`${String(length)}: ${JSON.stringify(r)}`)
+               }
+       }
+       const after = attempt(() => verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, [block])[0])
+       test = wrong.length === 0 && after === true
+       check(`verify_blocks refuses a blocks length that is not a whole number${test ? '' : ` (${wrong.join('; ')}; next call ${after})`}`, test)
+       passes += +test
+       failures += +!test
+}
+
 // Shared memory is rejected on both inputs and output buffers: isBytes()
 // requires a non-shared ArrayBuffer, so a view over a SharedArrayBuffer never
 // gets through. A bare SharedArrayBuffer stays rejected too (covered above).
@@ -887,15 +952,19 @@ failures += +!test
        }
 }
 
-// Prototype methods and accessors patched after the module loaded must not
-// change results. Global constructors and static functions are resolved at call
-// time and are not tested here. Every primitive runs under every patch. derive never touches the message
-// buffer, so a derive-only loop stayed green while sign and verify were signing
-// 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.
+// Prototype methods and accessors patched after the module loaded, the
+// static functions the host captures, and the Uint8Array and Uint32Array
+// globals replaced after it loaded, must not change results. Every primitive
+// runs under every patch. derive never touches the message buffer, so a
+// derive-only loop stayed green while sign and verify were signing 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. sign takes it as bytes and verify
+// as hex, so both of the copies normalize() allocates are made under every
+// patch; its hex form is built here, before any patch is applied.
 const truth = attempt(() => derive(NANO_ORG_VECTOR.privateKeyBytes))
 const patchedMessage = new Uint8Array(65).map((_, i) => (i * 37 + 11) & 255)
+const patchedMessageHex = [...patchedMessage].map(b => b.toString(16).padStart(2, '0')).join('')
 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
@@ -1036,23 +1105,73 @@ const patches = [
                Object.defineProperty(Object.prototype, Symbol.iterator, { * value () { yield true; yield true }, configurable: true, writable: true })
                //@ts-expect-error
                return () => { delete Object.prototype[Symbol.iterator] }
+       }],
+       // static functions captured at load; frozen with their constructors, so
+       // they are skipped under test:frozen like the rest
+       ['Array.isArray', () => {
+               const real = Array.isArray
+               //@ts-expect-error
+               Array.isArray = () => false
+               return () => { Array.isArray = real }
+       }],
+       ['Object.create', () => {
+               const real = Object.create
+               Object.create = () => { throw new Error('patched') }
+               return () => { Object.create = real }
+       }],
+       ['Object.defineProperty', () => {
+               const real = Object.defineProperty
+               Object.defineProperty = () => { throw new Error('patched') }
+               return () => { Object.defineProperty = real }
+       }],
+       // bytesToHex() encodes every returned key and signature with this
+       ['String.fromCharCode', () => {
+               const real = String.fromCharCode
+               String.fromCharCode = () => 'zz'
+               return () => { String.fromCharCode = real }
+       }],
+       ['Object.freeze', () => {
+               const real = Object.freeze
+               //@ts-expect-error
+               Object.freeze = (o) => o
+               return () => { Object.freeze = real }
        }]
 ]
+// The typed array constructors are captured at load because key bytes pass
+// through both: a replaced Uint32Array would be handed the private key's buffer
+// by the word packing. Global bindings stay writable under frozen intrinsics
+// and SES lockdown, so these run under test:frozen too.
+/** @type {[string, (() => () => void)][]} */
+const replacements = [
+       ['globalThis.Uint8Array', () => {
+               const real = globalThis.Uint8Array
+               //@ts-expect-error
+               globalThis.Uint8Array = () => { throw new Error('patched') }
+               return () => { globalThis.Uint8Array = real }
+       }],
+       ['globalThis.Uint32Array', () => {
+               const real = globalThis.Uint32Array
+               //@ts-expect-error
+               globalThis.Uint32Array = () => { throw new Error('patched') }
+               return () => { globalThis.Uint32Array = real }
+       }],
+]
 /** @type {[string, () => boolean][]} */
 const patchedPrimitives = [
        ['derive', () => derive(NANO_ORG_VECTOR.privateKeyBytes) === truth],
        ['derive from hex', () => derive(NANO_ORG_VECTOR.privateKey) === truth],
        ['sign', () => sign(patchedMessage, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes) === truthSignature],
-       ['verify', () => verify(truthSignature, patchedMessage, NANO_ORG_VECTOR.publicKeyBytes) === true],
+       ['verify', () => verify(truthSignature, patchedMessageHex, NANO_ORG_VECTOR.publicKeyBytes) === true],
        ['verify_blocks', () => {
                const r = verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, patchedBlocks)
-               return r.length === 2 && Object.keys(r).length === 2 && r[0] === true && r[1] === false
+               return r.length === 2 && Object.keys(r).length === 2 && r[0] === true && r[1] === false && Object.isFrozen(r)
        }]
 ]
-// Under frozen intrinsics (test:frozen) none of these patches can be applied,
-// which is the point of freezing them, so the list is skipped there.
+// Under frozen intrinsics (test:frozen) none of the prototype or static patches
+// can be applied, which is the point of freezing them, so only the global
+// replacements run there.
 const frozen = Object.isFrozen(Uint8Array.prototype)
-for (const [name, apply] of frozen ? [] : patches) {
+for (const [name, apply] of frozen ? replacements : [...patches, ...replacements]) {
        for (const [primitive, run] of patchedPrimitives) {
                const undo = apply()
                try {
index ffc2459ae7381bc1830d456d5952c10fce8434f3..419d9341fc19f441a9302666d2d8de08f0c046cd 100644 (file)
@@ -21,6 +21,7 @@ var NANO_ORG_VECTOR = {
   publicKeyBytes: new Uint8Array([48, 104, 187, 28, 160, 69, 37, 187, 14, 65, 108, 72, 95, 230, 166, 127, 213, 37, 64, 34, 125, 38, 124, 200, 182, 232, 218, 149, 138, 127, 160, 57]),
   signature: "74BCC59DBA39A1E34A5F75F96D6DE9154E3477AAD7DE30EA563DFCFE501A804228008F98DDF4A15FD35705102785C50EF76732C3A74B0FEC5B0DD67B574A5900",
   signatureBytes: new Uint8Array([116, 188, 197, 157, 186, 57, 161, 227, 74, 95, 117, 249, 109, 109, 233, 21, 78, 52, 119, 170, 215, 222, 48, 234, 86, 61, 252, 254, 80, 26, 128, 66, 40, 0, 143, 152, 221, 244, 161, 95, 211, 87, 5, 16, 39, 133, 197, 14, 247, 103, 50, 195, 167, 75, 15, 236, 91, 13, 214, 123, 87, 74, 89, 0]),
+  /** `signature` with `L` added to `S`: still below 2²⁵³, so nano_node accepts it */
   badSignature: "74BCC59DBA39A1E34A5F75F96D6DE9154E3477AAD7DE30EA563DFCFE501A804215d484f5f757b4b7a9f4fcb2057fa423f76732c3a74b0fec5b0dd67b574a5910",
   invalidMessageLength: "BB569136FA05F8CBF65CEF2EDE368475B289C4477342976556BA4C0DDF216E450"
 };
@@ -6197,8 +6198,15 @@ var TORSION_VECTORS = {
     { order: 8, torsion: "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", signature: "782F89C856BEF8A46756EFA1DF1C342409E5CB590085348B1628CC954B27E9AB6E77645E0F349DEDC9917D7B2B8E890B3B5D60C6476090C778B17E84AFC81000" }
   ]
 };
+var IDENTITY_NONCE_VECTOR = {
+  privateKey: "781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3",
+  publicKey: "3068BB1CA04525BB0E416C485FE6A67FD52540227D267CC8B6E8DA958A7FA039",
+  blockHash: "BB569136FA05F8CBF65CEF2EDE368475B289C4477342976556BA4C0DDF216E45",
+  signature: "0100000000000000000000000000000000000000000000000000000000000000DA3CCEFF6271953AB66C9369E2AE90A4F28F82EA256419E3A22D58CD6E5D3300"
+};
 export {
   IDENTITY,
+  IDENTITY_NONCE_VECTOR,
   NANO_ORG_VECTOR,
   RSNANO_PROBLEM_VECTOR as PROBLEM_VECTOR,
   PYTHON_ED25519_BLAKE2B_VECTORS,
index 739d9d3d3ebd24af84bfa05d428ae3e008d744a2..84f7ae967293120f8b0e8f6c38d9b9144e67c957 100644 (file)
@@ -4,4 +4,4 @@
 export { IDENTITY } from './identity.js'
 export { NANO_ORG_VECTOR, RSNANO_PROBLEM_VECTOR as PROBLEM_VECTOR } from './nano_org.js'
 export { PYTHON_ED25519_BLAKE2B_VECTORS } from './python_ed25519_blake2b.js'
-export { TORSION_VECTORS } from './torsion.js'
+export { IDENTITY_NONCE_VECTOR, TORSION_VECTORS } from './torsion.js'
index 57021f09d199fa3610789c9df576cfe520617410..f41058f53cfcb1ce2f38a312794d50b9ce2509d7 100644 (file)
@@ -15,6 +15,7 @@ export const NANO_ORG_VECTOR = {
        publicKeyBytes: new Uint8Array([0x30, 0x68, 0xBB, 0x1C, 0xA0, 0x45, 0x25, 0xBB, 0x0E, 0x41, 0x6C, 0x48, 0x5F, 0xE6, 0xA6, 0x7F, 0xD5, 0x25, 0x40, 0x22, 0x7D, 0x26, 0x7C, 0xC8, 0xB6, 0xE8, 0xDA, 0x95, 0x8A, 0x7F, 0xA0, 0x39]),
        signature: '74BCC59DBA39A1E34A5F75F96D6DE9154E3477AAD7DE30EA563DFCFE501A804228008F98DDF4A15FD35705102785C50EF76732C3A74B0FEC5B0DD67B574A5900',
        signatureBytes: new Uint8Array([0x74, 0xBC, 0xC5, 0x9D, 0xBA, 0x39, 0xA1, 0xE3, 0x4A, 0x5F, 0x75, 0xF9, 0x6D, 0x6D, 0xE9, 0x15, 0x4E, 0x34, 0x77, 0xAA, 0xD7, 0xDE, 0x30, 0xEA, 0x56, 0x3D, 0xFC, 0xFE, 0x50, 0x1A, 0x80, 0x42, 0x28, 0x00, 0x8F, 0x98, 0xDD, 0xF4, 0xA1, 0x5F, 0xD3, 0x57, 0x05, 0x10, 0x27, 0x85, 0xC5, 0x0E, 0xF7, 0x67, 0x32, 0xC3, 0xA7, 0x4B, 0x0F, 0xEC, 0x5B, 0x0D, 0xD6, 0x7B, 0x57, 0x4A, 0x59, 0x00]),
+       /** `signature` with `L` added to `S`: still below 2²⁵³, so nano_node accepts it */
        badSignature: '74BCC59DBA39A1E34A5F75F96D6DE9154E3477AAD7DE30EA563DFCFE501A804215d484f5f757b4b7a9f4fcb2057fa423f76732c3a74b0fec5b0dd67b574a5910',
        invalidMessageLength: 'BB569136FA05F8CBF65CEF2EDE368475B289C4477342976556BA4C0DDF216E450',
 }
index 479bb252c5fa551dedd78ae80724a53441178ee3..7356a0fc7a4f3a07d321a32f14eeb0cd2632e84b 100644 (file)
@@ -30,3 +30,21 @@ export const TORSION_VECTORS = {
                { order: 8, torsion: 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', signature: '782F89C856BEF8A46756EFA1DF1C342409E5CB590085348B1628CC954B27E9AB6E77645E0F349DEDC9917D7B2B8E890B3B5D60C6476090C778B17E84AFC81000' },
        ],
 }
+
+/**
+ * The nano.org key signing the nano.org block hash with the identity as its
+ * nonce point:
+ *
+ * `R = O`, `k = BLAKE2b(R || A || M) mod L`, `S = ka mod L`
+ *
+ * Only the key holder can make it. `[S]B - [k]A` is the identity, so it encodes
+ * to exactly `R` and the byte comparison of `verify_blocks()` accepts it, as
+ * nano_node would, while only the small-order check on `R` makes `verify()`
+ * reject it. Generated with an independent BigInt implementation.
+ */
+export const IDENTITY_NONCE_VECTOR = {
+       privateKey: '781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3',
+       publicKey: '3068BB1CA04525BB0E416C485FE6A67FD52540227D267CC8B6E8DA958A7FA039',
+       blockHash: 'BB569136FA05F8CBF65CEF2EDE368475B289C4477342976556BA4C0DDF216E45',
+       signature: '0100000000000000000000000000000000000000000000000000000000000000DA3CCEFF6271953AB66C9369E2AE90A4F28F82EA256419E3A22D58CD6E5D3300',
+}