]> git.codecow.com Git - nano25519.git/commitdiff
Add fe_iszero guard start function. Clear temporary buffers after use.
authorChris Duncan <chris@codecow.com>
Fri, 9 Oct 2026 17:55:47 +0000 (10:55 -0700)
committerChris Duncan <chris@codecow.com>
Fri, 9 Oct 2026 17:55:47 +0000 (10:55 -0700)
src/assembly/crypto_derive.ts
src/assembly/crypto_sign.ts
src/assembly/crypto_verify.ts
src/assembly/ed25519/ge.ts
src/assembly/ed25519/t.ts
src/assembly/errors.ts
src/assembly/index.ts
src/assembly/tests.ts
src/lib/errors.ts
src/lib/wasm.ts
test/mutants.mjs

index d38e072b19f0f37fa6c7b3f61580c676ee08d836..942a87be3253612d384cb9709d6fb1fc89ccb85e 100644 (file)
@@ -3,7 +3,7 @@
 
 import { Blake2b } from './ed25519/blake2b'
 import { ge_scalarmult_base_tobytes } from './ed25519/ge'
-import { t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6 } from './ed25519/t'
+import { clear_t, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6 } from './ed25519/t'
 import { clamp } from './ed25519/utils'
 
 const PRIVATEKEY_BYTES: i32 = 32
@@ -42,4 +42,5 @@ export function crypto_derive (A: StaticArray<u8>, key: StaticArray<u8>): void {
        // Perform fixed-base scalar multiplication `[s]B`, output to public key `A`
        ge_scalarmult_base_tobytes(A, s, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6)
        s.fill(0)
+       clear_t()
 }
index 10c459b1d72facf1012782a4e8db647642109a51..b68fc536e1ecf0acf8752bd6fa6ada10e6084d46 100644 (file)
@@ -6,7 +6,7 @@ import { crypto_derive } from './crypto_derive'
 import { Blake2b } from './ed25519/blake2b'
 import { ge_scalarmult_base_tobytes } from './ed25519/ge'
 import { sc_muladd, sc_reduce } from './ed25519/sc'
-import { t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6 } from './ed25519/t'
+import { clear_t, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6 } from './ed25519/t'
 import { clamp } from './ed25519/utils'
 
 // crypto_hash function
@@ -49,7 +49,10 @@ export function crypto_sign (RS: StaticArray<u8>, M: StaticArray<u8>, mlen: i32,
                c |= A[i] ^ pub[i]
        }
        // Return early if `A` does not match public key
-       if (c != 0) return c
+       if (c != 0) {
+               A.fill(0)
+               return c
+       }
 
        // Hash private key to `h`
        blake2b.init().update(prv, KEY_BYTELENGTH).digest(h)
@@ -70,6 +73,7 @@ export function crypto_sign (RS: StaticArray<u8>, M: StaticArray<u8>, mlen: i32,
 
        // Perform fixed-base scalar multiplication `[r]B`, output to point `R`
        ge_scalarmult_base_tobytes(R, r, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6)
+       clear_t()
 
        // Compute challenge hash `blake2b(R || A || M)`, output to `k`
        blake2b.init().update(R, 32).update(A, 32).update(M, mlen).digest(k)
index 506a8ecda27151d22bb65bf776559e23b311c8a1..4d1b000bc9ad56433f277934b2dd6d155a2b8c9f 100644 (file)
@@ -6,7 +6,7 @@ import { Blake2b } from './ed25519/blake2b'
 import { ge_double_scalarmult_vartime_to_p3, ge_frombytes, ge_frombytes_negate_vartime, ge_has_small_order, ge_is_canonical } from './ed25519/ge'
 import { ge_cached, ge_p1p1, ge_p3, ge_p3_tobytes, ge_sub_p3 } from './ed25519/p'
 import { sc_is_canonical, sc_reduce } from './ed25519/sc'
-import { t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6 } from './ed25519/t'
+import { clear_t, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6 } from './ed25519/t'
 import { equalbytes } from './ed25519/utils'
 
 // crypto_hash function
@@ -29,8 +29,9 @@ const t_u8x32 = new StaticArray<u8>(32)
  * @returns 0 if public key fails to decode, else return pointer to A
  */
 export function crypto_verify_decodepubkey (pub: StaticArray<u8>): ge_p3 | null {
-       // fail if public key cannot be decoded
-       return (ge_frombytes_negate_vartime(A, pub, t_u8x32, t_fe_0, t_fe_1, t_fe_2) != 0) ? null : A
+       const b = ge_frombytes_negate_vartime(A, pub, t_u8x32, t_fe_0, t_fe_1, t_fe_2)
+       clear_t()
+       return (b != 0) ? null : A
 }
 
 /**
@@ -62,6 +63,7 @@ export function crypto_verify_donna (sig: StaticArray<u8>, M: StaticArray<u8>, A
 
        ge_double_scalarmult_vartime_to_p3(sb_ah, h, A, S, t_fe_0)
        ge_p3_tobytes(check_r, sb_ah, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6)
+       clear_t()
 
        return equalbytes(sig, check_r, KEY_BYTELENGTH)
 }
@@ -90,7 +92,9 @@ export function crypto_verify_sodium (sig: StaticArray<u8>, M: StaticArray<u8>,
        ge_double_scalarmult_vartime_to_p3(sb_ah, h, A, S, t_fe_0)
        ge_sub_p3(check, expected_r, sb_ah, t_fe_0, t_ge_cached, t_ge_p1p1)
 
-       return ge_has_small_order(check, t_fe_0, t_u8x32)
+       const b = ge_has_small_order(check, t_fe_0, t_u8x32)
+       clear_t()
+       return b
 }
 
 /**
@@ -119,6 +123,7 @@ export function crypto_verify_strict (sig: StaticArray<u8>, M: StaticArray<u8>,
        ge_sub_p3(check, expected_r, sb_ah, t_fe_0, t_ge_cached, t_ge_p1p1)
 
        ge_p3_tobytes(check_r, sb_ah, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6)
+       clear_t()
        return equalbytes(sig, check_r, KEY_BYTELENGTH)
 }
 
@@ -130,14 +135,23 @@ export function crypto_verify_strict (sig: StaticArray<u8>, M: StaticArray<u8>,
 function verify_pubkey (pub: StaticArray<u8>): boolean {
 
        // fail if public key `k` is non-canonical (`p = 2²⁵⁵-19 ≤ k`)
-       if (ge_is_canonical(pub) != 0) return false
+       if (ge_is_canonical(pub) != 0) {
+               return false
+       }
 
        // fail if public key cannot be decoded
-       if (ge_frombytes_negate_vartime(A, pub, t_u8x32, t_fe_0, t_fe_1, t_fe_2) != 0) return false
+       if (ge_frombytes_negate_vartime(A, pub, t_u8x32, t_fe_0, t_fe_1, t_fe_2) != 0) {
+               clear_t()
+               return false
+       }
 
        // fail if public key `k` is small order
-       if (ge_has_small_order(A, t_fe_0, t_u8x32) != 0) return false
+       if (ge_has_small_order(A, t_fe_0, t_u8x32) != 0) {
+               clear_t()
+               return false
+       }
 
+       clear_t()
        return true
 }
 
@@ -149,16 +163,27 @@ function verify_pubkey (pub: StaticArray<u8>): boolean {
 function verify_signature (sig: StaticArray<u8>): boolean {
        // fail if scalar `S` is non-canonical (`L ≤ S`)
        memory.copy(changetype<usize>(S), changetype<usize>(sig) + 32, 32)
-       if (!sc_is_canonical(S)) return false
+       if (!sc_is_canonical(S)) {
+               return false
+       }
 
        // fail if nonce `R` is non-canonical (`p ≤ R`)
-       if (ge_is_canonical(sig) != 0) return false
+       if (ge_is_canonical(sig) != 0) {
+               return false
+       }
 
        // fail if nonce `R` does not decode to a valid curve point
-       if (ge_frombytes(expected_r, sig, t_fe_0, t_fe_1, t_fe_2, t_u8x32) != 0) return false
+       if (ge_frombytes(expected_r, sig, t_fe_0, t_fe_1, t_fe_2, t_u8x32) != 0) {
+               clear_t()
+               return false
+       }
 
        // fail if nonce `R` is small order
-       if (ge_has_small_order(expected_r, t_fe_0, t_u8x32) != 0) return false
+       if (ge_has_small_order(expected_r, t_fe_0, t_u8x32) != 0) {
+               clear_t()
+               return false
+       }
 
+       clear_t()
        return true
 }
index a0bbfe65f3a35ab72594ec029f5c2f721d838c49..d664ad75948bca8d59bd0487433cf4de5f3b0533 100644 (file)
@@ -336,9 +336,7 @@ export function ge_scalarmult_base_tobytes (S: StaticArray<u8>, a: StaticArray<u
                ge_p1p1_to_p3(h, r)
        }
 
-       ge_p3_tobytes(S, h,
-               t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6
-       )
+       ge_p3_tobytes(S, h, t_fe_0, t_fe_1, t_fe_2, t_fe_3, t_fe_4, t_fe_5, t_fe_6)
 
        // clear sensitive data
        ge_p1p1_0(r)
@@ -346,13 +344,6 @@ export function ge_scalarmult_base_tobytes (S: StaticArray<u8>, a: StaticArray<u
        ge_precomp_0(t)
        ge_p3_0(h)
        e.fill(0)
-       t_fe_0.fill(0)
-       t_fe_1.fill(0)
-       t_fe_2.fill(0)
-       t_fe_3.fill(0)
-       t_fe_4.fill(0)
-       t_fe_5.fill(0)
-       t_fe_6.fill(0)
 }
 
 const ge_double_scalarmult_vartime_aslide: StaticArray<i8> = new StaticArray<i8>(256)
index 4e4afcd83818f376bb59bcf9e5d0fb28ad7bc06e..566f8c949e03079bcb82efdff09747200ff9b4e3 100644 (file)
@@ -2,10 +2,14 @@
 //! SPDX-License-Identifier: GPL-3.0-or-later
 
 /**
- * Shared buffers for holding temporary values. To ensure buffers are not
- * overwritten between dependent calls, these should only be imported from the
- * highest call site (i.e. crypto_derive/crypto_sign/crypto_verify) and passed
- * down to lower functions as parameter arguments.
+ * Shared buffers for holding temporary values. Only import in `crypto_derive`,
+ * `crypto_sign`, and `crypto_verify`; they pass scratch buffers to lower
+ * functions as `t_` parameters, and they clear all buffers when done with them.
+ *
+ * Beware nested calls. `crypto_sign` calls `crypto_derive` which overwrites all
+ * temporary buffers; this specific call is OK because they never use the
+ * buffers at the same time. However, never pass a buffer to a called function
+ * if it presently holds a value in the current function.
  */
 import { fe } from './fe'
 
@@ -16,3 +20,13 @@ export const t_fe_3 = fe()
 export const t_fe_4 = fe()
 export const t_fe_5 = fe()
 export const t_fe_6 = fe()
+
+export function clear_t (): void {
+       t_fe_0.fill(0)
+       t_fe_1.fill(0)
+       t_fe_2.fill(0)
+       t_fe_3.fill(0)
+       t_fe_4.fill(0)
+       t_fe_5.fill(0)
+       t_fe_6.fill(0)
+}
index 425598263699c129fb21b4485451ba5dd6c86f24..42f19e155eeffa73a2c299c7bf9614ef37449fe0 100644 (file)
@@ -56,3 +56,14 @@ export const ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: i32 = 8
  */
 export const ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: i32 = 9
 export const ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: i32 = 10
+
+/**
+ * `fe_iszero` start-function guard in `tests.ts`. `a` is the packed case that
+ * failed, which rebuilds the exact 32 input bytes (see `fe_case` there and
+ * `zeroCase` in `src/lib/errors.ts`); `b` is what the function returned.
+ *
+ * - `XPASS`: a value that is 0 mod `p` was reported nonzero
+ * - `XFAIL`: a nonzero value was reported zero
+ */
+export const ERROR_FE_ISZERO_SELFTEST_XPASS: i32 = 11
+export const ERROR_FE_ISZERO_SELFTEST_XFAIL: i32 = 12
index 4a4d2c80ccdec2f4ee8a78a043258e729d59bedf..8c5f26576f37d33fa9a6f08abb2009b54ad019a1 100644 (file)
@@ -6,10 +6,10 @@ import { crypto_derive, } from './crypto_derive'
 import { crypto_sign, } from './crypto_sign'
 import { crypto_verify_decodepubkey, crypto_verify_donna, crypto_verify_sodium, } from './crypto_verify'
 import { raise, } from './env'
-import { BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_UNKNOWN, } from './errors'
+import { BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_FE_ISZERO_SELFTEST_XFAIL, ERROR_FE_ISZERO_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_UNKNOWN, } from './errors'
 import './tests'
 
-export { BLOCKHASH_BYTELENGTH, BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, ERROR_UNKNOWN, KEY_BYTELENGTH, MAX_MESSAGE_BYTELENGTH, MAX_VERIFY_BLOCKS, MAX_VERIFY_BLOCKS_BYTELENGTH, SIGNATURE_BYTELENGTH }
+export { BLOCKHASH_BYTELENGTH, BUFFER_INPUT_MSG, BUFFER_INPUT_PRV, BUFFER_INPUT_PUB, BUFFER_INPUT_SIG, BUFFER_OUTPUT_DERIVE, BUFFER_OUTPUT_SIGN, BUFFER_OUTPUT_VERIFY, ERROR_BYTE_OUT_OF_RANGE, ERROR_INDEX_OUT_OF_RANGE, ERROR_INVALID_BLOCK_COUNT, ERROR_INVALID_MESSAGE_LENGTH, ERROR_INVALID_PUBLIC_KEY, ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_FE_ISZERO_SELFTEST_XFAIL, ERROR_FE_ISZERO_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, ERROR_UNKNOWN, KEY_BYTELENGTH, MAX_MESSAGE_BYTELENGTH, MAX_VERIFY_BLOCKS, MAX_VERIFY_BLOCKS_BYTELENGTH, SIGNATURE_BYTELENGTH }
 
 // Static I/O buffers
 const INPUT_MSG = new StaticArray<u8>(MAX_MESSAGE_BYTELENGTH)
index ad69e0b70e77497896b6aee695fe191621744f16..a788be363dd190049217777de4a4b0934902fbd3 100644 (file)
@@ -2,10 +2,11 @@
 //! SPDX-License-Identifier: GPL-3.0-or-later
 
 import { KEY_BYTELENGTH } from './constants'
+import { fe, fe_frombytes, fe_iszero } from './ed25519/fe'
 import { ge_is_canonical } from './ed25519/ge'
 import { equalbytes } from './ed25519/utils'
 import { raise, } from './env'
-import { ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, } from './errors'
+import { ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE, ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR, ERROR_EQUALBYTES_SELFTEST_XPASS, ERROR_FE_ISZERO_SELFTEST_XFAIL, ERROR_FE_ISZERO_SELFTEST_XPASS, ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL, ERROR_GE_IS_CANONICAL_SELFTEST_XPASS, } from './errors'
 
 /**
  * Build guards, run from the module's start function. A failure aborts
@@ -168,3 +169,85 @@ for (let sign = 0; sign < 2; sign++) {
                }
        }
 }
+
+/**
+ * `fe_iszero` must report zero exactly when a field element is 0 mod `p`. It
+ * decides whether a point decodes, in the square-root checks of `ge_frombytes`
+ * and `ge_frombytes_negate_vartime`, and whether a key or `R` is small order,
+ * and its dangerous failure is reporting zero for a value that is not, which
+ * would let an invalid point decode. It reduces the value to 32 canonical bytes
+ * and tests them as two 16-byte halves, so the cases cover every byte of both
+ * halves, and the reduction in front of them with the loose limbs `fe_sub`
+ * hands it in `ge_frombytes`.
+ *
+ * A case packs into one integer, which is also its error detail, so the host
+ * can rebuild the exact bytes that failed:
+ * - bits 0-7: a byte value `m`
+ * - bits 8-12 and 13-17: byte positions `i` and `j`
+ * - bits 18-19: the shape, one of the `FE_*` values below
+ */
+const FE_ZERO: i32 = 0 // 0
+const FE_P: i32 = 1 // p + m as loose limbs at their bounds: zero only when m is 0
+const FE_ONE: i32 = 2 // byte i set to m
+const FE_PAIR: i32 = 3 // bytes i and j both set to m
+
+const check_fe_iszero_f = fe()
+const check_fe_iszero_t_fe = fe()
+const check_fe_iszero_t_u8x32 = new StaticArray<u8>(KEY_BYTELENGTH)
+
+function fe_case (shape: i32, m: i32, i: i32 = 0, j: i32 = 0): i32 {
+       return m | (i << 8) | (j << 13) | (shape << 18)
+}
+
+function check_fe_iszero (c: i32, zero: bool): void {
+       const shape = (c >> 18) & 3
+       const m = c & 0xff
+       if (shape == FE_P) {
+               // fe_frombytes would fold p to 0, so write the limbs of p + m directly:
+               // every limb at its maximum, 2²⁶ - 1 or 2²⁵ - 1, and limb 0 at 2²⁶ - 19 + m
+               for (let k = 0; k < 10; k++) {
+                       store<i32>(changetype<usize>(check_fe_iszero_f) + (k << 2), (k & 1) != 0 ? (1 << 25) - 1 : (1 << 26) - 1)
+               }
+               store<i32>(changetype<usize>(check_fe_iszero_f), (1 << 26) - 19 + m, 0)
+       } else {
+               actual.fill(0)
+               if (shape != FE_ZERO) {
+                       actual[(c >> 8) & 31] = u8(m)
+                       if (shape == FE_PAIR) actual[(c >> 13) & 31] = u8(m)
+               }
+               fe_frombytes(check_fe_iszero_f, actual)
+       }
+
+       const result = fe_iszero(check_fe_iszero_f, check_fe_iszero_t_fe, check_fe_iszero_t_u8x32)
+       if (zero && result != 1) {
+               raise(ERROR_FE_ISZERO_SELFTEST_XPASS, c, result)
+       }
+       if (!zero && result != 0) {
+               raise(ERROR_FE_ISZERO_SELFTEST_XFAIL, c, result)
+       }
+}
+
+// Zero, then `p + m` in loose limbs, which only the final reduction brings below
+// `p`: `p` itself must read as zero, and from `p + 19 = 2²⁵⁵` on the value
+// crosses the top bit, where a reduction that gets `q` wrong reads 19 as zero.
+check_fe_iszero(fe_case(FE_ZERO, 0), true)
+for (let m = 0; m < 256; m++) {
+       check_fe_iszero(fe_case(FE_P, m), m == 0)
+}
+
+// Every single bit of every byte. Bit 255 is not part of the value, so byte 31
+// stops at bit 6. Dropping or misreading either half fails here, and so does an
+// accumulator that sees only some bits of each byte.
+for (let i = 0; i < KEY_BYTELENGTH; i++) {
+       for (let bit = 0; bit < (i < 31 ? 8 : 7); bit++) {
+               check_fe_iszero(fe_case(FE_ONE, 1 << bit, i), false)
+       }
+}
+
+// The same byte at every pair of positions. Halves combined with xor instead of
+// or cancel at stride 16 and nowhere else.
+for (let i = 0; i < KEY_BYTELENGTH; i++) {
+       for (let j = i + 1; j < KEY_BYTELENGTH; j++) {
+               check_fe_iszero(fe_case(FE_PAIR, 0x40, i, j), false)
+       }
+}
index 80217ec83cdeb5a40c12fecea3db3b5d7320a511..3a34d76bdb664a278bbfa7fa56a168b24c9bcd5e 100644 (file)
@@ -32,6 +32,8 @@ export const errorCodes: Record<string, number> = {
        ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: 8,
        ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: 9,
        ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: 10,
+       ERROR_FE_ISZERO_SELFTEST_XPASS: 11,
+       ERROR_FE_ISZERO_SELFTEST_XFAIL: 12,
 }
 
 /** Buffer ids from `src/assembly/errors.ts`, in value order. */
@@ -114,6 +116,38 @@ function canonicalFailure (code: number, c: number, result: number): string {
        return `ge_is_canonical build error from "${HIGH[(c >> 9) & 3]}": expected ${expected} [${canonicalCase(c)}]; actual returned ${result} (byte 0 = 0x${hex(c & 0xff)}, sign ${(c >> 8) & 1}${flipped})`
 }
 
+/** The `fe_iszero` shapes, by `FE_*` value. */
+const SHAPES = ['zero', 'p', 'one', 'pair']
+
+/**
+ * Rebuilds the 32 bytes of a packed `fe_iszero` case. Mirrors `check_fe_iszero`
+ * in `tests.ts`.
+ */
+function zeroCase (c: number): number[] {
+       const shape = (c >> 18) & 3
+       const m = c & 0xff
+       const bytes: number[] = new Array(ENCODING_BYTELENGTH).fill(0)
+       if (shape === 1) {
+               // p + m reaches 2²⁵⁵ from m = 19, so this one needs all 256 bits
+               const value = (1n << 255n) - 19n + BigInt(m)
+               for (let i = 0; i < ENCODING_BYTELENGTH; i++) {
+                       bytes[i] = Number((value >> BigInt(8 * i)) & 0xffn)
+               }
+       } else if (shape !== 0) {
+               bytes[(c >> 8) & 31] = m
+               if (shape === 3) bytes[(c >> 13) & 31] = m
+       }
+       return bytes
+}
+
+function zeroFailure (code: number, c: number, result: number): string {
+       const expected = code === errorCodes.ERROR_FE_ISZERO_SELFTEST_XPASS ? 'zero' : 'nonzero'
+       const shape = (c >> 18) & 3
+       const m = c & 0xff
+       const where = shape === 1 ? `p + ${m} as loose limbs` : shape === 2 ? `byte ${(c >> 8) & 31} = 0x${hex(m)}` : shape === 3 ? `bytes ${(c >> 8) & 31} and ${(c >> 13) & 31} = 0x${hex(m)}` : '0'
+       return `fe_iszero build error from "${SHAPES[shape]}": expected ${expected} [${zeroCase(c)}]; actual returned ${result} (${where})`
+}
+
 /**
  * Turns the four integers reported by `env.abort` into a message. `line` only
  * locates an ERROR_UNKNOWN abort: every coded site reports the `throw` inside
@@ -139,6 +173,9 @@ function describe (code: number, line: number, detail: number, context: number):
                case errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XPASS:
                case errorCodes.ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL:
                        return canonicalFailure(code, detail, context)
+               case errorCodes.ERROR_FE_ISZERO_SELFTEST_XPASS:
+               case errorCodes.ERROR_FE_ISZERO_SELFTEST_XFAIL:
+                       return zeroFailure(code, detail, context)
                default:
                        return `Unrecognized wasm abort (code ${code}, a ${detail}, b ${context}), row ${line}`
        }
index 5ccc6f00f09ecb0cf6c044371fc28f9cc90deb0f..ad139cd04b62901f67ca88728d8dedd376e906f3 100644 (file)
@@ -40,6 +40,8 @@ type Exports = WebAssembly.Instance['exports'] & {
        ERROR_EQUALBYTES_SELFTEST_XFAIL_ONE: WebAssembly.Global<'i32'>
        ERROR_EQUALBYTES_SELFTEST_XFAIL_PAIR: WebAssembly.Global<'i32'>
        ERROR_EQUALBYTES_SELFTEST_XPASS: WebAssembly.Global<'i32'>
+       ERROR_FE_ISZERO_SELFTEST_XFAIL: WebAssembly.Global<'i32'>
+       ERROR_FE_ISZERO_SELFTEST_XPASS: WebAssembly.Global<'i32'>
        ERROR_GE_IS_CANONICAL_SELFTEST_XFAIL: WebAssembly.Global<'i32'>
        ERROR_GE_IS_CANONICAL_SELFTEST_XPASS: WebAssembly.Global<'i32'>
        ERROR_UNKNOWN: WebAssembly.Global<'i32'>
index 45a8343d63daefc0526a16ea075492f328dbe184..9ddb32ede633006f903a53d621ff608d0f169fdd 100644 (file)
@@ -28,8 +28,12 @@ const asc = new URL('node_modules/assemblyscript/bin/asc.js', root).pathname
 
 const EQUALBYTES = { fn: 'equalbytes', file: 'src/assembly/ed25519/utils.ts', codes: 'ERROR_EQUALBYTES_SELFTEST_' }
 const GE_IS_CANONICAL = { fn: 'ge_is_canonical', file: 'src/assembly/ed25519/ge.ts', codes: 'ERROR_GE_IS_CANONICAL_SELFTEST_' }
+const FE_ISZERO = { fn: 'fe_iszero', file: 'src/assembly/ed25519/fe.ts', codes: 'ERROR_FE_ISZERO_SELFTEST_' }
 
-/** `from` must occur exactly once inside the named function. */
+/**
+ * `from` must occur exactly once inside the guarded function, or inside `in`
+ * when the defect is in a function the guarded one depends on.
+ */
 const mutants = [
        { guard: EQUALBYTES, from: 'b |= f[i] ^ g[i]', to: 'b ^= f[i] ^ g[i]', why: 'accumulates with ^=, so equal deltas cancel' },
        { guard: EQUALBYTES, from: 'b |= f[i] ^ g[i]', to: 'b += f[i] ^ g[i]', why: 'accumulates with +=, so 0x80 pairs cancel in the byte mask' },
@@ -41,6 +45,12 @@ const mutants = [
        { guard: GE_IS_CANONICAL, from: '(s[31] & 0x7f) ^ 0x7f', to: 's[31] ^ 0x7f', why: 'does not mask the sign bit' },
        { guard: GE_IS_CANONICAL, from: '(0xec - s[0]) >> 8', to: '(0xed - s[0]) >> 8', why: 'accepts p itself' },
        { guard: GE_IS_CANONICAL, from: 'c & d & 1', to: '(c | d) & 1', why: 'combines its two conditions with | instead of &' },
+       { guard: FE_ISZERO, from: 'const d = v128.or(t0, t1)', to: 'const d = t0', why: 'tests only the low half' },
+       { guard: FE_ISZERO, from: 'const d = v128.or(t0, t1)', to: 'const d = v128.xor(t0, t1)', why: 'combines the halves with xor, so equal bytes 16 apart cancel' },
+       { guard: FE_ISZERO, from: 'const d = v128.or(t0, t1)', to: 'const d = v128.and(t0, t1)', why: 'combines the halves with and' },
+       { guard: FE_ISZERO, from: 'v128.load(changetype<usize>(t_u8x32), 16)', to: 'v128.load(changetype<usize>(t_u8x32), 15)', why: 'loads the high half a byte early, so byte 31 is never tested' },
+       { guard: FE_ISZERO, from: 'return u8(v128.any_true(d)) ^ 1', to: 'return u8(v128.any_true(d))', why: 'inverts its result' },
+       { guard: FE_ISZERO, in: 'fe_reduce', from: 'q = (f9 + q) >> 25', to: 'q = (f9 + q) >> 26', why: 'reduces with a 26-bit shift where the top limb is 25 bits, so loose limbs past 2²⁵⁵ come out wrong' },
 ]
 
 /** Copies the sources, applies one replacement inside one function, and compiles. */
@@ -50,7 +60,8 @@ async function build (name, mutant) {
        await cp(new URL('src/', root), new URL('src/', dir), { recursive: true })
        await cp(new URL('asconfig.json', root), new URL('asconfig.json', dir))
        if (mutant != null) {
-               const { guard: { fn, file }, from, to } = mutant
+               const { guard: { file }, from, to } = mutant
+               const fn = mutant.in ?? mutant.guard.fn
                const path = new URL(file, dir)
                const source = await readFile(path, 'utf8')
                const start = source.indexOf(`export function ${fn} (`)
@@ -127,6 +138,12 @@ try {
                        const y = bytes.reduceRight((n, b) => (n << 8n) | BigInt(b), 0n) & ((1n << 255n) - 1n)
                        test = (y < p) === result.message.includes('expected canonical')
                }
+               if (test && guard === FE_ISZERO) {
+                       // all 256 bits: the loose-limb cases go past 2²⁵⁵
+                       const bytes = JSON.parse(result.message.match(/\[[\d,]+\]/)[0])
+                       const y = bytes.reduceRight((n, b) => (n << 8n) | BigInt(b), 0n)
+                       test = (y % p === 0n) === result.message.includes('expected zero')
+               }
                check(`${guard.fn} guard rejects a build that ${why}`, test, `${code}: ${result.message ?? 'instantiated'}`)
        }
 } finally {