diff --git a/src/utils.ts b/src/utils.ts index f04a3f3..1f5c97f 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -17,11 +17,14 @@ export function randomFq(): Fq { } export function randomFr(): Fr { - return new Fr(randomBigIntModP(31, R)) + return new Fr(randomBigIntModP(32, R)) } export function randomBigIntModP(bytes: number, p: bigint): bigint { const randUpperBound = 2n ** BigInt(bytes * 8) + if (randUpperBound < p) { + throw new Error(`Insufficient bytes for modulus ${p}`) + } const upperBound = randUpperBound - (randUpperBound % p) let rand: bigint while ((rand = randomBigInt(bytes)) >= upperBound) {} diff --git a/test/ff.spec.ts b/test/ff.spec.ts index 1eeb016..6f0baf1 100644 --- a/test/ff.spec.ts +++ b/test/ff.spec.ts @@ -2,6 +2,7 @@ import { expect } from 'chai' import fs from 'node:fs/promises' import path from 'node:path' import { Fq, Fq12, Fq2, Fq6, Fr } from '../src/ff' +import { randomFr } from '../src/utils' async function readTestVectors( name: string, @@ -98,6 +99,11 @@ const reviveFq12 = ([x, y, z]: SFq12[]): PFq12Vector => [ describe('finite fields', () => { describe('Fr', () => { + it('random', () => { + const r = randomFr() + expect(r.value).to.not.equal(0n) + }) + it('inv', () => { const expected: [Fr, Fr][] = [ [1n, 1n],