modular.js 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416
  1. /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
  2. // Utilities for modular arithmetics and finite fields
  3. import { bitMask, bytesToNumberBE, bytesToNumberLE, ensureBytes, numberToBytesBE, numberToBytesLE, validateObject, } from './utils.js';
  4. // prettier-ignore
  5. const _0n = BigInt(0), _1n = BigInt(1), _2n = BigInt(2), _3n = BigInt(3);
  6. // prettier-ignore
  7. const _4n = BigInt(4), _5n = BigInt(5), _8n = BigInt(8);
  8. // prettier-ignore
  9. const _9n = BigInt(9), _16n = BigInt(16);
  10. // Calculates a modulo b
  11. export function mod(a, b) {
  12. const result = a % b;
  13. return result >= _0n ? result : b + result;
  14. }
  15. /**
  16. * Efficiently raise num to power and do modular division.
  17. * Unsafe in some contexts: uses ladder, so can expose bigint bits.
  18. * @example
  19. * pow(2n, 6n, 11n) // 64n % 11n == 9n
  20. */
  21. // TODO: use field version && remove
  22. export function pow(num, power, modulo) {
  23. if (modulo <= _0n || power < _0n)
  24. throw new Error('Expected power/modulo > 0');
  25. if (modulo === _1n)
  26. return _0n;
  27. let res = _1n;
  28. while (power > _0n) {
  29. if (power & _1n)
  30. res = (res * num) % modulo;
  31. num = (num * num) % modulo;
  32. power >>= _1n;
  33. }
  34. return res;
  35. }
  36. // Does x ^ (2 ^ power) mod p. pow2(30, 4) == 30 ^ (2 ^ 4)
  37. export function pow2(x, power, modulo) {
  38. let res = x;
  39. while (power-- > _0n) {
  40. res *= res;
  41. res %= modulo;
  42. }
  43. return res;
  44. }
  45. // Inverses number over modulo
  46. export function invert(number, modulo) {
  47. if (number === _0n || modulo <= _0n) {
  48. throw new Error(`invert: expected positive integers, got n=${number} mod=${modulo}`);
  49. }
  50. // Euclidean GCD https://brilliant.org/wiki/extended-euclidean-algorithm/
  51. // Fermat's little theorem "CT-like" version inv(n) = n^(m-2) mod m is 30x slower.
  52. let a = mod(number, modulo);
  53. let b = modulo;
  54. // prettier-ignore
  55. let x = _0n, y = _1n, u = _1n, v = _0n;
  56. while (a !== _0n) {
  57. // JIT applies optimization if those two lines follow each other
  58. const q = b / a;
  59. const r = b % a;
  60. const m = x - u * q;
  61. const n = y - v * q;
  62. // prettier-ignore
  63. b = a, a = r, x = u, y = v, u = m, v = n;
  64. }
  65. const gcd = b;
  66. if (gcd !== _1n)
  67. throw new Error('invert: does not exist');
  68. return mod(x, modulo);
  69. }
  70. /**
  71. * Tonelli-Shanks square root search algorithm.
  72. * 1. https://eprint.iacr.org/2012/685.pdf (page 12)
  73. * 2. Square Roots from 1; 24, 51, 10 to Dan Shanks
  74. * Will start an infinite loop if field order P is not prime.
  75. * @param P field order
  76. * @returns function that takes field Fp (created from P) and number n
  77. */
  78. export function tonelliShanks(P) {
  79. // Legendre constant: used to calculate Legendre symbol (a | p),
  80. // which denotes the value of a^((p-1)/2) (mod p).
  81. // (a | p) ≡ 1 if a is a square (mod p)
  82. // (a | p) ≡ -1 if a is not a square (mod p)
  83. // (a | p) ≡ 0 if a ≡ 0 (mod p)
  84. const legendreC = (P - _1n) / _2n;
  85. let Q, S, Z;
  86. // Step 1: By factoring out powers of 2 from p - 1,
  87. // find q and s such that p - 1 = q*(2^s) with q odd
  88. for (Q = P - _1n, S = 0; Q % _2n === _0n; Q /= _2n, S++)
  89. ;
  90. // Step 2: Select a non-square z such that (z | p) ≡ -1 and set c ≡ zq
  91. for (Z = _2n; Z < P && pow(Z, legendreC, P) !== P - _1n; Z++)
  92. ;
  93. // Fast-path
  94. if (S === 1) {
  95. const p1div4 = (P + _1n) / _4n;
  96. return function tonelliFast(Fp, n) {
  97. const root = Fp.pow(n, p1div4);
  98. if (!Fp.eql(Fp.sqr(root), n))
  99. throw new Error('Cannot find square root');
  100. return root;
  101. };
  102. }
  103. // Slow-path
  104. const Q1div2 = (Q + _1n) / _2n;
  105. return function tonelliSlow(Fp, n) {
  106. // Step 0: Check that n is indeed a square: (n | p) should not be ≡ -1
  107. if (Fp.pow(n, legendreC) === Fp.neg(Fp.ONE))
  108. throw new Error('Cannot find square root');
  109. let r = S;
  110. // TODO: will fail at Fp2/etc
  111. let g = Fp.pow(Fp.mul(Fp.ONE, Z), Q); // will update both x and b
  112. let x = Fp.pow(n, Q1div2); // first guess at the square root
  113. let b = Fp.pow(n, Q); // first guess at the fudge factor
  114. while (!Fp.eql(b, Fp.ONE)) {
  115. if (Fp.eql(b, Fp.ZERO))
  116. return Fp.ZERO; // https://en.wikipedia.org/wiki/Tonelli%E2%80%93Shanks_algorithm (4. If t = 0, return r = 0)
  117. // Find m such b^(2^m)==1
  118. let m = 1;
  119. for (let t2 = Fp.sqr(b); m < r; m++) {
  120. if (Fp.eql(t2, Fp.ONE))
  121. break;
  122. t2 = Fp.sqr(t2); // t2 *= t2
  123. }
  124. // NOTE: r-m-1 can be bigger than 32, need to convert to bigint before shift, otherwise there will be overflow
  125. const ge = Fp.pow(g, _1n << BigInt(r - m - 1)); // ge = 2^(r-m-1)
  126. g = Fp.sqr(ge); // g = ge * ge
  127. x = Fp.mul(x, ge); // x *= ge
  128. b = Fp.mul(b, g); // b *= g
  129. r = m;
  130. }
  131. return x;
  132. };
  133. }
  134. export function FpSqrt(P) {
  135. // NOTE: different algorithms can give different roots, it is up to user to decide which one they want.
  136. // For example there is FpSqrtOdd/FpSqrtEven to choice root based on oddness (used for hash-to-curve).
  137. // P ≡ 3 (mod 4)
  138. // √n = n^((P+1)/4)
  139. if (P % _4n === _3n) {
  140. // Not all roots possible!
  141. // const ORDER =
  142. // 0x1a0111ea397fe69a4b1ba7b6434bacd764774b84f38512bf6730d2a0f6b0f6241eabfffeb153ffffb9feffffffffaaabn;
  143. // const NUM = 72057594037927816n;
  144. const p1div4 = (P + _1n) / _4n;
  145. return function sqrt3mod4(Fp, n) {
  146. const root = Fp.pow(n, p1div4);
  147. // Throw if root**2 != n
  148. if (!Fp.eql(Fp.sqr(root), n))
  149. throw new Error('Cannot find square root');
  150. return root;
  151. };
  152. }
  153. // Atkin algorithm for q ≡ 5 (mod 8), https://eprint.iacr.org/2012/685.pdf (page 10)
  154. if (P % _8n === _5n) {
  155. const c1 = (P - _5n) / _8n;
  156. return function sqrt5mod8(Fp, n) {
  157. const n2 = Fp.mul(n, _2n);
  158. const v = Fp.pow(n2, c1);
  159. const nv = Fp.mul(n, v);
  160. const i = Fp.mul(Fp.mul(nv, _2n), v);
  161. const root = Fp.mul(nv, Fp.sub(i, Fp.ONE));
  162. if (!Fp.eql(Fp.sqr(root), n))
  163. throw new Error('Cannot find square root');
  164. return root;
  165. };
  166. }
  167. // P ≡ 9 (mod 16)
  168. if (P % _16n === _9n) {
  169. // NOTE: tonelli is too slow for bls-Fp2 calculations even on start
  170. // Means we cannot use sqrt for constants at all!
  171. //
  172. // const c1 = Fp.sqrt(Fp.negate(Fp.ONE)); // 1. c1 = sqrt(-1) in F, i.e., (c1^2) == -1 in F
  173. // const c2 = Fp.sqrt(c1); // 2. c2 = sqrt(c1) in F, i.e., (c2^2) == c1 in F
  174. // const c3 = Fp.sqrt(Fp.negate(c1)); // 3. c3 = sqrt(-c1) in F, i.e., (c3^2) == -c1 in F
  175. // const c4 = (P + _7n) / _16n; // 4. c4 = (q + 7) / 16 # Integer arithmetic
  176. // sqrt = (x) => {
  177. // let tv1 = Fp.pow(x, c4); // 1. tv1 = x^c4
  178. // let tv2 = Fp.mul(c1, tv1); // 2. tv2 = c1 * tv1
  179. // const tv3 = Fp.mul(c2, tv1); // 3. tv3 = c2 * tv1
  180. // let tv4 = Fp.mul(c3, tv1); // 4. tv4 = c3 * tv1
  181. // const e1 = Fp.equals(Fp.square(tv2), x); // 5. e1 = (tv2^2) == x
  182. // const e2 = Fp.equals(Fp.square(tv3), x); // 6. e2 = (tv3^2) == x
  183. // tv1 = Fp.cmov(tv1, tv2, e1); // 7. tv1 = CMOV(tv1, tv2, e1) # Select tv2 if (tv2^2) == x
  184. // tv2 = Fp.cmov(tv4, tv3, e2); // 8. tv2 = CMOV(tv4, tv3, e2) # Select tv3 if (tv3^2) == x
  185. // const e3 = Fp.equals(Fp.square(tv2), x); // 9. e3 = (tv2^2) == x
  186. // return Fp.cmov(tv1, tv2, e3); // 10. z = CMOV(tv1, tv2, e3) # Select the sqrt from tv1 and tv2
  187. // }
  188. }
  189. // Other cases: Tonelli-Shanks algorithm
  190. return tonelliShanks(P);
  191. }
  192. // Little-endian check for first LE bit (last BE bit);
  193. export const isNegativeLE = (num, modulo) => (mod(num, modulo) & _1n) === _1n;
  194. // prettier-ignore
  195. const FIELD_FIELDS = [
  196. 'create', 'isValid', 'is0', 'neg', 'inv', 'sqrt', 'sqr',
  197. 'eql', 'add', 'sub', 'mul', 'pow', 'div',
  198. 'addN', 'subN', 'mulN', 'sqrN'
  199. ];
  200. export function validateField(field) {
  201. const initial = {
  202. ORDER: 'bigint',
  203. MASK: 'bigint',
  204. BYTES: 'isSafeInteger',
  205. BITS: 'isSafeInteger',
  206. };
  207. const opts = FIELD_FIELDS.reduce((map, val) => {
  208. map[val] = 'function';
  209. return map;
  210. }, initial);
  211. return validateObject(field, opts);
  212. }
  213. // Generic field functions
  214. /**
  215. * Same as `pow` but for Fp: non-constant-time.
  216. * Unsafe in some contexts: uses ladder, so can expose bigint bits.
  217. */
  218. export function FpPow(f, num, power) {
  219. // Should have same speed as pow for bigints
  220. // TODO: benchmark!
  221. if (power < _0n)
  222. throw new Error('Expected power > 0');
  223. if (power === _0n)
  224. return f.ONE;
  225. if (power === _1n)
  226. return num;
  227. let p = f.ONE;
  228. let d = num;
  229. while (power > _0n) {
  230. if (power & _1n)
  231. p = f.mul(p, d);
  232. d = f.sqr(d);
  233. power >>= _1n;
  234. }
  235. return p;
  236. }
  237. /**
  238. * Efficiently invert an array of Field elements.
  239. * `inv(0)` will return `undefined` here: make sure to throw an error.
  240. */
  241. export function FpInvertBatch(f, nums) {
  242. const tmp = new Array(nums.length);
  243. // Walk from first to last, multiply them by each other MOD p
  244. const lastMultiplied = nums.reduce((acc, num, i) => {
  245. if (f.is0(num))
  246. return acc;
  247. tmp[i] = acc;
  248. return f.mul(acc, num);
  249. }, f.ONE);
  250. // Invert last element
  251. const inverted = f.inv(lastMultiplied);
  252. // Walk from last to first, multiply them by inverted each other MOD p
  253. nums.reduceRight((acc, num, i) => {
  254. if (f.is0(num))
  255. return acc;
  256. tmp[i] = f.mul(acc, tmp[i]);
  257. return f.mul(acc, num);
  258. }, inverted);
  259. return tmp;
  260. }
  261. export function FpDiv(f, lhs, rhs) {
  262. return f.mul(lhs, typeof rhs === 'bigint' ? invert(rhs, f.ORDER) : f.inv(rhs));
  263. }
  264. // This function returns True whenever the value x is a square in the field F.
  265. export function FpIsSquare(f) {
  266. const legendreConst = (f.ORDER - _1n) / _2n; // Integer arithmetic
  267. return (x) => {
  268. const p = f.pow(x, legendreConst);
  269. return f.eql(p, f.ZERO) || f.eql(p, f.ONE);
  270. };
  271. }
  272. // CURVE.n lengths
  273. export function nLength(n, nBitLength) {
  274. // Bit size, byte size of CURVE.n
  275. const _nBitLength = nBitLength !== undefined ? nBitLength : n.toString(2).length;
  276. const nByteLength = Math.ceil(_nBitLength / 8);
  277. return { nBitLength: _nBitLength, nByteLength };
  278. }
  279. /**
  280. * Initializes a finite field over prime. **Non-primes are not supported.**
  281. * Do not init in loop: slow. Very fragile: always run a benchmark on a change.
  282. * Major performance optimizations:
  283. * * a) denormalized operations like mulN instead of mul
  284. * * b) same object shape: never add or remove keys
  285. * * c) Object.freeze
  286. * @param ORDER prime positive bigint
  287. * @param bitLen how many bits the field consumes
  288. * @param isLE (def: false) if encoding / decoding should be in little-endian
  289. * @param redef optional faster redefinitions of sqrt and other methods
  290. */
  291. export function Field(ORDER, bitLen, isLE = false, redef = {}) {
  292. if (ORDER <= _0n)
  293. throw new Error(`Expected Field ORDER > 0, got ${ORDER}`);
  294. const { nBitLength: BITS, nByteLength: BYTES } = nLength(ORDER, bitLen);
  295. if (BYTES > 2048)
  296. throw new Error('Field lengths over 2048 bytes are not supported');
  297. const sqrtP = FpSqrt(ORDER);
  298. const f = Object.freeze({
  299. ORDER,
  300. BITS,
  301. BYTES,
  302. MASK: bitMask(BITS),
  303. ZERO: _0n,
  304. ONE: _1n,
  305. create: (num) => mod(num, ORDER),
  306. isValid: (num) => {
  307. if (typeof num !== 'bigint')
  308. throw new Error(`Invalid field element: expected bigint, got ${typeof num}`);
  309. return _0n <= num && num < ORDER; // 0 is valid element, but it's not invertible
  310. },
  311. is0: (num) => num === _0n,
  312. isOdd: (num) => (num & _1n) === _1n,
  313. neg: (num) => mod(-num, ORDER),
  314. eql: (lhs, rhs) => lhs === rhs,
  315. sqr: (num) => mod(num * num, ORDER),
  316. add: (lhs, rhs) => mod(lhs + rhs, ORDER),
  317. sub: (lhs, rhs) => mod(lhs - rhs, ORDER),
  318. mul: (lhs, rhs) => mod(lhs * rhs, ORDER),
  319. pow: (num, power) => FpPow(f, num, power),
  320. div: (lhs, rhs) => mod(lhs * invert(rhs, ORDER), ORDER),
  321. // Same as above, but doesn't normalize
  322. sqrN: (num) => num * num,
  323. addN: (lhs, rhs) => lhs + rhs,
  324. subN: (lhs, rhs) => lhs - rhs,
  325. mulN: (lhs, rhs) => lhs * rhs,
  326. inv: (num) => invert(num, ORDER),
  327. sqrt: redef.sqrt || ((n) => sqrtP(f, n)),
  328. invertBatch: (lst) => FpInvertBatch(f, lst),
  329. // TODO: do we really need constant cmov?
  330. // We don't have const-time bigints anyway, so probably will be not very useful
  331. cmov: (a, b, c) => (c ? b : a),
  332. toBytes: (num) => (isLE ? numberToBytesLE(num, BYTES) : numberToBytesBE(num, BYTES)),
  333. fromBytes: (bytes) => {
  334. if (bytes.length !== BYTES)
  335. throw new Error(`Fp.fromBytes: expected ${BYTES}, got ${bytes.length}`);
  336. return isLE ? bytesToNumberLE(bytes) : bytesToNumberBE(bytes);
  337. },
  338. });
  339. return Object.freeze(f);
  340. }
  341. export function FpSqrtOdd(Fp, elm) {
  342. if (!Fp.isOdd)
  343. throw new Error(`Field doesn't have isOdd`);
  344. const root = Fp.sqrt(elm);
  345. return Fp.isOdd(root) ? root : Fp.neg(root);
  346. }
  347. export function FpSqrtEven(Fp, elm) {
  348. if (!Fp.isOdd)
  349. throw new Error(`Field doesn't have isOdd`);
  350. const root = Fp.sqrt(elm);
  351. return Fp.isOdd(root) ? Fp.neg(root) : root;
  352. }
  353. /**
  354. * "Constant-time" private key generation utility.
  355. * Same as mapKeyToField, but accepts less bytes (40 instead of 48 for 32-byte field).
  356. * Which makes it slightly more biased, less secure.
  357. * @deprecated use mapKeyToField instead
  358. */
  359. export function hashToPrivateScalar(hash, groupOrder, isLE = false) {
  360. hash = ensureBytes('privateHash', hash);
  361. const hashLen = hash.length;
  362. const minLen = nLength(groupOrder).nByteLength + 8;
  363. if (minLen < 24 || hashLen < minLen || hashLen > 1024)
  364. throw new Error(`hashToPrivateScalar: expected ${minLen}-1024 bytes of input, got ${hashLen}`);
  365. const num = isLE ? bytesToNumberLE(hash) : bytesToNumberBE(hash);
  366. return mod(num, groupOrder - _1n) + _1n;
  367. }
  368. /**
  369. * Returns total number of bytes consumed by the field element.
  370. * For example, 32 bytes for usual 256-bit weierstrass curve.
  371. * @param fieldOrder number of field elements, usually CURVE.n
  372. * @returns byte length of field
  373. */
  374. export function getFieldBytesLength(fieldOrder) {
  375. if (typeof fieldOrder !== 'bigint')
  376. throw new Error('field order must be bigint');
  377. const bitLength = fieldOrder.toString(2).length;
  378. return Math.ceil(bitLength / 8);
  379. }
  380. /**
  381. * Returns minimal amount of bytes that can be safely reduced
  382. * by field order.
  383. * Should be 2^-128 for 128-bit curve such as P256.
  384. * @param fieldOrder number of field elements, usually CURVE.n
  385. * @returns byte length of target hash
  386. */
  387. export function getMinHashLength(fieldOrder) {
  388. const length = getFieldBytesLength(fieldOrder);
  389. return length + Math.ceil(length / 2);
  390. }
  391. /**
  392. * "Constant-time" private key generation utility.
  393. * Can take (n + n/2) or more bytes of uniform input e.g. from CSPRNG or KDF
  394. * and convert them into private scalar, with the modulo bias being negligible.
  395. * Needs at least 48 bytes of input for 32-byte private key.
  396. * https://research.kudelskisecurity.com/2020/07/28/the-definitive-guide-to-modulo-bias-and-how-to-avoid-it/
  397. * FIPS 186-5, A.2 https://csrc.nist.gov/publications/detail/fips/186/5/final
  398. * RFC 9380, https://www.rfc-editor.org/rfc/rfc9380#section-5
  399. * @param hash hash output from SHA3 or a similar function
  400. * @param groupOrder size of subgroup - (e.g. secp256k1.CURVE.n)
  401. * @param isLE interpret hash bytes as LE num
  402. * @returns valid private scalar
  403. */
  404. export function mapHashToField(key, fieldOrder, isLE = false) {
  405. const len = key.length;
  406. const fieldLen = getFieldBytesLength(fieldOrder);
  407. const minLen = getMinHashLength(fieldOrder);
  408. // No small numbers: need to understand bias story. No huge numbers: easier to detect JS timings.
  409. if (len < 16 || len < minLen || len > 1024)
  410. throw new Error(`expected ${minLen}-1024 bytes of input, got ${len}`);
  411. const num = isLE ? bytesToNumberBE(key) : bytesToNumberLE(key);
  412. // `mod(x, 11)` can sometimes produce 0. `mod(x, 10) + 1` is the same, but no 0
  413. const reduced = mod(num, fieldOrder - _1n) + _1n;
  414. return isLE ? numberToBytesLE(reduced, fieldLen) : numberToBytesBE(reduced, fieldLen);
  415. }
  416. //# sourceMappingURL=modular.js.map