From 7d746a7408ad9e274d0d7eb8fb868953c0cf3925 Mon Sep 17 00:00:00 2001 From: Paul Miller Date: Thu, 15 Dec 2022 22:11:40 +0000 Subject: [PATCH] Add modular division --- README.md | 7 ++++--- src/modular.ts | 10 ++++++++++ 2 files changed, 14 insertions(+), 3 deletions(-) diff --git a/README.md b/README.md index be14f67..4c35010 100644 --- a/README.md +++ b/README.md @@ -69,12 +69,13 @@ secp256k1.sign(randomBytes(32), secp256k1.utils.randomPrivateKey()); import { twistedEdwards } from '@noble/curves/edwards'; // Twisted Edwards curve import { sha512 } from '@noble/hashes/sha512'; +import { div } from '@noble/curves/modular'; const ed25519 = twistedEdwards({ a: -1n, - d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n, - P: 57896044618658097711785492504343953926634992332820282019728792003956564819949n, - n: 7237005577332262213973186563042994240857116359379907606001950938285454250989n, + d: div(-121665n, 121666n, 2n ** 255n - 19n), // -121665n/121666n + P: 2n ** 255n - 19n, + n: 2n ** 252n + 27742317777372353535851937790883648493n, h: 8n, Gx: 15112221349535400772501151409588531511454012693041857206046113283949847762202n, Gy: 46316835694926478169428394003475163141307993866256225615783033603165251855960n, diff --git a/src/modular.ts b/src/modular.ts index 575d1fd..0ff6208 100644 --- a/src/modular.ts +++ b/src/modular.ts @@ -64,6 +64,16 @@ export function invert(number: bigint, modulo: bigint): bigint { return mod(x, modulo); } +/** + * Division over finite field. + * `a/b mod p == a * invert(b) mod p` + */ +export function div(numerator: bigint, denominator: bigint, modulo: bigint): bigint { + const num = mod(numerator, modulo); + const iden = invert(denominator, modulo); + return mod(num * iden, modulo); +} + /** * Takes a list of numbers, efficiently inverts all of them. * @param nums list of bigints