From: Chris Duncan Date: Thu, 3 Sep 2026 05:17:45 +0000 (-0700) Subject: Expand unit tests for equalbytes. X-Git-Url: https://git.codecow.com/?a=commitdiff_plain;h=94457aaa9f7098ac84f5af1abd8b3ec40cce3360;p=nano25519.git Expand unit tests for equalbytes. --- diff --git a/src/assembly/tests.ts b/src/assembly/tests.ts index fef7ee7..2e56d66 100644 --- a/src/assembly/tests.ts +++ b/src/assembly/tests.ts @@ -6,16 +6,39 @@ import { equalbytes } from './utils' /** * Tests run on initialization to ensure build is correct. */ -const testbytesA = new StaticArray(32).fill(0) -const testbytesB = new StaticArray(32).fill(0) -/** equalbytes */ +/** + * equalbytes - checks masked bytes against the following test keys: + * - random bytes + * - all zeros + * - all ones + */ +const zeros = new StaticArray(32).fill(0) +const ones = new StaticArray(32).fill(255) +const random = new StaticArray(32) for (let i = 0; i < 32; i++) { - for (let j: u8 = 0; j < 8; j++) { - testbytesA[i] = 1 << j - if (equalbytes(testbytesA, testbytesB, 32)) { - throw new Error('equalbytes failed build test') + random[i] = u8(Math.random() * 255) +} + +const vectors = ['zeros', 'ones', 'random',] +const expecteds = [zeros, ones, random,] + +const actual = new StaticArray(32) + +for (let i = 0; i < vectors.length; i++) { + const vector = vectors[i] + const expected = expecteds[i] + memory.copy(changetype(actual), changetype(expected), 32) + for (let i = 0; i < 32; i++) { + if (!equalbytes(actual, expected, 32)) { + throw new Error(`equalbytes build error: ${vector} failed instead of passing (expected [${expected}], actual [${actual}])`) + } + for (let j: u8 = 1; j < 255; j++) { + actual[i] ^= j + if (equalbytes(actual, expected, 32)) { + throw new Error(`equalbytes build error: ${vector} passed instead of failing (expected [${expected}], actual [${actual}])`) + } + actual[i] = expected[i] } - testbytesA[i] = 0 } } diff --git a/src/lib/wasm.ts b/src/lib/wasm.ts index 50f4bf1..6f95e93 100644 --- a/src/lib/wasm.ts +++ b/src/lib/wasm.ts @@ -51,6 +51,7 @@ const module = new WebAssembly.Module(wasm) export const { exports } = new WebAssembly.Instance(module, { env: { memory, + seed: (): number => new Float64Array((crypto.getRandomValues(new BigUint64Array(1)).buffer))[0], abort: (msg: any, file: any, row: any, col: any): never => { const getString = (pointer: number): string | null => { const end = pointer + new Uint32Array(memory.buffer)[pointer - 4 >>> 2] >>> 1