]> git.codecow.com Git - nano25519.git/commitdiff
Expand unit tests for equalbytes.
authorChris Duncan <chris@codecow.com>
Thu, 3 Sep 2026 05:17:45 +0000 (22:17 -0700)
committerChris Duncan <chris@codecow.com>
Thu, 3 Sep 2026 05:17:45 +0000 (22:17 -0700)
src/assembly/tests.ts
src/lib/wasm.ts

index fef7ee76c798aede173fd751e3684dc93dfadbdc..2e56d6670106a3d0ac633693bb51737e86891b3c 100644 (file)
@@ -6,16 +6,39 @@ import { equalbytes } from './utils'
 /**
  * Tests run on initialization to ensure build is correct.
  */
-const testbytesA = new StaticArray<u8>(32).fill(0)
-const testbytesB = new StaticArray<u8>(32).fill(0)
 
-/** equalbytes */
+/**
+ * equalbytes - checks masked bytes against the following test keys:
+ * - random bytes
+ * - all zeros
+ * - all ones
+ */
+const zeros = new StaticArray<u8>(32).fill(0)
+const ones = new StaticArray<u8>(32).fill(255)
+const random = new StaticArray<u8>(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<u8>(32)
+
+for (let i = 0; i < vectors.length; i++) {
+       const vector = vectors[i]
+       const expected = expecteds[i]
+       memory.copy(changetype<usize>(actual), changetype<usize>(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
        }
 }
index 50f4bf143bd904f39f7993ffcec7a4bcbd55b944..6f95e93ab3543a728f4b576fa900f28a94085e4a 100644 (file)
@@ -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