```javascript
derive(prv[, out]) // 32-byte private key -> 32-byte public key
-sign(msg, prv, pub[, out]) // 32-byte block hash -> 64-byte signature
+sign(msg, prv, pub[, out]) // message up to 64 KiB -> 64-byte signature
verify(sig, msg, pub) // -> boolean
verify_blocks(pub, blocks) // { hash, signature }[], up to 64 -> boolean[]
```
`prototype.name`, so the run catches writes to built-ins themselves, not every
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.
+6220 / 0, with the same patches skipped as under frozen intrinsics. That was the
+suite as of `e9ddef1`; it has not been re-run under SES since.
**Results are defined, never assigned.** `verify_blocks` defines each element
of its `boolean[]` with the captured `Object.defineProperty` and a descriptor
`p3` it reads back, and its control recomputes `T` as `X·Y` to prove a point
comparison alone misses it.
+**Small order means *valid* at one call site and *reject* at the others, so
+each needs its own predicate.** On a well-formed point, `X = 0`, `Y = 0` or
+`X = ±√−1·Y` is exactly the eight torsion points (`ge_has_small_order`). A
+malformed point — `Z = 0`, or `X = Y = 0`, as in the all-zero state a fresh
+`ge_p3` starts in — matches that test too, and the safe answer for it depends on
+the caller. `crypto_verify_sodium` accepts when `R - [S]B + [k]A` is small
+order, so it calls `ge_accept_small_order`, which returns 0 only for a
+well-formed small-order point and −1 otherwise. `verify_pubkey` and `verify_signature` reject a
+small-order key or `R`, so they call `ge_reject_small_order`, which returns −1
+for small order *or* malformed. One predicate used at both kinds of site can
+fail closed for only one of them: before `bfbddc9` the shared function read a
+degenerate final point as valid, and a first attempt to fix it made the reject
+sites accept degenerate input, and a second wrote the accept predicate's −1
+straight to `OUTPUT_VERIFY`, where `u8()` turned it into `255` and every valid
+signature failed. Nothing reaches a
+malformed point today, since the addition formulas are complete and every input
+is decoded, but both defaults now fail closed. `test:arithmetic` checks each
+predicate on decoded, projective and degenerate points, and its control drops
+the malformed term from each. Both predicates are C-style, `0` to pass and `−1`
+to refuse, so `crypto_verify_sodium` must map its result to `1` or `0` itself
+before it reaches `OUTPUT_VERIFY`; never return the predicate's value directly.
+
**Do not add JS-side suspension points.** The safety of hashing straight out of
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
`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 **6340, 6340, 6220, 17, 12 and 36
-passing, 0 failing**; the frozen run skips the 120 checks under prototype and
+and `test:arithmetic`. Current state is **6362, 6362, 6222, 17, 12 and 47
+passing, 0 failing**; the frozen run skips the 140 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`
in the batch — the bug this feature has actually shipped is reporting invalid
signatures as valid, which an all-valid batch cannot catch.
+**Vary the hashes in a batch, not only the signatures.** Every batch in the
+suite once repeated one hash in every record, so a layout bug that verified
+each block against block 0's hash — in the wasm loop's pointer, or a host that
+read `blocks[0].hash` — passed all six suites, and would have let a valid
+`(hash₀, sig₀)` vouch for a forged `(hash₁, sig₀)` in the same batch. Both were
+built, and both passed the suite as it then stood. `test/node.mjs` now signs a distinct hash for each of
+`MAX_VERIFY_BLOCKS` blocks and gives some records the next block's genuine
+signature, which only a record read against its own hash rejects.
+
**Most rejections are decided before the final equation** — a small-order key,
a non-canonical scalar, a malformed block, or the identity key that pins `R`.
So `test/node.mjs` also forges signatures that pass every precondition, under a
`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.
+since no valid signature can carry a non-canonical encoding, so
+`test:arithmetic` calls `verify_pubkey` and `verify_signature` directly instead:
+each must reject all 38 non-canonical encodings, including the 20 that decode to
+points of large order and pass every other check. They are exported from
+`crypto_verify.ts` for that, and `index.ts` does not re-export them, so they
+are not wasm exports and exporting them leaves the production binary unchanged.
### Hostile arguments, patched prototypes, re-entrancy and hex input
`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
+The patch list at the end of `test/node.mjs` replaces 23 prototype methods and
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`,
+`set`, `fill` and `Symbol.iterator` on `%TypedArray%.prototype` itself as well as
+shadowed on `Uint8Array.prototype`, the `ArrayBuffer.prototype.byteLength` getter
+`isBytes()` relies on, index accessors on `Array.prototype`, and `get`, `set`
+and `Symbol.iterator` on `Object.prototype`. Every capture in `bytes.ts` and
+`verify.ts` has a patch; keep it that way. 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 and a frozen array, because a patch that
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
+test, that wraps internals over buffers of its own, and compares about 57,600
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
+and `[0]A + [0]B`; the checks `verify()` makes on the key and `R` at their call
+sites; and degenerate points, which both small-order predicates must refuse. 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`.
+reproduces. Its controls drop `ge_p3_0(r)`, recompute `T` as `X·Y`, and, in one
+probe, drop both canonicity checks and the malformed-point term from each of
+the two small-order predicates; each of the six must be seen.
## Style
* limbs at the bounds ref10 documents, aliased operands, small-order and
* non-canonical points, and zero scalars.
*
+ * **The checks `verify()` makes before its equation are tested at their call
+ * sites.** `verify_pubkey` and `verify_signature` reject non-canonical encodings
+ * of the key and of `R`, and no valid signature can carry one, so no public-API
+ * test can tell a build without those checks apart. Called directly, they must
+ * reject every non-canonical encoding, including the twenty that decode to
+ * points of large order and so pass every other check. These two use the shared
+ * `t_fe_*` themselves, as they do in `verify()`.
+ *
+ * **A degenerate point fails closed at both kinds of call site.** `verify()`
+ * accepts when `R - [S]B + [k]A` is small order, through `ge_accept_small_order`,
+ * and rejects a small-order key or `R`, through `ge_reject_small_order`. A point
+ * with `Z = 0`, or the all-zero state a fresh `ge_p3` starts in, must be refused
+ * by the first and rejected by the second; one predicate cannot do both.
+ *
* **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
* 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.
+ * pass the point comparison while failing the representation check. A third
+ * probe drops both canonicity checks and the malformed-point term from each of
+ * the two small-order predicates, and each of the four must be seen.
*
* Inputs come from a seeded generator, so any failure reproduces.
*/
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_is_small_order_point, ge_is_canonical, ge_scalarmult_base_tobytes } from './ed25519/ge'
+import { ge_double_scalarmult_vartime_to_p3, ge_frombytes, ge_frombytes_negate_vartime, ge_accept_small_order, ge_reject_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'
+import { verify_pubkey, verify_signature } from './crypto_verify'
const FA = fe(), FB = fe(), FH = fe()
const T0 = fe(), T1 = fe(), T2 = fe(), T3 = fe(), T4 = fe(), T5 = fe(), T6 = fe()
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_is_small_order_point_ (): i32 { return ge_is_small_order_point(PA, T0, U8T) }
+export function ge_accept_small_order_ (): i32 { return ge_accept_small_order(PA, T0, U8T) }
+export function ge_reject_small_order_ (): i32 { return ge_reject_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) }
+export function verify_pubkey_ (): i32 { return verify_pubkey(U8A) ? 1 : 0 }
+export function verify_signature_ (): i32 { return verify_signature(U8W) ? 1 : 0 }
`
-/** 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)' }
+/** Seeded controls: each `from` must occur once inside its `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)' }]
+const NO_PRECONDITIONS = [
+ { file: 'src/assembly/crypto_verify.ts', fn: 'verify_pubkey', from: 'if (ge_is_canonical(pub) != 0) {', to: 'if (false) {' },
+ { file: 'src/assembly/crypto_verify.ts', fn: 'verify_signature', from: 'if (ge_is_canonical(sig) != 0) {', to: 'if (false) {' },
+ { file: 'src/assembly/ed25519/ge.ts', fn: 'ge_accept_small_order', from: 'return 0 - (malformed | (small_order ^ 1))', to: 'return 0 - (small_order ^ 1)' },
+ { file: 'src/assembly/ed25519/ge.ts', fn: 'ge_reject_small_order', from: 'return 0 - (malformed | small_order)', to: 'return 0 - small_order' },
+]
-/** Copies the sources, exports memory, adds the harness, optionally applies one edit, and compiles. */
-async function probe (name, edit) {
+/** Copies the sources, exports memory, adds the harness, applies any edits, and compiles. */
+async function probe (name, edits = []) {
const dir = new URL(`${name}/`, work)
await mkdir(dir, { recursive: true })
await cp(new URL('src/', root), new URL('src/', dir), { recursive: true })
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) {
+ for (const edit of edits) {
const path = new URL(edit.file, dir)
const source = await readFile(path, 'utf8')
const start = source.indexOf(`export function ${edit.fn} (`)
note('ge_double_scalarmult_vartime_to_p3: [0]A + [0]B is the identity', equal(zero, IDENTITY) && isExtended(zero), 0)
}
+/**
+ * Runs the checks `verify()` makes before its equation at their call sites:
+ * every non-canonical encoding with both sign bits, its canonical counterpart
+ * `y < 19`, every torsion point, valid points and random bytes, as the key and
+ * as `R`. Draws from its own generator, so the inputs above do not move.
+ */
+function preconditions (h, note) {
+ const { x, bytes } = h
+ const draw = generator('nano25519 preconditions')
+ const canonical = (e) => (toLE(e) & ((1n << 255n) - 1n)) < P
+ const accepted = (e) => { const p = canonical(e) ? decode(e) : null; return p != null && order(p) === 0 }
+ const encodings = []
+ for (let k = 0n; k < 19n; k++) {
+ for (const sign of [0, 0x80]) {
+ const nonCanonical = fromLE(P + k)
+ nonCanonical[31] |= sign
+ const counterpart = fromLE(k)
+ counterpart[31] |= sign
+ encodings.push(nonCanonical, counterpart)
+ }
+ }
+ for (const T of TORSION) {
+ const e = encode(T)
+ encodings.push(e, Uint8Array.from(e, (v, i) => i === 31 ? v ^ 0x80 : v))
+ }
+ for (let k = 0; k < 100; k++) encodings.push(encode(mul(B, toLE(draw(32)) % L)), draw(32))
+
+ // the checks below are only as good as the encodings, so pin what they cover:
+ // non-canonical encodings that decode to points of large order pass every
+ // check but canonicity, and there are twenty of them
+ const large = encodings.filter(e => !canonical(e) && decode(e) != null && order(decode(e)) === 0)
+ note('preconditions cover the 20 non-canonical encodings of large-order points', large.length === 20, large.length)
+
+ for (const e of encodings) {
+ bytes(U8A).set(e)
+ note('verify_pubkey: canonical, decodable, not small order', x.verify_pubkey_() === (accepted(e) ? 1 : 0), e)
+ const S = toLE(draw(32)) % L
+ bytes(U8W, 64).set(e)
+ bytes(U8W, 64).set(fromLE(S), 32)
+ note('verify_signature: S < L, and R canonical, decodable, not small order', x.verify_signature_() === (accepted(e) ? 1 : 0), e)
+ }
+ // S at and past L under a valid R, which only S < L can reject
+ const R = encode(mul(B, toLE(draw(32)) % L))
+ for (const S of [L - 1n, L, L + 1n, (1n << 253n) - 1n, (1n << 256n) - 1n]) {
+ bytes(U8W, 64).set(R)
+ bytes(U8W, 64).set(fromLE(S), 32)
+ note('verify_signature: S < L, and R canonical, decodable, not small order', x.verify_signature_() === (S < L ? 1 : 0), S)
+ }
+}
+
+/**
+ * A degenerate representation must be refused where small order accepts and
+ * rejected where it rejects: `Z = 0` under the `X` and `Y` of every torsion point
+ * and of random values, `X = Y = 0` under any `Z`, and the all-zero state a fresh
+ * `ge_p3` starts in.
+ */
+function degenerate (h, note) {
+ const { x, setProjective } = h
+ const draw = generator('nano25519 degenerate')
+ const element = () => toLE(draw(32)) % P
+ const cases = [[0n, 0n, 0n, 0n]]
+ for (const T of TORSION) cases.push([T[0], T[1], 0n, T[3]])
+ for (let k = 0; k < 16; k++) cases.push([element(), element(), 0n, element()], [0n, 0n, element() || 1n, element()])
+ for (const p of cases) {
+ setProjective(PA, p)
+ note('ge_accept_small_order refuses degenerate points', x.ge_accept_small_order_() === -1, p)
+ note('ge_reject_small_order rejects degenerate points', x.ge_reject_small_order_() === -1, p)
+ }
+}
+
function collector () {
const results = {}
const note = (name, ok, input) => {
const started = performance.now()
await rm(work, { recursive: true, force: true })
try {
- const [clean, noIdentity, staleT] = await Promise.all([
+ const [clean, noIdentity, staleT, noPreconditions] = await Promise.all([
probe('clean'),
probe('no-identity', NO_IDENTITY).catch((err) => err),
probe('stale-t', STALE_T).catch((err) => err),
+ probe('no-preconditions', NO_PRECONDITIONS).catch((err) => err),
])
// positive controls
check(`control ${name}`, seen, Object.entries(results).map(([k, r]) => `${k}: ${r.bad}/${r.n} bad`).join('; '))
}
+ // one probe drops four independent checks; each must be seen on its own
+ {
+ const results = {}
+ if (noPreconditions instanceof WebAssembly.Module) {
+ const control = collector()
+ const h = harness(noPreconditions)
+ preconditions(h, control.note)
+ degenerate(h, control.note)
+ Object.assign(results, control.results)
+ }
+ const detail = noPreconditions instanceof WebAssembly.Module ? Object.entries(results).map(([k, r]) => `${k}: ${r.bad}/${r.n} bad`).join('; ') : String(noPreconditions?.message ?? noPreconditions)
+ for (const [name, key] of [
+ ['sees a verify_pubkey without its canonicity check', 'verify_pubkey: canonical, decodable, not small order'],
+ ['sees a verify_signature without its canonicity check on R', 'verify_signature: S < L, and R canonical, decodable, not small order'],
+ ['sees ge_accept_small_order accept a degenerate point', 'ge_accept_small_order refuses degenerate points'],
+ ['sees ge_reject_small_order pass a degenerate point', 'ge_reject_small_order rejects degenerate points'],
+ ]) {
+ check(`control ${name}`, results[key] != null && results[key].bad > 0, detail)
+ }
+ }
+
const h = harness(clean)
const { x, bytes, set, get, padded, setPoint, setProjective, getPoint } = h
const { results, note } = collector()
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_is_small_order_point on decoded points', x.ge_is_small_order_point_() === (isSmall(want) ? 1 : 0), e)
+ if (rc === 0) {
+ note('ge_accept_small_order on decoded points', x.ge_accept_small_order_() === (isSmall(want) ? 0 : -1), e)
+ note('ge_reject_small_order on decoded points', x.ge_reject_small_order_() === (isSmall(want) ? -1 : 0), e)
+ }
bytes(U8A).set(e)
const rn = x.ge_frombytes_negate_vartime_()
const gn = getPoint(PA)
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_is_small_order_point on projective points', x.ge_is_small_order_point_() === (isSmall(p) ? 1 : 0), k)
+ note('ge_accept_small_order on projective points', x.ge_accept_small_order_() === (isSmall(p) ? 0 : -1), k)
+ setProjective(PA, p.map(c => mod(c * lambda)))
+ note('ge_reject_small_order on projective points', x.ge_reject_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)
note('ge_scalarmult_base_tobytes', toLE(bytes(U8B)) === toLE(encode(mul(B, a))), a)
}
doubleScalarmult(h, note, 400)
+ preconditions(h, note)
+ degenerate(h, note)
let comparisons = 0
for (const [name, r] of Object.entries(results)) {
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`)
+console.log(`4 builds in ${((performance.now() - started) / 1000).toFixed(1)} s`)
process.exitCode = failures > 0 ? 1 : 0
// Check identity signature verifies
result = attempt(() => verify_blocks(IDENTITY.publicKeyBytes, [{ signature: IDENTITY.signatureBytes, hash: new Uint8Array(32) }]))
-test = result[0] === true
+test = Array.isArray(result) && result[0] === true
check(`verify identity signature bytes ${IDENTITY.signature}`, test)
passes += +test
failures += +!test
+// the same signature is not a sound Ed25519 signature: verify() rejects the
+// identity, a small-order key, as it does PROBLEM_VECTOR's
+result = attempt(() => verify(IDENTITY.signatureBytes, new Uint8Array(32), IDENTITY.publicKeyBytes))
+test = result === false
+check(`verify strict check fails for identity signature bytes ${IDENTITY.signature}`, test)
+passes += +test
+failures += +!test
+
// identity A and S=0 pin check_r so only R moves; any other A hides equalbytes bugs
const forgery = IDENTITY.signatureBytes.slice()
const accepted = []
check(`verify_blocks rejects exactly the ${corrupted.size} corrupted blocks of a full batch`, test)
passes += +test
failures += +!test
+
+ // Every other batch repeats one hash in every record, so a record-layout bug
+ // that verifies a block against another record's hash, block 0's say, cannot
+ // show: every record holds the same bytes. Sign a distinct hash per block, then
+ // give some records the next block's signature instead. That signature is
+ // genuine and its hash is in the same batch, so only reading each record's own
+ // hash rejects it; a bug reading the wrong record would accept it, or reject
+ // the honest records around it.
+ /** @type {{hash: Uint8Array<ArrayBuffer>, signature: unknown}[]} */
+ const distinct = []
+ /** @type {unknown[]} */
+ const signatures = []
+ for (let b = 0; b < constants.MAX_VERIFY_BLOCKS; b++) {
+ // 101 is odd, so byte 0 differs for every block
+ const blockHash = Uint8Array.from({ length: constants.BLOCKHASH_BYTELENGTH }, (_, i) => (i * 37 + 11 + b * 101) & 255)
+ distinct.push({ hash: blockHash, signature: null })
+ signatures.push(attempt(() => sign(blockHash, prv, pub)))
+ }
+ const swapped = new Set()
+ for (let b = 0; b < distinct.length; b++) {
+ if (b % 7 === 3) swapped.add(b)
+ distinct[b].signature = signatures[swapped.has(b) ? (b + 1) % signatures.length : b]
+ }
+ result = attempt(() => verify_blocks(pub, distinct))
+ test = signatures.every(s => typeof s === 'string' && !s.startsWith('threw'))
+ && Array.isArray(result) && result.length === distinct.length && result.every((v, b) => v === !swapped.has(b))
+ check(`verify_blocks checks each record against its own hash, rejecting exactly the ${swapped.size} records given another block's signature in a full batch of distinct hashes${test ? '' : ` (${JSON.stringify(result)})`}`, test)
+ passes += +test
+ failures += +!test
}
// A nonce offset by a small-order point, R' = rB + T, with S recomputed by the
// Check string inputs
result = attempt(() => derive(NANO_ORG_VECTOR.privateKey))
-test = result.toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase()
+test = typeof result === 'string' && result.toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase()
check(`derive from private key string ${NANO_ORG_VECTOR.privateKey}`, test)
passes += +test
failures += +!test
result = attempt(() => sign(NANO_ORG_VECTOR.blockHash, NANO_ORG_VECTOR.privateKey, NANO_ORG_VECTOR.publicKey))
-test = result.toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase()
+test = typeof result === 'string' && result.toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase()
check(`sign message string ${NANO_ORG_VECTOR.blockHash}`, test)
passes += +test
failures += +!test
// Check byte inputs
result = attempt(() => derive(NANO_ORG_VECTOR.privateKeyBytes))
-test = result.toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase()
+test = typeof result === 'string' && result.toLowerCase() === NANO_ORG_VECTOR.publicKey.toLowerCase()
check(`derive from private key bytes ${NANO_ORG_VECTOR.privateKey}`, test)
passes += +test
failures += +!test
failures += +!test
result = attempt(() => sign(NANO_ORG_VECTOR.blockHashBytes, NANO_ORG_VECTOR.privateKeyBytes, NANO_ORG_VECTOR.publicKeyBytes))
-test = result.toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase()
+test = typeof result === 'string' && result.toLowerCase() === NANO_ORG_VECTOR.signature.toLowerCase()
check(`sign message bytes ${NANO_ORG_VECTOR.blockHash}`, test)
passes += +test
failures += +!test
console.log(err)
result = false
}
-test = result[0] === true && Object.isFrozen(result)
+test = Array.isArray(result) && result[0] === true && Object.isFrozen(result)
check(`verify_blocks single hash bytes ${NANO_ORG_VECTOR.blockHash} with signature bytes ${NANO_ORG_VECTOR.signature}`, test)
passes += +test
failures += +!test
Uint8Array.prototype.fill = () => { throw new Error('patched') }
return () => { Uint8Array.prototype.fill = real }
}],
+ // the two above only shadow these, so replace the methods the host captured
+ // as well, and the iterator a spread or for...of over bytes would look up
+ ['%TypedArray%.prototype.set', () => {
+ const real = TypedArrayPrototype.set
+ TypedArrayPrototype.set = () => { throw new Error('patched') }
+ return () => { TypedArrayPrototype.set = real }
+ }],
+ ['%TypedArray%.prototype.fill', () => {
+ const real = TypedArrayPrototype.fill
+ TypedArrayPrototype.fill = () => { throw new Error('patched') }
+ return () => { TypedArrayPrototype.fill = real }
+ }],
+ ['%TypedArray%.prototype[Symbol.iterator]', () => {
+ const real = TypedArrayPrototype[Symbol.iterator]
+ TypedArrayPrototype[Symbol.iterator] = () => { throw new Error('patched') }
+ return () => { TypedArrayPrototype[Symbol.iterator] = real }
+ }],
// the only prototype method the hex decoder calls, on a private key
['String.prototype.charCodeAt', () => {
const real = String.prototype.charCodeAt
})
return () => { Object.defineProperty(TypedArrayPrototype, 'buffer', real) }
}],
+ // isBytes() tells an ArrayBuffer from a SharedArrayBuffer with this getter
+ ['ArrayBuffer.prototype.byteLength', () => {
+ const real = Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength')
+ if (!real) throw new TypeError('Failed to backup ArrayBuffer.prototype.byteLength')
+ Object.defineProperty(ArrayBuffer.prototype, 'byteLength', { get () { throw new Error('patched') }, configurable: true })
+ return () => { Object.defineProperty(ArrayBuffer.prototype, 'byteLength', real) }
+ }],
['DataView.prototype.getUint32', () => {
const real = DataView.prototype.getUint32
DataView.prototype.getUint32 = () => 0x41414141