]> git.codecow.com Git - nano25519.git/commitdiff
Update tests.
authorChris Duncan <chris@codecow.com>
Sat, 10 Oct 2026 08:33:29 +0000 (01:33 -0700)
committerChris Duncan <chris@codecow.com>
Sat, 10 Oct 2026 08:33:29 +0000 (01:33 -0700)
test/module.mjs
test/node.mjs
test/vectors.mjs
test/vectors/index.ts
test/vectors/torsion.ts [new file with mode: 0644]

index 39d3aec60a69f7cf3d470fa24febde749495762f..e60fdfd898c577f21d1590e6bd6bc6288d035953 100644 (file)
@@ -3,7 +3,7 @@
 
 /**
  * Tests that drive the compiled module directly through its integer ABI, below
- * the host layer, for two properties the public API cannot observe.
+ * the host layer, for three properties the public API cannot observe.
  *
  * **No secret residue.** After `derive`, `sign` and a failed `sign`, followed
  * by the `clearMemory()` the host runs on every unlock, linear memory must not
  * reads it with a strict `=== 1`; this is the property that keeps a looser
  * comparison there from ever mattering.
  *
+ * **Inputs scrubbed on every path.** Each export must leave the input buffers
+ * it reads zeroed when it returns or throws, before `clearMemory()` repeats the
+ * job. The residue diff runs after `clearMemory()`, so it cannot see this. Each
+ * buffer is located by a pattern written through its setter, the message
+ * buffer is also written past the length the call declares, and every success
+ * and throw path is read back before `clearMemory()`.
+ *
  * Positive controls prove each check can fire: the search finds the public key
  * before `clearMemory()`, the diff sees the public key output, a second probe
- * with `clear_t()` removed from `crypto_derive` must show residue, and both
- * result values must actually occur.
+ * with `clear_t()` removed from `crypto_derive` must show residue, a third with
+ * the `INPUT_SIG` scrub removed from the length check in `verify` must fail the
+ * input check there and nowhere else, and both result values must actually
+ * occur.
  *
  * Probes are compiled under `build/module/` with the project's own
  * `asconfig.json`, changed only in the copy.
@@ -40,6 +49,9 @@ const asc = new URL('node_modules/assemblyscript/bin/asc.js', root).pathname
 /** The line a dropped scrub removes; `from` must occur once inside `fn`. */
 const DROPPED_SCRUB = { file: 'src/assembly/crypto_derive.ts', fn: 'crypto_derive', from: '\n\tclear_t()' }
 
+/** A throw-path scrub that only the input-buffer check can see. */
+const DROPPED_INPUT_SCRUB = { file: 'src/assembly/index.ts', fn: 'verify', from: '\n\t\tINPUT_SIG.fill(0)' }
+
 /** Copies the sources, exports memory, optionally drops one line, and compiles. */
 async function probe (name, drop) {
        const dir = new URL(`${name}/`, work)
@@ -144,6 +156,78 @@ function copies (mem, s) {
 /** Input-dependent bytes left after `clearMemory()`, by memory diff. */
 const residue = (mod, op) => differing(run(mod, op, keyOf(1)).after, run(mod, op, keyOf(2)).after)
 
+/**
+ * Nonzero bytes that occur nowhere else in memory, so a search finds exactly the
+ * buffer written. Hashed from the name: patterns sharing an arithmetic step
+ * would contain one another.
+ */
+const pattern = (name, n) => createHash('blake2b512').update(name).digest().subarray(0, n).map(b => b | 1)
+const PATTERNS = { INPUT_MSG: pattern('INPUT_MSG', 32), INPUT_PRV: pattern('INPUT_PRV', 32), INPUT_PUB: pattern('INPUT_PUB', 32), INPUT_SIG: pattern('INPUT_SIG', 64) }
+
+/**
+ * Locates each input buffer by writing its pattern through its setter, and
+ * returns the address and byte length of each, with memory cleared again.
+ */
+function inputBuffers (x) {
+       x.setInputMsg(0, ...words(PATTERNS.INPUT_MSG))
+       x.setInputPrv(...words(PATTERNS.INPUT_PRV))
+       x.setInputPub(...words(PATTERNS.INPUT_PUB))
+       x.setInputSig(...words(PATTERNS.INPUT_SIG))
+       const mem = Buffer.from(x.memory.buffer)
+       const lengths = { INPUT_MSG: x.MAX_MESSAGE_BYTELENGTH.value, INPUT_PRV: 32, INPUT_PUB: 32, INPUT_SIG: 64 }
+       const found = {}
+       for (const [name, bytes] of Object.entries(PATTERNS)) {
+               const at = mem.indexOf(bytes)
+               if (at < 0 || mem.indexOf(bytes, at + 1) >= 0) throw new Error(`cannot locate ${name}`)
+               found[name] = [at, lengths[name]]
+       }
+       x.clearMemory()
+       return found
+}
+
+/**
+ * Every success and throw path of every export, each given only the inputs it
+ * reads. The message is also written at the top of its buffer, past the
+ * declared length, so a scrub scoped to that length leaves it behind.
+ */
+function inputPaths (mod) {
+       const prv = keyOf(1)
+       const pub = derive(instance(mod), prv)
+       const max = instance(mod).MAX_MESSAGE_BYTELENGTH.value
+       const msg = (x) => {
+               x.setInputMsg(0, ...words(PATTERNS.INPUT_MSG))
+               x.setInputMsg(max - 32, ...words(PATTERNS.INPUT_MSG))
+       }
+       const keys = (x, p = pub) => { x.setInputPrv(...words(prv)); x.setInputPub(...words(p)) }
+       const sig = (x) => x.setInputSig(...words(PATTERNS.INPUT_SIG))
+       const record = (x) => { x.setInputMsg(0, ...words(PATTERNS.INPUT_SIG.subarray(0, 32))); x.setInputMsg(32, ...words(PATTERNS.INPUT_SIG.subarray(32))); x.setInputMsg(64, ...words(PATTERNS.INPUT_MSG)); x.setInputMsg(max - 32, ...words(PATTERNS.INPUT_MSG)) }
+       return {
+               'derive': (x) => { x.setInputPrv(...words(prv)); x.derive() },
+               'sign': (x) => { msg(x); keys(x); x.sign(32) },
+               'sign, mismatched public key': (x) => { msg(x); keys(x, PATTERNS.INPUT_PUB); x.sign(32) },
+               'sign, invalid length': (x) => { msg(x); keys(x); x.sign(max + 1) },
+               'verify': (x) => { msg(x); x.setInputPub(...words(pub)); sig(x); x.verify(32) },
+               'verify, invalid length': (x) => { msg(x); x.setInputPub(...words(pub)); sig(x); x.verify(-1) },
+               'verify_blocks': (x) => { record(x); x.setInputPub(...words(pub)); x.verify_blocks(1) },
+               'verify_blocks, invalid count': (x) => { record(x); x.setInputPub(...words(pub)); x.verify_blocks(0) },
+       }
+}
+
+/** `path: BUFFER` for every input buffer a path leaves nonzero, read before `clearMemory()`. */
+function unscrubbed (mod) {
+       const left = []
+       for (const [path, call] of Object.entries(inputPaths(mod))) {
+               const x = instance(mod)
+               const buffers = inputBuffers(x)
+               try { call(x) } catch { }
+               const mem = new Uint8Array(x.memory.buffer)
+               for (const [name, [at, length]] of Object.entries(buffers)) {
+                       if (mem.subarray(at, at + length).some(b => b !== 0)) left.push(`${path}: ${name}`)
+               }
+       }
+       return left
+}
+
 let passes = 0
 let failures = 0
 function check (name, test, detail = '') {
@@ -157,7 +241,11 @@ await rm(work, { recursive: true, force: true })
 try {
        // a control that cannot be seeded is a failed check, not a crash, so the
        // residue checks below still run and report
-       const [clean, dropped] = await Promise.all([probe('clean'), probe('dropped-scrub', DROPPED_SCRUB).catch((err) => err)])
+       const [clean, dropped, droppedInput] = await Promise.all([
+               probe('clean'),
+               probe('dropped-scrub', DROPPED_SCRUB).catch((err) => err),
+               probe('dropped-input-scrub', DROPPED_INPUT_SCRUB).catch((err) => err),
+       ])
 
        // positive controls: the search and the diff can both fire
        const control = run(clean, 'derive', keyOf(1))
@@ -177,6 +265,13 @@ try {
                check(`no copy of any secret representation after ${op}`, found.length === 0, found.join(', '))
        }
 
+       // inputs scrubbed by each export itself, on success and throw paths alike
+       const seededInput = droppedInput instanceof WebAssembly.Module ? unscrubbed(droppedInput) : [String(droppedInput?.message ?? droppedInput)]
+       check('input check sees the INPUT_SIG left by a verify length check without its scrub',
+               seededInput.includes('verify, invalid length: INPUT_SIG'), seededInput.join('; ') || 'nothing seen')
+       const left = unscrubbed(clean)
+       check(`every export leaves its input buffers zeroed on all ${Object.keys(inputPaths(clean)).length} success and throw paths`, left.length === 0, left.join('; '))
+
        // OUTPUT_VERIFY must only ever hold 0 or 1, across valid, forged, malformed,
        // undecodable and degenerate inputs on both verification paths
        const x = instance(clean)
@@ -227,5 +322,5 @@ try {
 
 console.log(`${passes} \x1b[32mPASSED\x1b[0m`)
 console.log(`${failures} \x1b[31mFAILED\x1b[0m`)
-console.log(`2 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
+console.log(`3 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
 process.exitCode = failures > 0 ? 1 : 0
index 6f6c41cbfc2625f125062096eadce5ebbc1a49bc..4e1f8e6f2bb6b83fd0ac03694ac2edd737bff407 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 } from './vectors.mjs'
+import { IDENTITY, NANO_ORG_VECTOR, PROBLEM_VECTOR, PYTHON_ED25519_BLAKE2B_VECTORS, TORSION_VECTORS } from './vectors.mjs'
 
 /**
  * @param {string} name
@@ -15,6 +15,18 @@ function check (name, test) {
        console.log(`${test ? '\x1b[32mPASS' : '\x1b[31mFAIL'}\x1b[0m: ${name}`)
 }
 
+/**
+ * Runs `f`, turning a throw into a string so it can be compared as a result.
+ * @param {() => unknown} f
+ */
+function attempt (f) {
+       try {
+               return f()
+       } catch (err) {
+               return `threw ${typeof err === 'object' && err != null && 'message' in err ? err.message : err}`
+       }
+}
+
 const bigBuf = new Uint8Array(128).fill(255)
 let inbuf, outbuf, result, test, passes = 0, failures = 0
 
@@ -219,14 +231,6 @@ failures += +!test
 // and not only in the 64 KiB message sweeps further down.
 {
        const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
-       /** @param {() => unknown} f */
-       const attempt = (f) => {
-               try {
-                       return f()
-               } catch (err) {
-                       return `threw ${typeof err === 'object' && err != null && 'message' in err ? err.message : err}`
-               }
-       }
 
        // the checks below only assert rejections, so assert the baseline too or they die quietly
        test = verify(sig, hash, pub) === true && verify_blocks(pub, [{ hash, signature: sig }])[0] === true
@@ -290,6 +294,131 @@ failures += +!test
        failures += +!test
 }
 
+// A nonce offset by a small-order point, R' = rB + T, with S recomputed by the
+// key holder. These are the only signatures whose final equation leaves a
+// torsion difference, so they are the only ones that tell a cofactored check
+// from a cofactorless one, or from a broken one: verify() once rejected every
+// order-8 offset while accepting orders 2 and 4, and the suite stayed green.
+{
+       const { publicKey, blockHash, signatures } = TORSION_VECTORS
+       /** @param {string} hex */
+       const bytes = (hex) => new Uint8Array(hex.match(/.{2}/g)?.map(b => parseInt(b, 16)) ?? [])
+       const offsets = signatures.filter(({ order }) => order > 1)
+       /** @param {{ order: number, torsion: string }} v */
+       const label = ({ order, torsion }) => `order ${order} ${torsion.slice(0, 8)}`
+
+       // 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
+       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
+
+       let missed = offsets.filter((v) => attempt(() => verify(v.signature, blockHash, publicKey)) !== true
+               || attempt(() => verify(bytes(v.signature), bytes(blockHash), bytes(publicKey))) !== true).map(label)
+       test = missed.length === 0
+       check(`verify accepts a nonce offset by each point of order 2, 4 and 8${test ? '' : ` (rejected ${missed.join(', ')})`}`, test)
+       passes += +test
+       failures += +!test
+
+       missed = offsets.filter((v) => attempt(() => verify_blocks(publicKey, [{ signature: v.signature, hash: blockHash }])[0]) !== false).map(label)
+       result = attempt(() => verify_blocks(publicKey, signatures.map(({ signature }) => ({ signature, hash: blockHash }))))
+       test = missed.length === 0 && Array.isArray(result) && result.join() === 'true,false,false,false,false,false,false,false'
+       check(`verify_blocks rejects a nonce offset by each point of order 2, 4 and 8${test ? '' : ` (accepted ${missed.join(', ')}; batch ${result})`}`, test)
+       passes += +test
+       failures += +!test
+
+       // acceptance must come from the equation, not from the torsion: the same
+       // nonces with the unmodified S, or with one bit of S flipped, must fail
+       missed = []
+       for (const v of offsets) {
+               const stale = v.signature.slice(0, 64) + signatures[0].signature.slice(64)
+               const flipped = bytes(v.signature)
+               flipped[32] ^= 1
+               if (attempt(() => verify(stale, blockHash, publicKey)) !== false || attempt(() => verify(flipped, bytes(blockHash), bytes(publicKey))) !== false) {
+                       missed.push(label(v))
+               }
+       }
+       test = missed.length === 0
+       check(`verify rejects a torsion-offset nonce whose S does not match it${test ? '' : ` (accepted ${missed.join(', ')})`}`, test)
+       passes += +test
+       failures += +!test
+}
+
+// An error raised while the mutex is held must release it. derive() and sign()
+// validate their inputs, and verify_blocks() its block count, before taking the
+// lock, so those throws never reach the finally that unlocks; these do.
+{
+       const { blockHashBytes: hash, privateKeyBytes: prv, publicKeyBytes: pub, signatureBytes: sig } = NANO_ORG_VECTOR
+       /** @type {[string, () => unknown][]} */
+       const inside = [
+               ['verify, invalid message', () => verify(sig, 'zz', pub)],
+               ['verify, invalid public key', () => verify(sig, hash, new Uint8Array(31))],
+               ['verify_blocks, invalid public key', () => verify_blocks(new Uint8Array(31), [{ hash, signature: sig }])],
+               ['verify_blocks, invalid second block', () => verify_blocks(pub, [{ hash, signature: sig }, { hash, signature: 'zz' }])],
+               ['verify_blocks, throwing block getter', () => verify_blocks(pub, [{ hash, get signature () { throw new Error('getter') } }])],
+               ['sign, mismatched public key (wasm abort)', () => sign(hash, prv, new Uint8Array(32))],
+       ]
+       /** @type {string[]} */
+       const leaked = []
+       for (const [name, f] of inside) {
+               const raised = attempt(() => { f(); return 'returned' })
+               const after = attempt(() => verify(sig, hash, pub))
+               if (typeof raised !== 'string' || !raised.startsWith('threw') || raised.includes('mutex') || after !== true) {
+                       leaked.push(`${name}: ${raised}; next call ${after}`)
+               }
+       }
+       test = leaked.length === 0
+       check(`errors raised inside the lock release it${test ? '' : ` (${leaked.join('; ')})`}`, test)
+       passes += +test
+       failures += +!test
+
+       // a getter that calls back into the package mid-call must be refused, and the
+       // outer call must still complete
+       let inner = null
+       result = attempt(() => verify_blocks(pub, [{ hash, get signature () { inner = attempt(() => verify(sig, hash, pub)); return sig } }]))
+       test = typeof inner === 'string' && inner.includes('Failed to acquire mutex') && Array.isArray(result) && result[0] === true
+       check(`re-entrant call from a block getter is refused and the outer call completes${test ? '' : ` (inner ${inner}, outer ${result})`}`, test)
+       passes += +test
+       failures += +!test
+}
+
+// Hexadecimal input is decoded arithmetically, not by table lookup, so check
+// the arithmetic against every byte value in either case, and every invalid
+// character at every position, including code units above 0xff whose low byte
+// is a valid digit or letter.
+{
+       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)
+       /** @type {Record<string, string>} */
+       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)
+       test = wrong.length === 0
+       check(`hex input decodes every byte value in lower, upper and mixed case${test ? '' : ` (wrong: ${wrong.join(', ')})`}`, test)
+       passes += +test
+       failures += +!test
+
+       const invalid = ['/', ':', '@', 'G', '`', 'g', ' ', '\0', 'İ', 'Ł', 'š', 'Ȱ', '0', '٠', '\ud83d']
+       /** @type {{ position: number, code: string, result: unknown }[]} */
+       const accepted = []
+       for (let i = 0; i < privateKey.length; i++) {
+               for (const c of invalid) {
+                       const r = attempt(() => derive(privateKey.slice(0, i) + c + privateKey.slice(i + 1)))
+                       if (r !== 'threw Invalid hexadecimal character') {
+                               accepted.push({ position: i, code: `0x${c.charCodeAt(0).toString(16)}`, result: r })
+                       }
+               }
+       }
+       test = accepted.length === 0
+       check(`invalid hex character rejected at every position of a private key${test ? '' : ` (${accepted.length} not rejected, first ${JSON.stringify(accepted.slice(0, 4))})`}`, test)
+       passes += +test
+       failures += +!test
+}
+
 // Check output buffer offset handling
 try {
        outbuf = new Uint8Array(33)
@@ -744,7 +873,14 @@ failures += +!test
 const truth = 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 patchedBlocks = [{ hash: NANO_ORG_VECTOR.blockHashBytes, signature: NANO_ORG_VECTOR.signatureBytes }]
+// 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()
+patchedForgery[40] ^= 1
+const patchedBlocks = [
+       { hash: NANO_ORG_VECTOR.blockHashBytes, signature: NANO_ORG_VECTOR.signatureBytes },
+       { hash: NANO_ORG_VECTOR.blockHashBytes, signature: patchedForgery },
+]
 const TypedArrayPrototype = Object.getPrototypeOf(Uint8Array.prototype)
 /** @type {[string, (() => () => void)][]} */
 const patches = [
@@ -852,6 +988,48 @@ const patches = [
                //@ts-expect-error
                globalThis.Uint32Array = () => { throw new Error('patched') }
                return () => { globalThis.Uint32Array = real }
+       }],
+       // An index accessor on Array.prototype intercepts every [[Set]] on an index
+       // an array does not own yet: assignment, push and fill alike. Results must be
+       // defined as own properties, or a forged block reads as verified.
+       ['Array.prototype index accessors', () => {
+               for (let i = 0; i < constants.MAX_VERIFY_BLOCKS; i++) {
+                       Object.defineProperty(Array.prototype, i, { get () { return true }, set () { }, configurable: true })
+               }
+               return () => {
+                       for (let i = 0; i < constants.MAX_VERIFY_BLOCKS; i++) {
+                               delete Array.prototype[i]
+                       }
+               }
+       }],
+       ['Array.prototype.push', () => {
+               const real = Array.prototype.push
+               Array.prototype.push = function () { return 0 }
+               return () => { Array.prototype.push = real }
+       }],
+       ['Array.prototype.fill', () => {
+               const real = Array.prototype.fill
+               //@ts-expect-error
+               Array.prototype.fill = function () { return this }
+               return () => { Array.prototype.fill = real }
+       }],
+       // descriptor objects and array-likes inherit from Object.prototype unless
+       // they are built without one, as the second definition here would without
+       // its own null prototype
+       ['Object.prototype get and set', () => {
+               Object.defineProperty(Object.prototype, 'get', { __proto__: null, value () { return true }, configurable: true, writable: true })
+               Object.defineProperty(Object.prototype, 'set', { __proto__: null, value () { }, configurable: true, writable: true })
+               return () => {
+                       //@ts-expect-error
+                       delete Object.prototype.get
+                       //@ts-expect-error
+                       delete Object.prototype.set
+               }
+       }],
+       ['Object.prototype[Symbol.iterator]', () => {
+               Object.defineProperty(Object.prototype, Symbol.iterator, { * value () { yield true; yield true }, configurable: true, writable: true })
+               //@ts-expect-error
+               return () => { delete Object.prototype[Symbol.iterator] }
        }]
 ]
 /** @type {[string, () => boolean][]} */
@@ -859,7 +1037,10 @@ const patchedPrimitives = [
        ['derive', () => derive(NANO_ORG_VECTOR.privateKeyBytes) === truth],
        ['sign', () => sign(patchedMessage, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes) === truthSignature],
        ['verify', () => verify(truthSignature, patchedMessage, NANO_ORG_VECTOR.publicKeyBytes) === true],
-       ['verify_blocks', () => verify_blocks(NANO_ORG_VECTOR.publicKeyBytes, patchedBlocks)[0] === 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
+       }]
 ]
 for (const [name, apply] of patches) {
        for (const [primitive, run] of patchedPrimitives) {
index cfe32f0af3aba0e6d74b95de3b05dd5e3ab464e1..ffc2459ae7381bc1830d456d5952c10fce8434f3 100644 (file)
@@ -6180,11 +6180,29 @@ var PYTHON_ED25519_BLAKE2B_VECTORS = [
     signature: "d03965ac316a20f5a47ab2d6185eb3f0aeea9c2eb8abe922e96d317b3bd0ef02e8d47fd92384e28615eb3314adbc71c4675996099e484ceb162847c40c32440e08b8b2b733424243760fe426a4b54908632110a66c2f6591eabd3345e3e4eb98fa6e264bf09efe12ee50f8f54e9f77b1e355f6c50544e23fb1433ddf73be84d879de7c0046dc4996d9e773f4bc9efe5738829adb26c81b37c93a1b270b20329d658675fc6ea534e0810a4432826bf58c941efb65d57a338bbd2e26640f89ffbc1a858efcb8550ee3a5e1998bd177e93a7363c344fe6b199ee5d02e82d522c4feba15452f80288a821a579116ec6dad2b3b310da903401aa62100ab5d1a36553e06203b33890cc9b832f79ef80560ccb9a39ce767967ed628c6ad573cb116dbefefd75499da96bd68a8a97b928a8bbc103b6621fcde2beca1231d206be6cd9ec7aff6f6c94fcd7204ed3455c68c83f4a41da4af2b74ef5c53f1d8ac70bdcb7ed185ce81bd84359d44254d95629e9855a94a7c1958d1f8ada5d0532ed8a5aa3fb2d17ba70eb6248e594e1a2297acbbb39d502f1a8c6eb6f1ce22b3de1a1f40cc24554119a831a9aad6079cad88425de6bde1a9187ebb6092cf67bf2b13fd65f27088d78b7e883c8759d2c4f5c65adb7553878ad575f9fad878e80a0c9ba63bcbcc2732e69485bbc9c90bfbd62481d9089beccf80cfe2df16a2cf65bd92dd597b0707e0917af48bbb75fed413d238f5555a7a569d80c3414a8d0859dc65a46128bab27af87a71314f318c782b23ebfe808b82b0ce26401d2e22f04d83d1255dc51addd3b75a2b1ae0784504df543af8969be3ea7082ff7fc9888c144da2af58429ec96031dbcad3dad9af0dcbaaaf268cb8fcffead94f3c7ca495e056a9b47acdb751fb73e666c6c655ade8297297d07ad1ba5e43f1bca32301651339e22904cc8c42f58c30c04aafdb038dda0847dd988dcda6f3bfd15c4b4c4525004aa06eeff8ca61783aacec57fb3d1f92b0fe2fd1a85f6724517b65e614ad6808d6f6ee34dff7310fdc82aebfd904b01e1dc54b2927094b2db68d6f903b68401adebf5a7e08d78ff4ef5d63653a65040cf9bfd4aca7984a74d37145986780fc0b16ac451649de6188a7dbdf191f64b5fc5e2ab47b57f7f7276cd419c17a3ca8e1b939ae49e488acba6b965610b5480109c8b17b80e1b7b750dfc7598d5d5011fd2dcc5600a32ef5b52a1ecc820e308aa342721aac0943bf6686b64b2579376504ccc493d97e6aed3fb0f9cd71a43dd497f01f17c0e2cb3797aa2a2f256656168e6c496afc5fb93246f6b1116398a346f1a641f3b041e989f7914f90cc2c7fff357876e506b50d334ba77c225bc307ba537152f3f1610e4eafe595f6d9d90d11faa933a15ef1369546868a7f3a45a96768d40fd9d03412c091c6315cf4fde7cb68606937380db2eaaa707b4c4185c32eddcdd306705e4dc1ffc872eeee475a64dfac86aba41c0618983f8741c5ef68d3a101e8a3b8cac60c905c15fc910840b94c00a0b9d0"
   }
 ];
+
+// test/vectors/torsion.ts
+var TORSION_VECTORS = {
+  privateKey: "781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3",
+  publicKey: "3068BB1CA04525BB0E416C485FE6A67FD52540227D267CC8B6E8DA958A7FA039",
+  blockHash: "BB569136FA05F8CBF65CEF2EDE368475B289C4477342976556BA4C0DDF216E45",
+  signatures: [
+    { order: 1, torsion: "0100000000000000000000000000000000000000000000000000000000000000", signature: "74BCC59DBA39A1E34A5F75F96D6DE9154E3477AAD7DE30EA563DFCFE501A804228008F98DDF4A15FD35705102785C50EF76732C3A74B0FEC5B0DD67B574A5900" },
+    { order: 2, torsion: "ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f", signature: "79433A6245C65E1CB5A08A06929216EAB1CB88552821CF15A9C20301AFE57FBD468572C195B9A36829561FD6F552E5CE67EC99608EB9D67A5EE3208676A6990F" },
+    { order: 4, torsion: "0000000000000000000000000000000000000000000000000000000000000000", signature: "41152EF8578868B26BAD13438E44172913AC06AF974EBD4B340063B15752D2AD516CE58A34BA8A5D7008A6AC76184A15462C0CA2EC6724DBB41C1112CA02FD06" },
+    { order: 4, torsion: "0000000000000000000000000000000000000000000000000000000000000080", signature: "ACEAD107A877974D9452ECBC71BBE8D6EC53F95068B142B4CBFF9C4EA8AD2D52B84BA3168F26F6D145E5B210DE7CAE8C299F3EC4B3FFDE847A86A28540C1F509" },
+    { order: 8, torsion: "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05", signature: "75D07637A941075B98A9105E20E3CBDBF61A34A6FF7ACB74E9D7336AB4D81654D045E8B436BA585F52AA79FEA1FFA4EABDF1E3D8E8AAF9ADA8044B1501897D03" },
+    { order: 8, torsion: "26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85", signature: "FA0E2FD1D85E5EACF27DFD855578146DDB2A40D9FBDCBAC98B7E7DDD7AEC408498536DCEA374C79D7B63661BDDB111C4F37C1B8277D1FC36324E9E4289023C0C" },
+    { order: 8, torsion: "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a", signature: "F3F0D02E27A1A1530D82027AAA87EB9224D5BF2604234536748182228513BF7BABD08E47A61B4B64922CDC0D3CDCDB09584D5086C9CBDAD1785D4A22C831B308" },
+    { order: 8, torsion: "c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa", signature: "782F89C856BEF8A46756EFA1DF1C342409E5CB590085348B1628CC954B27E9AB6E77645E0F349DEDC9917D7B2B8E890B3B5D60C6476090C778B17E84AFC81000" }
+  ]
+};
 export {
   IDENTITY,
   NANO_ORG_VECTOR,
   RSNANO_PROBLEM_VECTOR as PROBLEM_VECTOR,
-  PYTHON_ED25519_BLAKE2B_VECTORS
+  PYTHON_ED25519_BLAKE2B_VECTORS,
+  TORSION_VECTORS
 };
 //! SPDX-FileCopyrightText: 2026 Chris Duncan <chris@codecow.com>
 //! SPDX-License-Identifier: GPL-3.0-or-later
index cbdefcbd977ecd494261640e1f64038bc24971f4..739d9d3d3ebd24af84bfa05d428ae3e008d744a2 100644 (file)
@@ -4,3 +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'
diff --git a/test/vectors/torsion.ts b/test/vectors/torsion.ts
new file mode 100644 (file)
index 0000000..479bb25
--- /dev/null
@@ -0,0 +1,32 @@
+//! SPDX-FileCopyrightText: 2026 Chris Duncan <chris@codecow.com>
+//! SPDX-License-Identifier: GPL-3.0-or-later
+
+/**
+ * The nano.org key signing the nano.org block hash with its nonce point offset
+ * by each of the eight points `T` of order dividing 8:
+ *
+ * `R' = rB + T`, `k' = BLAKE2b(R' || A || M) mod L`, `S' = r + k'a mod L`
+ *
+ * where `r` is the deterministic nonce of the unmodified signature. Only the key
+ * holder can make these, since `S'` needs `a`. `R' - ([S']B - [k']A) = T`, so a
+ * cofactored verifier accepts all eight and a cofactorless one accepts only the
+ * order-1 row, which is the nano.org signature itself.
+ *
+ * `torsion` is the encoding of `T`. Generated with an independent BigInt
+ * implementation; the order-1 row reproducing the nano.org signature checks it.
+ */
+export const TORSION_VECTORS = {
+       privateKey: '781186FB9EF17DB6E3D1056550D9FAE5D5BBADA6A6BC370E4CBB938B1DC71DA3',
+       publicKey: '3068BB1CA04525BB0E416C485FE6A67FD52540227D267CC8B6E8DA958A7FA039',
+       blockHash: 'BB569136FA05F8CBF65CEF2EDE368475B289C4477342976556BA4C0DDF216E45',
+       signatures: [
+               { order: 1, torsion: '0100000000000000000000000000000000000000000000000000000000000000', signature: '74BCC59DBA39A1E34A5F75F96D6DE9154E3477AAD7DE30EA563DFCFE501A804228008F98DDF4A15FD35705102785C50EF76732C3A74B0FEC5B0DD67B574A5900' },
+               { order: 2, torsion: 'ecffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff7f', signature: '79433A6245C65E1CB5A08A06929216EAB1CB88552821CF15A9C20301AFE57FBD468572C195B9A36829561FD6F552E5CE67EC99608EB9D67A5EE3208676A6990F' },
+               { order: 4, torsion: '0000000000000000000000000000000000000000000000000000000000000000', signature: '41152EF8578868B26BAD13438E44172913AC06AF974EBD4B340063B15752D2AD516CE58A34BA8A5D7008A6AC76184A15462C0CA2EC6724DBB41C1112CA02FD06' },
+               { order: 4, torsion: '0000000000000000000000000000000000000000000000000000000000000080', signature: 'ACEAD107A877974D9452ECBC71BBE8D6EC53F95068B142B4CBFF9C4EA8AD2D52B84BA3168F26F6D145E5B210DE7CAE8C299F3EC4B3FFDE847A86A28540C1F509' },
+               { order: 8, torsion: '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc05', signature: '75D07637A941075B98A9105E20E3CBDBF61A34A6FF7ACB74E9D7336AB4D81654D045E8B436BA585F52AA79FEA1FFA4EABDF1E3D8E8AAF9ADA8044B1501897D03' },
+               { order: 8, torsion: '26e8958fc2b227b045c3f489f2ef98f0d5dfac05d3c63339b13802886d53fc85', signature: 'FA0E2FD1D85E5EACF27DFD855578146DDB2A40D9FBDCBAC98B7E7DDD7AEC408498536DCEA374C79D7B63661BDDB111C4F37C1B8277D1FC36324E9E4289023C0C' },
+               { order: 8, torsion: 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac037a', signature: 'F3F0D02E27A1A1530D82027AAA87EB9224D5BF2604234536748182228513BF7BABD08E47A61B4B64922CDC0D3CDCDB09584D5086C9CBDAD1785D4A22C831B308' },
+               { order: 8, torsion: 'c7176a703d4dd84fba3c0b760d10670f2a2053fa2c39ccc64ec7fd7792ac03fa', signature: '782F89C856BEF8A46756EFA1DF1C342409E5CB590085348B1628CC954B27E9AB6E77645E0F349DEDC9917D7B2B8E890B3B5D60C6476090C778B17E84AFC81000' },
+       ],
+}