modular.js 17 KB

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