You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

8125 lines
248 KiB

5 years ago
  1. (function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
  2. module.exports.buildF1 = require("./src/f1.js");
  3. module.exports.buildBn128 = require("./src/bn128.js");
  4. module.exports.buildGroth16 = require("./src/groth16.js");
  5. },{"./src/bn128.js":3,"./src/f1.js":15,"./src/groth16.js":16}],2:[function(require,module,exports){
  6. var bigInt = (function (undefined) {
  7. "use strict";
  8. var BASE = 1e7,
  9. LOG_BASE = 7,
  10. MAX_INT = 9007199254740992,
  11. MAX_INT_ARR = smallToArray(MAX_INT),
  12. DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
  13. var supportsNativeBigInt = typeof BigInt === "function";
  14. function Integer(v, radix, alphabet, caseSensitive) {
  15. if (typeof v === "undefined") return Integer[0];
  16. if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);
  17. return parseValue(v);
  18. }
  19. function BigInteger(value, sign) {
  20. this.value = value;
  21. this.sign = sign;
  22. this.isSmall = false;
  23. }
  24. BigInteger.prototype = Object.create(Integer.prototype);
  25. function SmallInteger(value) {
  26. this.value = value;
  27. this.sign = value < 0;
  28. this.isSmall = true;
  29. }
  30. SmallInteger.prototype = Object.create(Integer.prototype);
  31. function NativeBigInt(value) {
  32. this.value = value;
  33. }
  34. NativeBigInt.prototype = Object.create(Integer.prototype);
  35. function isPrecise(n) {
  36. return -MAX_INT < n && n < MAX_INT;
  37. }
  38. function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
  39. if (n < 1e7)
  40. return [n];
  41. if (n < 1e14)
  42. return [n % 1e7, Math.floor(n / 1e7)];
  43. return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
  44. }
  45. function arrayToSmall(arr) { // If BASE changes this function may need to change
  46. trim(arr);
  47. var length = arr.length;
  48. if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
  49. switch (length) {
  50. case 0: return 0;
  51. case 1: return arr[0];
  52. case 2: return arr[0] + arr[1] * BASE;
  53. default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
  54. }
  55. }
  56. return arr;
  57. }
  58. function trim(v) {
  59. var i = v.length;
  60. while (v[--i] === 0);
  61. v.length = i + 1;
  62. }
  63. function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
  64. var x = new Array(length);
  65. var i = -1;
  66. while (++i < length) {
  67. x[i] = 0;
  68. }
  69. return x;
  70. }
  71. function truncate(n) {
  72. if (n > 0) return Math.floor(n);
  73. return Math.ceil(n);
  74. }
  75. function add(a, b) { // assumes a and b are arrays with a.length >= b.length
  76. var l_a = a.length,
  77. l_b = b.length,
  78. r = new Array(l_a),
  79. carry = 0,
  80. base = BASE,
  81. sum, i;
  82. for (i = 0; i < l_b; i++) {
  83. sum = a[i] + b[i] + carry;
  84. carry = sum >= base ? 1 : 0;
  85. r[i] = sum - carry * base;
  86. }
  87. while (i < l_a) {
  88. sum = a[i] + carry;
  89. carry = sum === base ? 1 : 0;
  90. r[i++] = sum - carry * base;
  91. }
  92. if (carry > 0) r.push(carry);
  93. return r;
  94. }
  95. function addAny(a, b) {
  96. if (a.length >= b.length) return add(a, b);
  97. return add(b, a);
  98. }
  99. function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
  100. var l = a.length,
  101. r = new Array(l),
  102. base = BASE,
  103. sum, i;
  104. for (i = 0; i < l; i++) {
  105. sum = a[i] - base + carry;
  106. carry = Math.floor(sum / base);
  107. r[i] = sum - carry * base;
  108. carry += 1;
  109. }
  110. while (carry > 0) {
  111. r[i++] = carry % base;
  112. carry = Math.floor(carry / base);
  113. }
  114. return r;
  115. }
  116. BigInteger.prototype.add = function (v) {
  117. var n = parseValue(v);
  118. if (this.sign !== n.sign) {
  119. return this.subtract(n.negate());
  120. }
  121. var a = this.value, b = n.value;
  122. if (n.isSmall) {
  123. return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
  124. }
  125. return new BigInteger(addAny(a, b), this.sign);
  126. };
  127. BigInteger.prototype.plus = BigInteger.prototype.add;
  128. SmallInteger.prototype.add = function (v) {
  129. var n = parseValue(v);
  130. var a = this.value;
  131. if (a < 0 !== n.sign) {
  132. return this.subtract(n.negate());
  133. }
  134. var b = n.value;
  135. if (n.isSmall) {
  136. if (isPrecise(a + b)) return new SmallInteger(a + b);
  137. b = smallToArray(Math.abs(b));
  138. }
  139. return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
  140. };
  141. SmallInteger.prototype.plus = SmallInteger.prototype.add;
  142. NativeBigInt.prototype.add = function (v) {
  143. return new NativeBigInt(this.value + parseValue(v).value);
  144. }
  145. NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
  146. function subtract(a, b) { // assumes a and b are arrays with a >= b
  147. var a_l = a.length,
  148. b_l = b.length,
  149. r = new Array(a_l),
  150. borrow = 0,
  151. base = BASE,
  152. i, difference;
  153. for (i = 0; i < b_l; i++) {
  154. difference = a[i] - borrow - b[i];
  155. if (difference < 0) {
  156. difference += base;
  157. borrow = 1;
  158. } else borrow = 0;
  159. r[i] = difference;
  160. }
  161. for (i = b_l; i < a_l; i++) {
  162. difference = a[i] - borrow;
  163. if (difference < 0) difference += base;
  164. else {
  165. r[i++] = difference;
  166. break;
  167. }
  168. r[i] = difference;
  169. }
  170. for (; i < a_l; i++) {
  171. r[i] = a[i];
  172. }
  173. trim(r);
  174. return r;
  175. }
  176. function subtractAny(a, b, sign) {
  177. var value;
  178. if (compareAbs(a, b) >= 0) {
  179. value = subtract(a, b);
  180. } else {
  181. value = subtract(b, a);
  182. sign = !sign;
  183. }
  184. value = arrayToSmall(value);
  185. if (typeof value === "number") {
  186. if (sign) value = -value;
  187. return new SmallInteger(value);
  188. }
  189. return new BigInteger(value, sign);
  190. }
  191. function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
  192. var l = a.length,
  193. r = new Array(l),
  194. carry = -b,
  195. base = BASE,
  196. i, difference;
  197. for (i = 0; i < l; i++) {
  198. difference = a[i] + carry;
  199. carry = Math.floor(difference / base);
  200. difference %= base;
  201. r[i] = difference < 0 ? difference + base : difference;
  202. }
  203. r = arrayToSmall(r);
  204. if (typeof r === "number") {
  205. if (sign) r = -r;
  206. return new SmallInteger(r);
  207. } return new BigInteger(r, sign);
  208. }
  209. BigInteger.prototype.subtract = function (v) {
  210. var n = parseValue(v);
  211. if (this.sign !== n.sign) {
  212. return this.add(n.negate());
  213. }
  214. var a = this.value, b = n.value;
  215. if (n.isSmall)
  216. return subtractSmall(a, Math.abs(b), this.sign);
  217. return subtractAny(a, b, this.sign);
  218. };
  219. BigInteger.prototype.minus = BigInteger.prototype.subtract;
  220. SmallInteger.prototype.subtract = function (v) {
  221. var n = parseValue(v);
  222. var a = this.value;
  223. if (a < 0 !== n.sign) {
  224. return this.add(n.negate());
  225. }
  226. var b = n.value;
  227. if (n.isSmall) {
  228. return new SmallInteger(a - b);
  229. }
  230. return subtractSmall(b, Math.abs(a), a >= 0);
  231. };
  232. SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
  233. NativeBigInt.prototype.subtract = function (v) {
  234. return new NativeBigInt(this.value - parseValue(v).value);
  235. }
  236. NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
  237. BigInteger.prototype.negate = function () {
  238. return new BigInteger(this.value, !this.sign);
  239. };
  240. SmallInteger.prototype.negate = function () {
  241. var sign = this.sign;
  242. var small = new SmallInteger(-this.value);
  243. small.sign = !sign;
  244. return small;
  245. };
  246. NativeBigInt.prototype.negate = function () {
  247. return new NativeBigInt(-this.value);
  248. }
  249. BigInteger.prototype.abs = function () {
  250. return new BigInteger(this.value, false);
  251. };
  252. SmallInteger.prototype.abs = function () {
  253. return new SmallInteger(Math.abs(this.value));
  254. };
  255. NativeBigInt.prototype.abs = function () {
  256. return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
  257. }
  258. function multiplyLong(a, b) {
  259. var a_l = a.length,
  260. b_l = b.length,
  261. l = a_l + b_l,
  262. r = createArray(l),
  263. base = BASE,
  264. product, carry, i, a_i, b_j;
  265. for (i = 0; i < a_l; ++i) {
  266. a_i = a[i];
  267. for (var j = 0; j < b_l; ++j) {
  268. b_j = b[j];
  269. product = a_i * b_j + r[i + j];
  270. carry = Math.floor(product / base);
  271. r[i + j] = product - carry * base;
  272. r[i + j + 1] += carry;
  273. }
  274. }
  275. trim(r);
  276. return r;
  277. }
  278. function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
  279. var l = a.length,
  280. r = new Array(l),
  281. base = BASE,
  282. carry = 0,
  283. product, i;
  284. for (i = 0; i < l; i++) {
  285. product = a[i] * b + carry;
  286. carry = Math.floor(product / base);
  287. r[i] = product - carry * base;
  288. }
  289. while (carry > 0) {
  290. r[i++] = carry % base;
  291. carry = Math.floor(carry / base);
  292. }
  293. return r;
  294. }
  295. function shiftLeft(x, n) {
  296. var r = [];
  297. while (n-- > 0) r.push(0);
  298. return r.concat(x);
  299. }
  300. function multiplyKaratsuba(x, y) {
  301. var n = Math.max(x.length, y.length);
  302. if (n <= 30) return multiplyLong(x, y);
  303. n = Math.ceil(n / 2);
  304. var b = x.slice(n),
  305. a = x.slice(0, n),
  306. d = y.slice(n),
  307. c = y.slice(0, n);
  308. var ac = multiplyKaratsuba(a, c),
  309. bd = multiplyKaratsuba(b, d),
  310. abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
  311. var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
  312. trim(product);
  313. return product;
  314. }
  315. // The following function is derived from a surface fit of a graph plotting the performance difference
  316. // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
  317. function useKaratsuba(l1, l2) {
  318. return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
  319. }
  320. BigInteger.prototype.multiply = function (v) {
  321. var n = parseValue(v),
  322. a = this.value, b = n.value,
  323. sign = this.sign !== n.sign,
  324. abs;
  325. if (n.isSmall) {
  326. if (b === 0) return Integer[0];
  327. if (b === 1) return this;
  328. if (b === -1) return this.negate();
  329. abs = Math.abs(b);
  330. if (abs < BASE) {
  331. return new BigInteger(multiplySmall(a, abs), sign);
  332. }
  333. b = smallToArray(abs);
  334. }
  335. if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
  336. return new BigInteger(multiplyKaratsuba(a, b), sign);
  337. return new BigInteger(multiplyLong(a, b), sign);
  338. };
  339. BigInteger.prototype.times = BigInteger.prototype.multiply;
  340. function multiplySmallAndArray(a, b, sign) { // a >= 0
  341. if (a < BASE) {
  342. return new BigInteger(multiplySmall(b, a), sign);
  343. }
  344. return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
  345. }
  346. SmallInteger.prototype._multiplyBySmall = function (a) {
  347. if (isPrecise(a.value * this.value)) {
  348. return new SmallInteger(a.value * this.value);
  349. }
  350. return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
  351. };
  352. BigInteger.prototype._multiplyBySmall = function (a) {
  353. if (a.value === 0) return Integer[0];
  354. if (a.value === 1) return this;
  355. if (a.value === -1) return this.negate();
  356. return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
  357. };
  358. SmallInteger.prototype.multiply = function (v) {
  359. return parseValue(v)._multiplyBySmall(this);
  360. };
  361. SmallInteger.prototype.times = SmallInteger.prototype.multiply;
  362. NativeBigInt.prototype.multiply = function (v) {
  363. return new NativeBigInt(this.value * parseValue(v).value);
  364. }
  365. NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
  366. function square(a) {
  367. //console.assert(2 * BASE * BASE < MAX_INT);
  368. var l = a.length,
  369. r = createArray(l + l),
  370. base = BASE,
  371. product, carry, i, a_i, a_j;
  372. for (i = 0; i < l; i++) {
  373. a_i = a[i];
  374. carry = 0 - a_i * a_i;
  375. for (var j = i; j < l; j++) {
  376. a_j = a[j];
  377. product = 2 * (a_i * a_j) + r[i + j] + carry;
  378. carry = Math.floor(product / base);
  379. r[i + j] = product - carry * base;
  380. }
  381. r[i + l] = carry;
  382. }
  383. trim(r);
  384. return r;
  385. }
  386. BigInteger.prototype.square = function () {
  387. return new BigInteger(square(this.value), false);
  388. };
  389. SmallInteger.prototype.square = function () {
  390. var value = this.value * this.value;
  391. if (isPrecise(value)) return new SmallInteger(value);
  392. return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
  393. };
  394. NativeBigInt.prototype.square = function (v) {
  395. return new NativeBigInt(this.value * this.value);
  396. }
  397. function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
  398. var a_l = a.length,
  399. b_l = b.length,
  400. base = BASE,
  401. result = createArray(b.length),
  402. divisorMostSignificantDigit = b[b_l - 1],
  403. // normalization
  404. lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
  405. remainder = multiplySmall(a, lambda),
  406. divisor = multiplySmall(b, lambda),
  407. quotientDigit, shift, carry, borrow, i, l, q;
  408. if (remainder.length <= a_l) remainder.push(0);
  409. divisor.push(0);
  410. divisorMostSignificantDigit = divisor[b_l - 1];
  411. for (shift = a_l - b_l; shift >= 0; shift--) {
  412. quotientDigit = base - 1;
  413. if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
  414. quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
  415. }
  416. // quotientDigit <= base - 1
  417. carry = 0;
  418. borrow = 0;
  419. l = divisor.length;
  420. for (i = 0; i < l; i++) {
  421. carry += quotientDigit * divisor[i];
  422. q = Math.floor(carry / base);
  423. borrow += remainder[shift + i] - (carry - q * base);
  424. carry = q;
  425. if (borrow < 0) {
  426. remainder[shift + i] = borrow + base;
  427. borrow = -1;
  428. } else {
  429. remainder[shift + i] = borrow;
  430. borrow = 0;
  431. }
  432. }
  433. while (borrow !== 0) {
  434. quotientDigit -= 1;
  435. carry = 0;
  436. for (i = 0; i < l; i++) {
  437. carry += remainder[shift + i] - base + divisor[i];
  438. if (carry < 0) {
  439. remainder[shift + i] = carry + base;
  440. carry = 0;
  441. } else {
  442. remainder[shift + i] = carry;
  443. carry = 1;
  444. }
  445. }
  446. borrow += carry;
  447. }
  448. result[shift] = quotientDigit;
  449. }
  450. // denormalization
  451. remainder = divModSmall(remainder, lambda)[0];
  452. return [arrayToSmall(result), arrayToSmall(remainder)];
  453. }
  454. function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
  455. // Performs faster than divMod1 on larger input sizes.
  456. var a_l = a.length,
  457. b_l = b.length,
  458. result = [],
  459. part = [],
  460. base = BASE,
  461. guess, xlen, highx, highy, check;
  462. while (a_l) {
  463. part.unshift(a[--a_l]);
  464. trim(part);
  465. if (compareAbs(part, b) < 0) {
  466. result.push(0);
  467. continue;
  468. }
  469. xlen = part.length;
  470. highx = part[xlen - 1] * base + part[xlen - 2];
  471. highy = b[b_l - 1] * base + b[b_l - 2];
  472. if (xlen > b_l) {
  473. highx = (highx + 1) * base;
  474. }
  475. guess = Math.ceil(highx / highy);
  476. do {
  477. check = multiplySmall(b, guess);
  478. if (compareAbs(check, part) <= 0) break;
  479. guess--;
  480. } while (guess);
  481. result.push(guess);
  482. part = subtract(part, check);
  483. }
  484. result.reverse();
  485. return [arrayToSmall(result), arrayToSmall(part)];
  486. }
  487. function divModSmall(value, lambda) {
  488. var length = value.length,
  489. quotient = createArray(length),
  490. base = BASE,
  491. i, q, remainder, divisor;
  492. remainder = 0;
  493. for (i = length - 1; i >= 0; --i) {
  494. divisor = remainder * base + value[i];
  495. q = truncate(divisor / lambda);
  496. remainder = divisor - q * lambda;
  497. quotient[i] = q | 0;
  498. }
  499. return [quotient, remainder | 0];
  500. }
  501. function divModAny(self, v) {
  502. var value, n = parseValue(v);
  503. if (supportsNativeBigInt) {
  504. return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];
  505. }
  506. var a = self.value, b = n.value;
  507. var quotient;
  508. if (b === 0) throw new Error("Cannot divide by zero");
  509. if (self.isSmall) {
  510. if (n.isSmall) {
  511. return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
  512. }
  513. return [Integer[0], self];
  514. }
  515. if (n.isSmall) {
  516. if (b === 1) return [self, Integer[0]];
  517. if (b == -1) return [self.negate(), Integer[0]];
  518. var abs = Math.abs(b);
  519. if (abs < BASE) {
  520. value = divModSmall(a, abs);
  521. quotient = arrayToSmall(value[0]);
  522. var remainder = value[1];
  523. if (self.sign) remainder = -remainder;
  524. if (typeof quotient === "number") {
  525. if (self.sign !== n.sign) quotient = -quotient;
  526. return [new SmallInteger(quotient), new SmallInteger(remainder)];
  527. }
  528. return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
  529. }
  530. b = smallToArray(abs);
  531. }
  532. var comparison = compareAbs(a, b);
  533. if (comparison === -1) return [Integer[0], self];
  534. if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
  535. // divMod1 is faster on smaller input sizes
  536. if (a.length + b.length <= 200)
  537. value = divMod1(a, b);
  538. else value = divMod2(a, b);
  539. quotient = value[0];
  540. var qSign = self.sign !== n.sign,
  541. mod = value[1],
  542. mSign = self.sign;
  543. if (typeof quotient === "number") {
  544. if (qSign) quotient = -quotient;
  545. quotient = new SmallInteger(quotient);
  546. } else quotient = new BigInteger(quotient, qSign);
  547. if (typeof mod === "number") {
  548. if (mSign) mod = -mod;
  549. mod = new SmallInteger(mod);
  550. } else mod = new BigInteger(mod, mSign);
  551. return [quotient, mod];
  552. }
  553. BigInteger.prototype.divmod = function (v) {
  554. var result = divModAny(this, v);
  555. return {
  556. quotient: result[0],
  557. remainder: result[1]
  558. };
  559. };
  560. NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
  561. BigInteger.prototype.divide = function (v) {
  562. return divModAny(this, v)[0];
  563. };
  564. NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {
  565. return new NativeBigInt(this.value / parseValue(v).value);
  566. };
  567. SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
  568. BigInteger.prototype.mod = function (v) {
  569. return divModAny(this, v)[1];
  570. };
  571. NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {
  572. return new NativeBigInt(this.value % parseValue(v).value);
  573. };
  574. SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
  575. BigInteger.prototype.pow = function (v) {
  576. var n = parseValue(v),
  577. a = this.value,
  578. b = n.value,
  579. value, x, y;
  580. if (b === 0) return Integer[1];
  581. if (a === 0) return Integer[0];
  582. if (a === 1) return Integer[1];
  583. if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
  584. if (n.sign) {
  585. return Integer[0];
  586. }
  587. if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
  588. if (this.isSmall) {
  589. if (isPrecise(value = Math.pow(a, b)))
  590. return new SmallInteger(truncate(value));
  591. }
  592. x = this;
  593. y = Integer[1];
  594. while (true) {
  595. if (b & 1 === 1) {
  596. y = y.times(x);
  597. --b;
  598. }
  599. if (b === 0) break;
  600. b /= 2;
  601. x = x.square();
  602. }
  603. return y;
  604. };
  605. SmallInteger.prototype.pow = BigInteger.prototype.pow;
  606. NativeBigInt.prototype.pow = function (v) {
  607. var n = parseValue(v);
  608. var a = this.value, b = n.value;
  609. var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
  610. if (b === _0) return Integer[1];
  611. if (a === _0) return Integer[0];
  612. if (a === _1) return Integer[1];
  613. if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];
  614. if (n.isNegative()) return new NativeBigInt(_0);
  615. var x = this;
  616. var y = Integer[1];
  617. while (true) {
  618. if ((b & _1) === _1) {
  619. y = y.times(x);
  620. --b;
  621. }
  622. if (b === _0) break;
  623. b /= _2;
  624. x = x.square();
  625. }
  626. return y;
  627. }
  628. BigInteger.prototype.modPow = function (exp, mod) {
  629. exp = parseValue(exp);
  630. mod = parseValue(mod);
  631. if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
  632. var r = Integer[1],
  633. base = this.mod(mod);
  634. while (exp.isPositive()) {
  635. if (base.isZero()) return Integer[0];
  636. if (exp.isOdd()) r = r.multiply(base).mod(mod);
  637. exp = exp.divide(2);
  638. base = base.square().mod(mod);
  639. }
  640. return r;
  641. };
  642. NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
  643. function compareAbs(a, b) {
  644. if (a.length !== b.length) {
  645. return a.length > b.length ? 1 : -1;
  646. }
  647. for (var i = a.length - 1; i >= 0; i--) {
  648. if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
  649. }
  650. return 0;
  651. }
  652. BigInteger.prototype.compareAbs = function (v) {
  653. var n = parseValue(v),
  654. a = this.value,
  655. b = n.value;
  656. if (n.isSmall) return 1;
  657. return compareAbs(a, b);
  658. };
  659. SmallInteger.prototype.compareAbs = function (v) {
  660. var n = parseValue(v),
  661. a = Math.abs(this.value),
  662. b = n.value;
  663. if (n.isSmall) {
  664. b = Math.abs(b);
  665. return a === b ? 0 : a > b ? 1 : -1;
  666. }
  667. return -1;
  668. };
  669. NativeBigInt.prototype.compareAbs = function (v) {
  670. var a = this.value;
  671. var b = parseValue(v).value;
  672. a = a >= 0 ? a : -a;
  673. b = b >= 0 ? b : -b;
  674. return a === b ? 0 : a > b ? 1 : -1;
  675. }
  676. BigInteger.prototype.compare = function (v) {
  677. // See discussion about comparison with Infinity:
  678. // https://github.com/peterolson/BigInteger.js/issues/61
  679. if (v === Infinity) {
  680. return -1;
  681. }
  682. if (v === -Infinity) {
  683. return 1;
  684. }
  685. var n = parseValue(v),
  686. a = this.value,
  687. b = n.value;
  688. if (this.sign !== n.sign) {
  689. return n.sign ? 1 : -1;
  690. }
  691. if (n.isSmall) {
  692. return this.sign ? -1 : 1;
  693. }
  694. return compareAbs(a, b) * (this.sign ? -1 : 1);
  695. };
  696. BigInteger.prototype.compareTo = BigInteger.prototype.compare;
  697. SmallInteger.prototype.compare = function (v) {
  698. if (v === Infinity) {
  699. return -1;
  700. }
  701. if (v === -Infinity) {
  702. return 1;
  703. }
  704. var n = parseValue(v),
  705. a = this.value,
  706. b = n.value;
  707. if (n.isSmall) {
  708. return a == b ? 0 : a > b ? 1 : -1;
  709. }
  710. if (a < 0 !== n.sign) {
  711. return a < 0 ? -1 : 1;
  712. }
  713. return a < 0 ? 1 : -1;
  714. };
  715. SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
  716. NativeBigInt.prototype.compare = function (v) {
  717. if (v === Infinity) {
  718. return -1;
  719. }
  720. if (v === -Infinity) {
  721. return 1;
  722. }
  723. var a = this.value;
  724. var b = parseValue(v).value;
  725. return a === b ? 0 : a > b ? 1 : -1;
  726. }
  727. NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
  728. BigInteger.prototype.equals = function (v) {
  729. return this.compare(v) === 0;
  730. };
  731. NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
  732. BigInteger.prototype.notEquals = function (v) {
  733. return this.compare(v) !== 0;
  734. };
  735. NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
  736. BigInteger.prototype.greater = function (v) {
  737. return this.compare(v) > 0;
  738. };
  739. NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
  740. BigInteger.prototype.lesser = function (v) {
  741. return this.compare(v) < 0;
  742. };
  743. NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
  744. BigInteger.prototype.greaterOrEquals = function (v) {
  745. return this.compare(v) >= 0;
  746. };
  747. NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
  748. BigInteger.prototype.lesserOrEquals = function (v) {
  749. return this.compare(v) <= 0;
  750. };
  751. NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
  752. BigInteger.prototype.isEven = function () {
  753. return (this.value[0] & 1) === 0;
  754. };
  755. SmallInteger.prototype.isEven = function () {
  756. return (this.value & 1) === 0;
  757. };
  758. NativeBigInt.prototype.isEven = function () {
  759. return (this.value & BigInt(1)) === BigInt(0);
  760. }
  761. BigInteger.prototype.isOdd = function () {
  762. return (this.value[0] & 1) === 1;
  763. };
  764. SmallInteger.prototype.isOdd = function () {
  765. return (this.value & 1) === 1;
  766. };
  767. NativeBigInt.prototype.isOdd = function () {
  768. return (this.value & BigInt(1)) === BigInt(1);
  769. }
  770. BigInteger.prototype.isPositive = function () {
  771. return !this.sign;
  772. };
  773. SmallInteger.prototype.isPositive = function () {
  774. return this.value > 0;
  775. };
  776. NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
  777. BigInteger.prototype.isNegative = function () {
  778. return this.sign;
  779. };
  780. SmallInteger.prototype.isNegative = function () {
  781. return this.value < 0;
  782. };
  783. NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
  784. BigInteger.prototype.isUnit = function () {
  785. return false;
  786. };
  787. SmallInteger.prototype.isUnit = function () {
  788. return Math.abs(this.value) === 1;
  789. };
  790. NativeBigInt.prototype.isUnit = function () {
  791. return this.abs().value === BigInt(1);
  792. }
  793. BigInteger.prototype.isZero = function () {
  794. return false;
  795. };
  796. SmallInteger.prototype.isZero = function () {
  797. return this.value === 0;
  798. };
  799. NativeBigInt.prototype.isZero = function () {
  800. return this.value === BigInt(0);
  801. }
  802. BigInteger.prototype.isDivisibleBy = function (v) {
  803. var n = parseValue(v);
  804. if (n.isZero()) return false;
  805. if (n.isUnit()) return true;
  806. if (n.compareAbs(2) === 0) return this.isEven();
  807. return this.mod(n).isZero();
  808. };
  809. NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
  810. function isBasicPrime(v) {
  811. var n = v.abs();
  812. if (n.isUnit()) return false;
  813. if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
  814. if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
  815. if (n.lesser(49)) return true;
  816. // we don't know if it's prime: let the other functions figure it out
  817. }
  818. function millerRabinTest(n, a) {
  819. var nPrev = n.prev(),
  820. b = nPrev,
  821. r = 0,
  822. d, t, i, x;
  823. while (b.isEven()) b = b.divide(2), r++;
  824. next: for (i = 0; i < a.length; i++) {
  825. if (n.lesser(a[i])) continue;
  826. x = bigInt(a[i]).modPow(b, n);
  827. if (x.isUnit() || x.equals(nPrev)) continue;
  828. for (d = r - 1; d != 0; d--) {
  829. x = x.square().mod(n);
  830. if (x.isUnit()) return false;
  831. if (x.equals(nPrev)) continue next;
  832. }
  833. return false;
  834. }
  835. return true;
  836. }
  837. // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
  838. BigInteger.prototype.isPrime = function (strict) {
  839. var isPrime = isBasicPrime(this);
  840. if (isPrime !== undefined) return isPrime;
  841. var n = this.abs();
  842. var bits = n.bitLength();
  843. if (bits <= 64)
  844. return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
  845. var logN = Math.log(2) * bits.toJSNumber();
  846. var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
  847. for (var a = [], i = 0; i < t; i++) {
  848. a.push(bigInt(i + 2));
  849. }
  850. return millerRabinTest(n, a);
  851. };
  852. NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
  853. BigInteger.prototype.isProbablePrime = function (iterations) {
  854. var isPrime = isBasicPrime(this);
  855. if (isPrime !== undefined) return isPrime;
  856. var n = this.abs();
  857. var t = iterations === undefined ? 5 : iterations;
  858. for (var a = [], i = 0; i < t; i++) {
  859. a.push(bigInt.randBetween(2, n.minus(2)));
  860. }
  861. return millerRabinTest(n, a);
  862. };
  863. NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
  864. BigInteger.prototype.modInv = function (n) {
  865. var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
  866. while (!newR.isZero()) {
  867. q = r.divide(newR);
  868. lastT = t;
  869. lastR = r;
  870. t = newT;
  871. r = newR;
  872. newT = lastT.subtract(q.multiply(newT));
  873. newR = lastR.subtract(q.multiply(newR));
  874. }
  875. if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
  876. if (t.compare(0) === -1) {
  877. t = t.add(n);
  878. }
  879. if (this.isNegative()) {
  880. return t.negate();
  881. }
  882. return t;
  883. };
  884. NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
  885. BigInteger.prototype.next = function () {
  886. var value = this.value;
  887. if (this.sign) {
  888. return subtractSmall(value, 1, this.sign);
  889. }
  890. return new BigInteger(addSmall(value, 1), this.sign);
  891. };
  892. SmallInteger.prototype.next = function () {
  893. var value = this.value;
  894. if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
  895. return new BigInteger(MAX_INT_ARR, false);
  896. };
  897. NativeBigInt.prototype.next = function () {
  898. return new NativeBigInt(this.value + BigInt(1));
  899. }
  900. BigInteger.prototype.prev = function () {
  901. var value = this.value;
  902. if (this.sign) {
  903. return new BigInteger(addSmall(value, 1), true);
  904. }
  905. return subtractSmall(value, 1, this.sign);
  906. };
  907. SmallInteger.prototype.prev = function () {
  908. var value = this.value;
  909. if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
  910. return new BigInteger(MAX_INT_ARR, true);
  911. };
  912. NativeBigInt.prototype.prev = function () {
  913. return new NativeBigInt(this.value - BigInt(1));
  914. }
  915. var powersOfTwo = [1];
  916. while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
  917. var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
  918. function shift_isSmall(n) {
  919. return Math.abs(n) <= BASE;
  920. }
  921. BigInteger.prototype.shiftLeft = function (v) {
  922. var n = parseValue(v).toJSNumber();
  923. if (!shift_isSmall(n)) {
  924. throw new Error(String(n) + " is too large for shifting.");
  925. }
  926. if (n < 0) return this.shiftRight(-n);
  927. var result = this;
  928. if (result.isZero()) return result;
  929. while (n >= powers2Length) {
  930. result = result.multiply(highestPower2);
  931. n -= powers2Length - 1;
  932. }
  933. return result.multiply(powersOfTwo[n]);
  934. };
  935. NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
  936. BigInteger.prototype.shiftRight = function (v) {
  937. var remQuo;
  938. var n = parseValue(v).toJSNumber();
  939. if (!shift_isSmall(n)) {
  940. throw new Error(String(n) + " is too large for shifting.");
  941. }
  942. if (n < 0) return this.shiftLeft(-n);
  943. var result = this;
  944. while (n >= powers2Length) {
  945. if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
  946. remQuo = divModAny(result, highestPower2);
  947. result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
  948. n -= powers2Length - 1;
  949. }
  950. remQuo = divModAny(result, powersOfTwo[n]);
  951. return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
  952. };
  953. NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
  954. function bitwise(x, y, fn) {
  955. y = parseValue(y);
  956. var xSign = x.isNegative(), ySign = y.isNegative();
  957. var xRem = xSign ? x.not() : x,
  958. yRem = ySign ? y.not() : y;
  959. var xDigit = 0, yDigit = 0;
  960. var xDivMod = null, yDivMod = null;
  961. var result = [];
  962. while (!xRem.isZero() || !yRem.isZero()) {
  963. xDivMod = divModAny(xRem, highestPower2);
  964. xDigit = xDivMod[1].toJSNumber();
  965. if (xSign) {
  966. xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
  967. }
  968. yDivMod = divModAny(yRem, highestPower2);
  969. yDigit = yDivMod[1].toJSNumber();
  970. if (ySign) {
  971. yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
  972. }
  973. xRem = xDivMod[0];
  974. yRem = yDivMod[0];
  975. result.push(fn(xDigit, yDigit));
  976. }
  977. var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
  978. for (var i = result.length - 1; i >= 0; i -= 1) {
  979. sum = sum.multiply(highestPower2).add(bigInt(result[i]));
  980. }
  981. return sum;
  982. }
  983. BigInteger.prototype.not = function () {
  984. return this.negate().prev();
  985. };
  986. NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
  987. BigInteger.prototype.and = function (n) {
  988. return bitwise(this, n, function (a, b) { return a & b; });
  989. };
  990. NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
  991. BigInteger.prototype.or = function (n) {
  992. return bitwise(this, n, function (a, b) { return a | b; });
  993. };
  994. NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
  995. BigInteger.prototype.xor = function (n) {
  996. return bitwise(this, n, function (a, b) { return a ^ b; });
  997. };
  998. NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
  999. var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
  1000. function roughLOB(n) { // get lowestOneBit (rough)
  1001. // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
  1002. // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
  1003. var v = n.value,
  1004. x = typeof v === "number" ? v | LOBMASK_I :
  1005. typeof v === "bigint" ? v | BigInt(LOBMASK_I) :
  1006. v[0] + v[1] * BASE | LOBMASK_BI;
  1007. return x & -x;
  1008. }
  1009. function integerLogarithm(value, base) {
  1010. if (base.compareTo(value) <= 0) {
  1011. var tmp = integerLogarithm(value, base.square(base));
  1012. var p = tmp.p;
  1013. var e = tmp.e;
  1014. var t = p.multiply(base);
  1015. return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
  1016. }
  1017. return { p: bigInt(1), e: 0 };
  1018. }
  1019. BigInteger.prototype.bitLength = function () {
  1020. var n = this;
  1021. if (n.compareTo(bigInt(0)) < 0) {
  1022. n = n.negate().subtract(bigInt(1));
  1023. }
  1024. if (n.compareTo(bigInt(0)) === 0) {
  1025. return bigInt(0);
  1026. }
  1027. return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
  1028. }
  1029. NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
  1030. function max(a, b) {
  1031. a = parseValue(a);
  1032. b = parseValue(b);
  1033. return a.greater(b) ? a : b;
  1034. }
  1035. function min(a, b) {
  1036. a = parseValue(a);
  1037. b = parseValue(b);
  1038. return a.lesser(b) ? a : b;
  1039. }
  1040. function gcd(a, b) {
  1041. a = parseValue(a).abs();
  1042. b = parseValue(b).abs();
  1043. if (a.equals(b)) return a;
  1044. if (a.isZero()) return b;
  1045. if (b.isZero()) return a;
  1046. var c = Integer[1], d, t;
  1047. while (a.isEven() && b.isEven()) {
  1048. d = min(roughLOB(a), roughLOB(b));
  1049. a = a.divide(d);
  1050. b = b.divide(d);
  1051. c = c.multiply(d);
  1052. }
  1053. while (a.isEven()) {
  1054. a = a.divide(roughLOB(a));
  1055. }
  1056. do {
  1057. while (b.isEven()) {
  1058. b = b.divide(roughLOB(b));
  1059. }
  1060. if (a.greater(b)) {
  1061. t = b; b = a; a = t;
  1062. }
  1063. b = b.subtract(a);
  1064. } while (!b.isZero());
  1065. return c.isUnit() ? a : a.multiply(c);
  1066. }
  1067. function lcm(a, b) {
  1068. a = parseValue(a).abs();
  1069. b = parseValue(b).abs();
  1070. return a.divide(gcd(a, b)).multiply(b);
  1071. }
  1072. function randBetween(a, b) {
  1073. a = parseValue(a);
  1074. b = parseValue(b);
  1075. var low = min(a, b), high = max(a, b);
  1076. var range = high.subtract(low).add(1);
  1077. if (range.isSmall) return low.add(Math.floor(Math.random() * range));
  1078. var digits = toBase(range, BASE).value;
  1079. var result = [], restricted = true;
  1080. for (var i = 0; i < digits.length; i++) {
  1081. var top = restricted ? digits[i] : BASE;
  1082. var digit = truncate(Math.random() * top);
  1083. result.push(digit);
  1084. if (digit < top) restricted = false;
  1085. }
  1086. return low.add(Integer.fromArray(result, BASE, false));
  1087. }
  1088. var parseBase = function (text, base, alphabet, caseSensitive) {
  1089. alphabet = alphabet || DEFAULT_ALPHABET;
  1090. text = String(text);
  1091. if (!caseSensitive) {
  1092. text = text.toLowerCase();
  1093. alphabet = alphabet.toLowerCase();
  1094. }
  1095. var length = text.length;
  1096. var i;
  1097. var absBase = Math.abs(base);
  1098. var alphabetValues = {};
  1099. for (i = 0; i < alphabet.length; i++) {
  1100. alphabetValues[alphabet[i]] = i;
  1101. }
  1102. for (i = 0; i < length; i++) {
  1103. var c = text[i];
  1104. if (c === "-") continue;
  1105. if (c in alphabetValues) {
  1106. if (alphabetValues[c] >= absBase) {
  1107. if (c === "1" && absBase === 1) continue;
  1108. throw new Error(c + " is not a valid digit in base " + base + ".");
  1109. }
  1110. }
  1111. }
  1112. base = parseValue(base);
  1113. var digits = [];
  1114. var isNegative = text[0] === "-";
  1115. for (i = isNegative ? 1 : 0; i < text.length; i++) {
  1116. var c = text[i];
  1117. if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));
  1118. else if (c === "<") {
  1119. var start = i;
  1120. do { i++; } while (text[i] !== ">" && i < text.length);
  1121. digits.push(parseValue(text.slice(start + 1, i)));
  1122. }
  1123. else throw new Error(c + " is not a valid character");
  1124. }
  1125. return parseBaseFromArray(digits, base, isNegative);
  1126. };
  1127. function parseBaseFromArray(digits, base, isNegative) {
  1128. var val = Integer[0], pow = Integer[1], i;
  1129. for (i = digits.length - 1; i >= 0; i--) {
  1130. val = val.add(digits[i].times(pow));
  1131. pow = pow.times(base);
  1132. }
  1133. return isNegative ? val.negate() : val;
  1134. }
  1135. function stringify(digit, alphabet) {
  1136. alphabet = alphabet || DEFAULT_ALPHABET;
  1137. if (digit < alphabet.length) {
  1138. return alphabet[digit];
  1139. }
  1140. return "<" + digit + ">";
  1141. }
  1142. function toBase(n, base) {
  1143. base = bigInt(base);
  1144. if (base.isZero()) {
  1145. if (n.isZero()) return { value: [0], isNegative: false };
  1146. throw new Error("Cannot convert nonzero numbers to base 0.");
  1147. }
  1148. if (base.equals(-1)) {
  1149. if (n.isZero()) return { value: [0], isNegative: false };
  1150. if (n.isNegative())
  1151. return {
  1152. value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))
  1153. .map(Array.prototype.valueOf, [1, 0])
  1154. ),
  1155. isNegative: false
  1156. };
  1157. var arr = Array.apply(null, Array(n.toJSNumber() - 1))
  1158. .map(Array.prototype.valueOf, [0, 1]);
  1159. arr.unshift([1]);
  1160. return {
  1161. value: [].concat.apply([], arr),
  1162. isNegative: false
  1163. };
  1164. }
  1165. var neg = false;
  1166. if (n.isNegative() && base.isPositive()) {
  1167. neg = true;
  1168. n = n.abs();
  1169. }
  1170. if (base.isUnit()) {
  1171. if (n.isZero()) return { value: [0], isNegative: false };
  1172. return {
  1173. value: Array.apply(null, Array(n.toJSNumber()))
  1174. .map(Number.prototype.valueOf, 1),
  1175. isNegative: neg
  1176. };
  1177. }
  1178. var out = [];
  1179. var left = n, divmod;
  1180. while (left.isNegative() || left.compareAbs(base) >= 0) {
  1181. divmod = left.divmod(base);
  1182. left = divmod.quotient;
  1183. var digit = divmod.remainder;
  1184. if (digit.isNegative()) {
  1185. digit = base.minus(digit).abs();
  1186. left = left.next();
  1187. }
  1188. out.push(digit.toJSNumber());
  1189. }
  1190. out.push(left.toJSNumber());
  1191. return { value: out.reverse(), isNegative: neg };
  1192. }
  1193. function toBaseString(n, base, alphabet) {
  1194. var arr = toBase(n, base);
  1195. return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {
  1196. return stringify(x, alphabet);
  1197. }).join('');
  1198. }
  1199. BigInteger.prototype.toArray = function (radix) {
  1200. return toBase(this, radix);
  1201. };
  1202. SmallInteger.prototype.toArray = function (radix) {
  1203. return toBase(this, radix);
  1204. };
  1205. NativeBigInt.prototype.toArray = function (radix) {
  1206. return toBase(this, radix);
  1207. };
  1208. BigInteger.prototype.toString = function (radix, alphabet) {
  1209. if (radix === undefined) radix = 10;
  1210. if (radix !== 10) return toBaseString(this, radix, alphabet);
  1211. var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
  1212. while (--l >= 0) {
  1213. digit = String(v[l]);
  1214. str += zeros.slice(digit.length) + digit;
  1215. }
  1216. var sign = this.sign ? "-" : "";
  1217. return sign + str;
  1218. };
  1219. SmallInteger.prototype.toString = function (radix, alphabet) {
  1220. if (radix === undefined) radix = 10;
  1221. if (radix != 10) return toBaseString(this, radix, alphabet);
  1222. return String(this.value);
  1223. };
  1224. NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
  1225. NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }
  1226. BigInteger.prototype.valueOf = function () {
  1227. return parseInt(this.toString(), 10);
  1228. };
  1229. BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
  1230. SmallInteger.prototype.valueOf = function () {
  1231. return this.value;
  1232. };
  1233. SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
  1234. NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {
  1235. return parseInt(this.toString(), 10);
  1236. }
  1237. function parseStringValue(v) {
  1238. if (isPrecise(+v)) {
  1239. var x = +v;
  1240. if (x === truncate(x))
  1241. return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
  1242. throw new Error("Invalid integer: " + v);
  1243. }
  1244. var sign = v[0] === "-";
  1245. if (sign) v = v.slice(1);
  1246. var split = v.split(/e/i);
  1247. if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
  1248. if (split.length === 2) {
  1249. var exp = split[1];
  1250. if (exp[0] === "+") exp = exp.slice(1);
  1251. exp = +exp;
  1252. if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
  1253. var text = split[0];
  1254. var decimalPlace = text.indexOf(".");
  1255. if (decimalPlace >= 0) {
  1256. exp -= text.length - decimalPlace - 1;
  1257. text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
  1258. }
  1259. if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
  1260. text += (new Array(exp + 1)).join("0");
  1261. v = text;
  1262. }
  1263. var isValid = /^([0-9][0-9]*)$/.test(v);
  1264. if (!isValid) throw new Error("Invalid integer: " + v);
  1265. if (supportsNativeBigInt) {
  1266. return new NativeBigInt(BigInt(sign ? "-" + v : v));
  1267. }
  1268. var r = [], max = v.length, l = LOG_BASE, min = max - l;
  1269. while (max > 0) {
  1270. r.push(+v.slice(min, max));
  1271. min -= l;
  1272. if (min < 0) min = 0;
  1273. max -= l;
  1274. }
  1275. trim(r);
  1276. return new BigInteger(r, sign);
  1277. }
  1278. function parseNumberValue(v) {
  1279. if (supportsNativeBigInt) {
  1280. return new NativeBigInt(BigInt(v));
  1281. }
  1282. if (isPrecise(v)) {
  1283. if (v !== truncate(v)) throw new Error(v + " is not an integer.");
  1284. return new SmallInteger(v);
  1285. }
  1286. return parseStringValue(v.toString());
  1287. }
  1288. function parseValue(v) {
  1289. if (typeof v === "number") {
  1290. return parseNumberValue(v);
  1291. }
  1292. if (typeof v === "string") {
  1293. return parseStringValue(v);
  1294. }
  1295. if (typeof v === "bigint") {
  1296. return new NativeBigInt(v);
  1297. }
  1298. return v;
  1299. }
  1300. // Pre-define numbers in range [-999,999]
  1301. for (var i = 0; i < 1000; i++) {
  1302. Integer[i] = parseValue(i);
  1303. if (i > 0) Integer[-i] = parseValue(-i);
  1304. }
  1305. // Backwards compatibility
  1306. Integer.one = Integer[1];
  1307. Integer.zero = Integer[0];
  1308. Integer.minusOne = Integer[-1];
  1309. Integer.max = max;
  1310. Integer.min = min;
  1311. Integer.gcd = gcd;
  1312. Integer.lcm = lcm;
  1313. Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };
  1314. Integer.randBetween = randBetween;
  1315. Integer.fromArray = function (digits, base, isNegative) {
  1316. return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
  1317. };
  1318. return Integer;
  1319. })();
  1320. // Node.js check
  1321. if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
  1322. module.exports = bigInt;
  1323. }
  1324. //amd check
  1325. if (typeof define === "function" && define.amd) {
  1326. define("big-integer", [], function () {
  1327. return bigInt;
  1328. });
  1329. }
  1330. },{}],3:[function(require,module,exports){
  1331. /* globals WebAssembly */
  1332. const bigInt = require("big-integer");
  1333. const ModuleBuilder = require("./wasmbuilder/index.js");
  1334. const buildF1m = require("./build_f1m.js");
  1335. const buildF2m = require("./build_f2m.js");
  1336. const buildF1 = require("./build_f1.js");
  1337. const buildCurve = require("./build_curve.js");
  1338. const buildTest = require("./build_testg1");
  1339. const buildFFT = require("./build_fft");
  1340. const buildMultiexp = require("./build_multiexp");
  1341. const buildPol = require("./build_pol");
  1342. const utils = require("./utils");
  1343. async function build() {
  1344. const bn128 = new Bn128();
  1345. bn128.q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583");
  1346. bn128.r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
  1347. bn128.n64 = Math.floor((bn128.q.minus(1).bitLength() - 1)/64) +1;
  1348. bn128.n32 = bn128.n64*2;
  1349. bn128.n8 = bn128.n64*8;
  1350. bn128.memory = new WebAssembly.Memory({initial:10000});
  1351. bn128.i32 = new Uint32Array(bn128.memory.buffer);
  1352. const moduleBuilder = new ModuleBuilder();
  1353. moduleBuilder.setMemory(10000);
  1354. buildF1m(moduleBuilder, bn128.q, "f1m");
  1355. buildF1(moduleBuilder, bn128.r, "fr", "frm");
  1356. buildCurve(moduleBuilder, "g1", "f1m");
  1357. buildMultiexp(moduleBuilder, "g1", "g1", "f1m", "fr");
  1358. buildFFT(moduleBuilder, "fft", "frm");
  1359. buildPol(moduleBuilder, "pol", "frm");
  1360. const pNonResidueF2 = moduleBuilder.alloc(
  1361. utils.bigInt2BytesLE(
  1362. bigInt("15537367993719455909907449462855742678907882278146377936676643359958227611562"), // -1 in montgomery
  1363. bn128.n8
  1364. )
  1365. );
  1366. buildF2m(moduleBuilder, pNonResidueF2, "f2m", "f1m");
  1367. buildCurve(moduleBuilder, "g2", "f2m");
  1368. buildMultiexp(moduleBuilder, "g2", "g2", "f2m", "fr");
  1369. buildTest(moduleBuilder);
  1370. const code = moduleBuilder.build();
  1371. const wasmModule = await WebAssembly.compile(code);
  1372. bn128.instance = await WebAssembly.instantiate(wasmModule, {
  1373. env: {
  1374. "memory": bn128.memory
  1375. }
  1376. });
  1377. bn128.pq = moduleBuilder.modules.f1m.pq;
  1378. bn128.pr = moduleBuilder.modules.frm.pq;
  1379. bn128.pg1 = bn128.g1_allocPoint([bigInt(1), bigInt(2), bigInt(1)]);
  1380. Object.assign(bn128, bn128.instance.exports);
  1381. return bn128;
  1382. }
  1383. class Bn128 {
  1384. constructor() {
  1385. }
  1386. alloc(length) {
  1387. while (this.i32[0] & 3) this.i32[0]++; // Return always aligned pointers
  1388. const res = this.i32[0];
  1389. this.i32[0] += length;
  1390. return res;
  1391. }
  1392. putInt(pos, _a) {
  1393. const a = bigInt(_a);
  1394. if (pos & 0x7) throw new Error("Pointer must be aligned");
  1395. if (a.bitLength > this.n64*64) {
  1396. return this.putInt(a.mod(this.q));
  1397. }
  1398. for (let i=0; i<this.n32; i++) {
  1399. this.i32[(pos>>2)+i] = a.shiftRight(i*32).and(0xFFFFFFFF).toJSNumber();
  1400. }
  1401. }
  1402. getInt(pos) {
  1403. if (pos & 0x7) throw new Error("Pointer must be aligned");
  1404. let acc = bigInt(this.i32[(pos>>2)+this.n32-1]);
  1405. for (let i=this.n32-2; i>=0; i--) {
  1406. acc = acc.shiftLeft(32);
  1407. acc = acc.add(this.i32[(pos>>2)+i]);
  1408. }
  1409. return acc;
  1410. }
  1411. allocInt(_a) {
  1412. const p = this.alloc(this.n8);
  1413. if (_a) this.putInt(p, _a);
  1414. return p;
  1415. }
  1416. putIntF2(pos, a) {
  1417. this.putInt(pos, a[0]);
  1418. this.putInt(pos+this.n8, a[1]);
  1419. }
  1420. getIntF2(pos) {
  1421. const p = Array(2);
  1422. p[0] = this.getInt(pos);
  1423. p[1] = this.getInt(pos+this.n8);
  1424. return p;
  1425. }
  1426. allocIntF2(a) {
  1427. const pP = this.alloc(this.n8*2);
  1428. if (a) {
  1429. this.putIntF2(pP, a);
  1430. }
  1431. return pP;
  1432. }
  1433. g1_putPoint(pos, p) {
  1434. this.putInt(pos, p[0]);
  1435. this.putInt(pos+this.n8, p[1]);
  1436. if (p.length == 3) {
  1437. this.putInt(pos+this.n8*2, p[2]);
  1438. } else {
  1439. this.putInt(pos+this.n8*2, 1);
  1440. }
  1441. }
  1442. g1_getPoint(pos) {
  1443. const p = Array(3);
  1444. p[0] = this.getInt(pos);
  1445. p[1] = this.getInt(pos+this.n8);
  1446. p[2] = this.getInt(pos+this.n8*2);
  1447. return p;
  1448. }
  1449. g1_allocPoint(p) {
  1450. const pP = this.alloc(this.n8*3);
  1451. if (p) {
  1452. this.g1_putPoint(pP, p);
  1453. }
  1454. return pP;
  1455. }
  1456. g2_putPoint(pos, p) {
  1457. this.putIntF2(pos, p[0]);
  1458. this.putIntF2(pos+this.n8*2, p[1]);
  1459. if (p.length == 3) {
  1460. this.putIntF2(pos+this.n8*4, p[2]);
  1461. } else {
  1462. this.putIntF2(pos+this.n8*4, 1);
  1463. }
  1464. }
  1465. g2_getPoint(pos) {
  1466. const p = Array(3);
  1467. p[0] = this.getIntF2(pos);
  1468. p[1] = this.getIntF2(pos+this.n8*2);
  1469. p[2] = this.getIntF2(pos+this.n8*4);
  1470. return p;
  1471. }
  1472. g2_allocPoint(p) {
  1473. const pP = this.alloc(this.n8*6);
  1474. if (p) {
  1475. this.g2_putPoint(pP, p);
  1476. }
  1477. return pP;
  1478. }
  1479. putBin(b) {
  1480. const p = this.alloc(b.byteLength);
  1481. const s32 = new Uint32Array(b);
  1482. this.i32.set(s32, p/4);
  1483. return p;
  1484. }
  1485. test_AddG1(n) {
  1486. const start = new Date().getTime();
  1487. const pg = this.g1_allocPoint([bigInt(1), bigInt(2), bigInt(1)]);
  1488. this.g1_toMontgomery(pg,pg);
  1489. const p2 = this.g1_allocPoint();
  1490. this.instance.exports.testAddG1(n, pg, p2);
  1491. this.g1_fromMontgomery(p2,p2);
  1492. const end = new Date().getTime();
  1493. const time = end - start;
  1494. return time;
  1495. }
  1496. test_fft(n) {
  1497. const N=n;
  1498. const p = this.i32[0];
  1499. for (let i=0; i<N; i++) {
  1500. this.putInt(p+i*32, i);
  1501. }
  1502. const start = new Date().getTime();
  1503. this.fft_ifft(p, N);
  1504. const end = new Date().getTime();
  1505. const time = end - start;
  1506. return time;
  1507. }
  1508. }
  1509. module.exports = build;
  1510. },{"./build_curve.js":4,"./build_f1.js":5,"./build_f1m.js":6,"./build_f2m.js":7,"./build_fft":8,"./build_multiexp":10,"./build_pol":11,"./build_testg1":13,"./utils":17,"./wasmbuilder/index.js":20,"big-integer":2}],4:[function(require,module,exports){
  1511. const buildTimesScalar = require("./build_timesscalar");
  1512. module.exports = function buildCurve(module, prefix, prefixField) {
  1513. const n64 = module.modules[prefixField].n64;
  1514. const n8 = n64*8;
  1515. if (module.modules[prefix]) return prefix; // already builded
  1516. module.modules[prefix] = {
  1517. n64: n64*3
  1518. };
  1519. function buildIsZero() {
  1520. const f = module.addFunction(prefix + "_isZero");
  1521. f.addParam("p1", "i32");
  1522. f.setReturnType("i32");
  1523. const c = f.getCodeBuilder();
  1524. f.addCode(c.call(
  1525. prefixField + "_isZero",
  1526. c.i32_add(
  1527. c.getLocal("p1"),
  1528. c.i32_const(n8*2)
  1529. )
  1530. ));
  1531. }
  1532. function buildCopy() {
  1533. const f = module.addFunction(prefix + "_copy");
  1534. f.addParam("p1", "i32");
  1535. f.addParam("pr", "i32");
  1536. const c = f.getCodeBuilder();
  1537. f.addCode(c.call(
  1538. prefixField + "_copy",
  1539. c.getLocal("p1"),
  1540. c.getLocal("pr")
  1541. ));
  1542. f.addCode(c.call(
  1543. prefixField + "_copy",
  1544. c.i32_add(
  1545. c.getLocal("p1"),
  1546. c.i32_const(n8)
  1547. ),
  1548. c.i32_add(
  1549. c.getLocal("pr"),
  1550. c.i32_const(n8)
  1551. )
  1552. ));
  1553. f.addCode(c.call(
  1554. prefixField + "_copy",
  1555. c.i32_add(
  1556. c.getLocal("p1"),
  1557. c.i32_const(n8*2)
  1558. ),
  1559. c.i32_add(
  1560. c.getLocal("pr"),
  1561. c.i32_const(n8*2)
  1562. )
  1563. ));
  1564. }
  1565. function buildZero() {
  1566. const f = module.addFunction(prefix + "_zero");
  1567. f.addParam("pr", "i32");
  1568. const c = f.getCodeBuilder();
  1569. f.addCode(c.call(
  1570. prefixField + "_zero",
  1571. c.getLocal("pr")
  1572. ));
  1573. f.addCode(c.call(
  1574. prefixField + "_one",
  1575. c.i32_add(
  1576. c.getLocal("pr"),
  1577. c.i32_const(n8)
  1578. )
  1579. ));
  1580. f.addCode(c.call(
  1581. prefixField + "_zero",
  1582. c.i32_add(
  1583. c.getLocal("pr"),
  1584. c.i32_const(n8*2)
  1585. )
  1586. ));
  1587. }
  1588. function buildDouble() {
  1589. const f = module.addFunction(prefix + "_double");
  1590. f.addParam("p1", "i32");
  1591. f.addParam("pr", "i32");
  1592. const c = f.getCodeBuilder();
  1593. const x = c.getLocal("p1");
  1594. const y = c.i32_add(c.getLocal("p1"), c.i32_const(n8));
  1595. const z = c.i32_add(c.getLocal("p1"), c.i32_const(n8*2));
  1596. const x3 = c.getLocal("pr");
  1597. const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8));
  1598. const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8*2));
  1599. const A = c.i32_const(module.alloc(n8));
  1600. const B = c.i32_const(module.alloc(n8));
  1601. const C = c.i32_const(module.alloc(n8));
  1602. const D = c.i32_const(module.alloc(n8));
  1603. const E = c.i32_const(module.alloc(n8));
  1604. const F = c.i32_const(module.alloc(n8));
  1605. const G = c.i32_const(module.alloc(n8));
  1606. const eightC = c.i32_const(module.alloc(n8));
  1607. f.addCode(
  1608. c.if(
  1609. c.call(prefix + "_isZero", c.getLocal("p1")),
  1610. [
  1611. ...c.call(prefix + "_copy", c.getLocal("p1"), c.getLocal("pr")),
  1612. ...c.ret([])
  1613. ]
  1614. ),
  1615. c.call(prefixField + "_mul", x, x, A),
  1616. c.call(prefixField + "_mul", y, y, B),
  1617. c.call(prefixField + "_mul", B, B, C),
  1618. c.call(prefixField + "_add", x, B, D),
  1619. c.call(prefixField + "_mul", D, D, D),
  1620. c.call(prefixField + "_sub", D, A, D),
  1621. c.call(prefixField + "_sub", D, C, D),
  1622. c.call(prefixField + "_add", D, D, D),
  1623. c.call(prefixField + "_add", A, A, E),
  1624. c.call(prefixField + "_add", E, A, E),
  1625. c.call(prefixField + "_mul", E, E, F),
  1626. c.call(prefixField + "_mul", y, z, G),
  1627. c.call(prefixField + "_add", D, D, x3),
  1628. c.call(prefixField + "_sub", F, x3, x3),
  1629. c.call(prefixField + "_add", C, C, eightC),
  1630. c.call(prefixField + "_add", eightC, eightC, eightC),
  1631. c.call(prefixField + "_add", eightC, eightC, eightC),
  1632. c.call(prefixField + "_sub", D, x3, y3),
  1633. c.call(prefixField + "_mul", y3, E, y3),
  1634. c.call(prefixField + "_sub", y3, eightC, y3),
  1635. c.call(prefixField + "_add", G, G, z3),
  1636. );
  1637. }
  1638. function buildToMontgomery() {
  1639. const f = module.addFunction(prefix + "_toMontgomery");
  1640. f.addParam("p1", "i32");
  1641. f.addParam("pr", "i32");
  1642. const c = f.getCodeBuilder();
  1643. f.addCode(c.call(
  1644. prefixField + "_toMontgomery",
  1645. c.getLocal("p1"),
  1646. c.getLocal("pr")
  1647. ));
  1648. for (let i=1; i<3; i++) {
  1649. f.addCode(c.call(
  1650. prefixField + "_toMontgomery",
  1651. c.i32_add(c.getLocal("p1"), c.i32_const(i*n8)),
  1652. c.i32_add(c.getLocal("pr"), c.i32_const(i*n8))
  1653. ));
  1654. }
  1655. }
  1656. function buildFromMontgomery() {
  1657. const f = module.addFunction(prefix + "_fromMontgomery");
  1658. f.addParam("p1", "i32");
  1659. f.addParam("pr", "i32");
  1660. const c = f.getCodeBuilder();
  1661. f.addCode(c.call(
  1662. prefixField + "_fromMontgomery",
  1663. c.getLocal("p1"),
  1664. c.getLocal("pr")
  1665. ));
  1666. for (let i=1; i<3; i++) {
  1667. f.addCode(c.call(
  1668. prefixField + "_fromMontgomery",
  1669. c.i32_add(c.getLocal("p1"), c.i32_const(i*n8)),
  1670. c.i32_add(c.getLocal("pr"), c.i32_const(i*n8))
  1671. ));
  1672. }
  1673. }
  1674. function buildAdd() {
  1675. const f = module.addFunction(prefix + "_add");
  1676. f.addParam("p1", "i32");
  1677. f.addParam("p2", "i32");
  1678. f.addParam("pr", "i32");
  1679. f.addLocal("z1", "i32");
  1680. f.addLocal("z2", "i32");
  1681. const c = f.getCodeBuilder();
  1682. const x1 = c.getLocal("p1");
  1683. const y1 = c.i32_add(c.getLocal("p1"), c.i32_const(n8));
  1684. f.addCode(c.setLocal("z1", c.i32_add(c.getLocal("p1"), c.i32_const(n8*2))));
  1685. const z1 = c.getLocal("z1");
  1686. const x2 = c.getLocal("p2");
  1687. const y2 = c.i32_add(c.getLocal("p2"), c.i32_const(n8));
  1688. f.addCode(c.setLocal("z2", c.i32_add(c.getLocal("p2"), c.i32_const(n8*2))));
  1689. const z2 = c.getLocal("z2");
  1690. const x3 = c.getLocal("pr");
  1691. const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8));
  1692. const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8*2));
  1693. const Z1Z1 = c.i32_const(module.alloc(n8));
  1694. const Z2Z2 = c.i32_const(module.alloc(n8));
  1695. const U1 = c.i32_const(module.alloc(n8));
  1696. const U2 = c.i32_const(module.alloc(n8));
  1697. const Z1_cubed = c.i32_const(module.alloc(n8));
  1698. const Z2_cubed = c.i32_const(module.alloc(n8));
  1699. const S1 = c.i32_const(module.alloc(n8));
  1700. const S2 = c.i32_const(module.alloc(n8));
  1701. const H = c.i32_const(module.alloc(n8));
  1702. const S2_minus_S1 = c.i32_const(module.alloc(n8));
  1703. const I = c.i32_const(module.alloc(n8));
  1704. const J = c.i32_const(module.alloc(n8));
  1705. const r = c.i32_const(module.alloc(n8));
  1706. const r2 = c.i32_const(module.alloc(n8));
  1707. const V = c.i32_const(module.alloc(n8));
  1708. const V2 = c.i32_const(module.alloc(n8));
  1709. const S1_J2 = c.i32_const(module.alloc(n8));
  1710. f.addCode(
  1711. c.if(
  1712. c.call(prefix + "_isZero", c.getLocal("p1")),
  1713. [
  1714. ...c.call(prefix + "_copy", c.getLocal("p2"), c.getLocal("pr")),
  1715. ...c.ret([])
  1716. ]
  1717. ),
  1718. c.if(
  1719. c.call(prefix + "_isZero", c.getLocal("p2")),
  1720. [
  1721. ...c.call(prefix + "_copy", c.getLocal("p1"), c.getLocal("pr")),
  1722. ...c.ret([])
  1723. ]
  1724. ),
  1725. c.call(prefixField + "_mul", z1, z1, Z1Z1),
  1726. c.call(prefixField + "_mul", z2, z2, Z2Z2),
  1727. c.call(prefixField + "_mul", x1, Z2Z2, U1),
  1728. c.call(prefixField + "_mul", x2, Z1Z1, U2),
  1729. c.call(prefixField + "_mul", z1, Z1Z1, Z1_cubed),
  1730. c.call(prefixField + "_mul", z2, Z2Z2, Z2_cubed),
  1731. c.call(prefixField + "_mul", y1, Z2_cubed, S1),
  1732. c.call(prefixField + "_mul", y2, Z1_cubed, S2),
  1733. c.if(
  1734. c.call(prefixField + "_eq", U1, U2),
  1735. c.if(
  1736. c.call(prefixField + "_eq", S1, S2),
  1737. [
  1738. ...c.call(prefix + "_double", c.getLocal("p1"), c.getLocal("pr")),
  1739. ...c.ret([])
  1740. ]
  1741. )
  1742. ),
  1743. c.call(prefixField + "_sub", U2, U1, H),
  1744. c.call(prefixField + "_sub", S2, S1, S2_minus_S1),
  1745. c.call(prefixField + "_add", H, H, I),
  1746. c.call(prefixField + "_mul", I, I, I),
  1747. c.call(prefixField + "_mul", H, I, J),
  1748. c.call(prefixField + "_add", S2_minus_S1, S2_minus_S1, r),
  1749. c.call(prefixField + "_mul", U1, I, V),
  1750. c.call(prefixField + "_mul", r, r, r2),
  1751. c.call(prefixField + "_add", V, V, V2),
  1752. c.call(prefixField + "_sub", r2, J, x3),
  1753. c.call(prefixField + "_sub", x3, V2, x3),
  1754. c.call(prefixField + "_mul", S1, J, S1_J2),
  1755. c.call(prefixField + "_add", S1_J2, S1_J2, S1_J2),
  1756. c.call(prefixField + "_sub", V, x3, y3),
  1757. c.call(prefixField + "_mul", y3, r, y3),
  1758. c.call(prefixField + "_sub", y3, S1_J2, y3),
  1759. c.call(prefixField + "_add", z1, z2, z3),
  1760. c.call(prefixField + "_mul", z3, z3, z3),
  1761. c.call(prefixField + "_sub", z3, Z1Z1, z3),
  1762. c.call(prefixField + "_sub", z3, Z2Z2, z3),
  1763. c.call(prefixField + "_mul", z3, H, z3),
  1764. );
  1765. }
  1766. function buildNeg() {
  1767. const f = module.addFunction(prefix + "_neg");
  1768. f.addParam("p1", "i32");
  1769. f.addParam("pr", "i32");
  1770. const c = f.getCodeBuilder();
  1771. const x = c.getLocal("p1");
  1772. const y = c.i32_add(c.getLocal("p1"), c.i32_const(n8));
  1773. const z = c.i32_add(c.getLocal("p1"), c.i32_const(n8*2));
  1774. const x3 = c.getLocal("pr");
  1775. const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8));
  1776. const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8*2));
  1777. f.addCode(
  1778. c.call(prefixField + "_copy", x, x3),
  1779. c.call(prefixField + "_neg", y, y3),
  1780. c.call(prefixField + "_copy", z, z3)
  1781. );
  1782. }
  1783. function buildSub() {
  1784. const f = module.addFunction(prefix + "_sub");
  1785. f.addParam("p1", "i32");
  1786. f.addParam("p2", "i32");
  1787. f.addParam("pr", "i32");
  1788. const c = f.getCodeBuilder();
  1789. f.addCode(
  1790. c.call(prefix + "_neg", c.getLocal("p2"), c.getLocal("pr")),
  1791. c.call(prefix + "_add", c.getLocal("p1"), c.getLocal("pr"), c.getLocal("pr")),
  1792. );
  1793. }
  1794. function buildAffine() {
  1795. const f = module.addFunction(prefix + "_affine");
  1796. f.addParam("p1", "i32");
  1797. f.addParam("pr", "i32");
  1798. const c = f.getCodeBuilder();
  1799. const x = c.getLocal("p1");
  1800. const y = c.i32_add(c.getLocal("p1"), c.i32_const(n8));
  1801. const z = c.i32_add(c.getLocal("p1"), c.i32_const(n8*2));
  1802. const x3 = c.getLocal("pr");
  1803. const y3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8));
  1804. const z3 = c.i32_add(c.getLocal("pr"), c.i32_const(n8*2));
  1805. const Z_inv = c.i32_const(module.alloc(n8));
  1806. const Z2_inv = c.i32_const(module.alloc(n8));
  1807. const Z3_inv = c.i32_const(module.alloc(n8));
  1808. f.addCode(
  1809. c.if(
  1810. c.call(prefix + "_isZero", c.getLocal("p1")),
  1811. c.call(prefix + "_zero", c.getLocal("pr")),
  1812. [
  1813. ...c.call(prefixField + "_inverse", z, Z_inv),
  1814. ...c.call(prefixField + "_mul", Z_inv, Z_inv, Z2_inv),
  1815. ...c.call(prefixField + "_mul", Z_inv, Z2_inv, Z3_inv),
  1816. ...c.call(prefixField + "_mul", x, Z2_inv, x3),
  1817. ...c.call(prefixField + "_mul", y, Z3_inv, y3),
  1818. ...c.call(prefixField + "_one", z3)
  1819. ]
  1820. )
  1821. );
  1822. }
  1823. buildIsZero();
  1824. buildZero();
  1825. buildCopy();
  1826. buildDouble();
  1827. buildAdd();
  1828. buildNeg();
  1829. buildSub();
  1830. buildFromMontgomery();
  1831. buildToMontgomery();
  1832. buildAffine();
  1833. buildTimesScalar(
  1834. module,
  1835. prefix + "_timesScalar",
  1836. n8*3,
  1837. prefix + "_add",
  1838. prefix + "_double",
  1839. prefix
  1840. );
  1841. module.exportFunction(prefix + "_isZero");
  1842. module.exportFunction(prefix + "_copy");
  1843. module.exportFunction(prefix + "_zero");
  1844. module.exportFunction(prefix + "_double");
  1845. module.exportFunction(prefix + "_add");
  1846. module.exportFunction(prefix + "_neg");
  1847. module.exportFunction(prefix + "_sub");
  1848. module.exportFunction(prefix + "_fromMontgomery");
  1849. module.exportFunction(prefix + "_toMontgomery");
  1850. module.exportFunction(prefix + "_affine");
  1851. module.exportFunction(prefix + "_timesScalar");
  1852. /*
  1853. buildG1MulScalar(module, zq);
  1854. module.exportFunction("g1MulScalar");
  1855. */
  1856. return prefix;
  1857. };
  1858. },{"./build_timesscalar":14}],5:[function(require,module,exports){
  1859. const bigInt = require("big-integer");
  1860. const buildF1m =require("./build_f1m.js");
  1861. module.exports = function buildF1(module, _q, _prefix, _f1mPrefix, _intPrefix) {
  1862. const q = bigInt(_q);
  1863. const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1;
  1864. const n8 = n64*8;
  1865. const prefix = _prefix || "f1";
  1866. if (module.modules[prefix]) return prefix; // already builded
  1867. module.modules[prefix] = {
  1868. n64: n64
  1869. };
  1870. const intPrefix = _intPrefix || "int";
  1871. const f1mPrefix = buildF1m(module, q, _f1mPrefix, intPrefix);
  1872. const pR2 = module.modules[f1mPrefix].pR2;
  1873. const pq = module.modules[f1mPrefix].pq;
  1874. function buildMul() {
  1875. const pAux1 = module.alloc(n8);
  1876. const f = module.addFunction(prefix+ "_mul");
  1877. f.addParam("x", "i32");
  1878. f.addParam("y", "i32");
  1879. f.addParam("r", "i32");
  1880. const c = f.getCodeBuilder();
  1881. f.addCode(c.call(f1mPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux1)));
  1882. f.addCode(c.call(f1mPrefix + "_mul", c.i32_const(pAux1), c.i32_const(pR2), c.getLocal("r")));
  1883. }
  1884. function buildInverse() {
  1885. const f = module.addFunction(prefix+ "_inverse");
  1886. f.addParam("x", "i32");
  1887. f.addParam("r", "i32");
  1888. const c = f.getCodeBuilder();
  1889. f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("x"), c.i32_const(pq), c.getLocal("r")));
  1890. }
  1891. buildMul();
  1892. buildInverse();
  1893. module.exportFunction(f1mPrefix + "_add", prefix + "_add");
  1894. module.exportFunction(f1mPrefix + "_sub", prefix + "_sub");
  1895. module.exportFunction(f1mPrefix + "_neg", prefix + "_neg");
  1896. module.exportFunction(prefix + "_mul");
  1897. module.exportFunction(prefix + "_inverse");
  1898. module.exportFunction(f1mPrefix + "_copy", prefix+"_copy");
  1899. module.exportFunction(f1mPrefix + "_zero", prefix+"_zero");
  1900. module.exportFunction(f1mPrefix + "_one", prefix+"_one");
  1901. module.exportFunction(f1mPrefix + "_isZero", prefix+"_isZero");
  1902. module.exportFunction(f1mPrefix + "_eq", prefix+"_eq");
  1903. return prefix;
  1904. };
  1905. },{"./build_f1m.js":6,"big-integer":2}],6:[function(require,module,exports){
  1906. const bigInt = require("big-integer");
  1907. const buildInt = require("./build_int.js");
  1908. const utils = require("./utils.js");
  1909. module.exports = function buildF1m(module, _q, _prefix, _intPrefix) {
  1910. const q = bigInt(_q);
  1911. const n64 = Math.floor((q.minus(1).bitLength() - 1)/64) +1;
  1912. const n32 = n64*2;
  1913. const n8 = n64*8;
  1914. const prefix = _prefix || "f1m";
  1915. if (module.modules[prefix]) return prefix; // already builded
  1916. const intPrefix = buildInt(module, n64, _intPrefix);
  1917. const pq = module.alloc(n8, utils.bigInt2BytesLE(q, n8));
  1918. const pR2 = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).square().mod(q), n8));
  1919. const pOne = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(n64*64).mod(q), n8));
  1920. const pZero = module.alloc(utils.bigInt2BytesLE(bigInt.zero, n8));
  1921. module.modules[prefix] = {
  1922. pq: pq,
  1923. pR2: pR2,
  1924. n64: n64,
  1925. q: q,
  1926. pOne: pOne,
  1927. pZero: pZero
  1928. };
  1929. function buildOne() {
  1930. const f = module.addFunction(prefix+"_one");
  1931. f.addParam("pr", "i32");
  1932. const c = f.getCodeBuilder();
  1933. f.addCode(c.call(prefix + "_copy", c.i32_const(pOne), c.getLocal("pr")));
  1934. }
  1935. function buildAdd() {
  1936. const f = module.addFunction(prefix+"_add");
  1937. f.addParam("x", "i32");
  1938. f.addParam("y", "i32");
  1939. f.addParam("r", "i32");
  1940. const c = f.getCodeBuilder();
  1941. f.addCode(
  1942. c.if(
  1943. c.call(intPrefix+"_add", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")),
  1944. c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))),
  1945. c.if(
  1946. c.call(intPrefix+"_gte", c.getLocal("r"), c.i32_const(pq) ),
  1947. c.drop(c.call(intPrefix+"_sub", c.getLocal("r"), c.i32_const(pq), c.getLocal("r"))),
  1948. )
  1949. )
  1950. );
  1951. }
  1952. function buildSub() {
  1953. const f = module.addFunction(prefix+"_sub");
  1954. f.addParam("x", "i32");
  1955. f.addParam("y", "i32");
  1956. f.addParam("r", "i32");
  1957. const c = f.getCodeBuilder();
  1958. f.addCode(
  1959. c.if(
  1960. c.call(intPrefix+"_sub", c.getLocal("x"), c.getLocal("y"), c.getLocal("r")),
  1961. c.drop(c.call(intPrefix+"_add", c.getLocal("r"), c.i32_const(pq), c.getLocal("r")))
  1962. )
  1963. );
  1964. }
  1965. function buildNeg() {
  1966. const f = module.addFunction(prefix+"_neg");
  1967. f.addParam("x", "i32");
  1968. f.addParam("r", "i32");
  1969. const c = f.getCodeBuilder();
  1970. f.addCode(
  1971. c.if(
  1972. c.i32_eqz( c.call(intPrefix + "_isZero", c.getLocal("x"))),
  1973. c.drop(c.call(intPrefix+"_sub", c.i32_const(pq), c.getLocal("x"), c.getLocal("r"))),
  1974. )
  1975. );
  1976. }
  1977. function buildMReduct() {
  1978. const carries = module.alloc(n32*n32*8);
  1979. const f = module.addFunction(prefix+"_mReduct");
  1980. f.addParam("t", "i32");
  1981. f.addParam("r", "i32");
  1982. f.addLocal("np32", "i64");
  1983. f.addLocal("c", "i64");
  1984. f.addLocal("m", "i64");
  1985. const c = f.getCodeBuilder();
  1986. const np32 = bigInt("100000000",16).minus( q.modInv(bigInt("100000000",16))).toJSNumber();
  1987. f.addCode(c.setLocal("np32", c.i64_const(np32)));
  1988. for (let i=0; i<n32; i++) {
  1989. f.addCode(c.setLocal("c", c.i64_const(0)));
  1990. f.addCode(
  1991. c.setLocal(
  1992. "m",
  1993. c.i64_and(
  1994. c.i64_mul(
  1995. c.i64_load32_u(c.getLocal("t"), i*4),
  1996. c.getLocal("np32")
  1997. ),
  1998. c.i64_const("0xFFFFFFFF")
  1999. )
  2000. )
  2001. );
  2002. for (let j=0; j<n32; j++) {
  2003. f.addCode(
  2004. c.setLocal("c",
  2005. c.i64_add(
  2006. c.i64_add(
  2007. c.i64_load32_u(c.getLocal("t"), (i+j)*4),
  2008. c.i64_shr_u(c.getLocal("c"), c.i64_const(32))
  2009. ),
  2010. c.i64_mul(
  2011. c.i64_load32_u(c.i32_const(pq), j*4),
  2012. c.getLocal("m")
  2013. )
  2014. )
  2015. )
  2016. );
  2017. f.addCode(
  2018. c.i64_store32(
  2019. c.getLocal("t"),
  2020. (i+j)*4,
  2021. c.getLocal("c")
  2022. )
  2023. );
  2024. }
  2025. f.addCode(
  2026. c.i64_store32(
  2027. c.i32_const(carries),
  2028. i*4,
  2029. c.i64_shr_u(c.getLocal("c"), c.i64_const(32))
  2030. )
  2031. );
  2032. }
  2033. f.addCode(
  2034. c.call(
  2035. prefix+"_add",
  2036. c.i32_const(carries),
  2037. c.i32_add(
  2038. c.getLocal("t"),
  2039. c.i32_const(n32*4)
  2040. ),
  2041. c.getLocal("r")
  2042. )
  2043. );
  2044. }
  2045. function buildMul() {
  2046. const pAux2 = module.alloc(n8*2);
  2047. const f = module.addFunction(prefix+"_mul");
  2048. f.addParam("x", "i32");
  2049. f.addParam("y", "i32");
  2050. f.addParam("r", "i32");
  2051. const c = f.getCodeBuilder();
  2052. f.addCode(c.call(intPrefix + "_mul", c.getLocal("x"), c.getLocal("y"), c.i32_const(pAux2) ));
  2053. f.addCode(c.call(prefix + "_mReduct", c.i32_const(pAux2), c.getLocal("r")));
  2054. }
  2055. function buildToMontgomery() {
  2056. const f = module.addFunction(prefix+"_toMontgomery");
  2057. f.addParam("x", "i32");
  2058. f.addParam("r", "i32");
  2059. const c = f.getCodeBuilder();
  2060. f.addCode(c.call(prefix+"_mul", c.getLocal("x"), c.i32_const(pR2), c.getLocal("r")));
  2061. }
  2062. function buildFromMontgomery() {
  2063. const pAux2 = module.alloc(n8*2);
  2064. const f = module.addFunction(prefix+"_fromMontgomery");
  2065. f.addParam("x", "i32");
  2066. f.addParam("r", "i32");
  2067. const c = f.getCodeBuilder();
  2068. f.addCode(c.call(intPrefix + "_copy", c.getLocal("x"), c.i32_const(pAux2) ));
  2069. f.addCode(c.call(intPrefix + "_zero", c.i32_const(pAux2 + n8) ));
  2070. f.addCode(c.call(prefix+"_mReduct", c.i32_const(pAux2), c.getLocal("r")));
  2071. }
  2072. function buildInverse() {
  2073. const f = module.addFunction(prefix+ "_inverse");
  2074. f.addParam("x", "i32");
  2075. f.addParam("r", "i32");
  2076. const c = f.getCodeBuilder();
  2077. f.addCode(c.call(prefix + "_fromMontgomery", c.getLocal("x"), c.getLocal("r")));
  2078. f.addCode(c.call(intPrefix + "_inverseMod", c.getLocal("r"), c.i32_const(pq), c.getLocal("r")));
  2079. f.addCode(c.call(prefix + "_toMontgomery", c.getLocal("r"), c.getLocal("r")));
  2080. }
  2081. buildAdd();
  2082. buildSub();
  2083. buildNeg();
  2084. buildMReduct();
  2085. buildMul();
  2086. buildToMontgomery();
  2087. buildFromMontgomery();
  2088. buildInverse();
  2089. module.exportFunction(prefix + "_add");
  2090. module.exportFunction(prefix + "_sub");
  2091. module.exportFunction(prefix + "_neg");
  2092. module.exportFunction(prefix + "_mReduct");
  2093. module.exportFunction(prefix + "_mul");
  2094. module.exportFunction(prefix + "_fromMontgomery");
  2095. module.exportFunction(prefix + "_toMontgomery");
  2096. module.exportFunction(prefix + "_inverse");
  2097. module.exportFunction(intPrefix + "_copy", prefix+"_copy");
  2098. module.exportFunction(intPrefix + "_zero", prefix+"_zero");
  2099. module.exportFunction(intPrefix + "_isZero", prefix+"_isZero");
  2100. module.exportFunction(intPrefix + "_eq", prefix+"_eq");
  2101. buildOne();
  2102. module.exportFunction(prefix + "_one");
  2103. return prefix;
  2104. };
  2105. },{"./build_int.js":9,"./utils.js":17,"big-integer":2}],7:[function(require,module,exports){
  2106. module.exports = function buildF2m(module, pNonResidue, prefix, f1mPrefix) {
  2107. if (module.modules[prefix]) return prefix; // already builded
  2108. const f1n8 = module.modules[f1mPrefix].n64*8;
  2109. module.modules[prefix] = {
  2110. n64: module.modules[f1mPrefix].n64*2
  2111. };
  2112. function buildAdd() {
  2113. const f = module.addFunction(prefix+"_add");
  2114. f.addParam("x", "i32");
  2115. f.addParam("y", "i32");
  2116. f.addParam("r", "i32");
  2117. const c = f.getCodeBuilder();
  2118. const x0 = c.getLocal("x");
  2119. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2120. const y0 = c.getLocal("y");
  2121. const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8));
  2122. const r0 = c.getLocal("r");
  2123. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2124. f.addCode(
  2125. c.call(f1mPrefix+"_add", x0, y0, r0),
  2126. c.call(f1mPrefix+"_add", x1, y1, r1),
  2127. );
  2128. }
  2129. function buildSub() {
  2130. const f = module.addFunction(prefix+"_sub");
  2131. f.addParam("x", "i32");
  2132. f.addParam("y", "i32");
  2133. f.addParam("r", "i32");
  2134. const c = f.getCodeBuilder();
  2135. const x0 = c.getLocal("x");
  2136. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2137. const y0 = c.getLocal("y");
  2138. const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8));
  2139. const r0 = c.getLocal("r");
  2140. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2141. f.addCode(
  2142. c.call(f1mPrefix+"_sub", x0, y0, r0),
  2143. c.call(f1mPrefix+"_sub", x1, y1, r1),
  2144. );
  2145. }
  2146. function buildNeg() {
  2147. const f = module.addFunction(prefix+"_neg");
  2148. f.addParam("x", "i32");
  2149. f.addParam("r", "i32");
  2150. const c = f.getCodeBuilder();
  2151. const x0 = c.getLocal("x");
  2152. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2153. const r0 = c.getLocal("r");
  2154. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2155. f.addCode(
  2156. c.call(f1mPrefix+"_neg", x0, r0),
  2157. c.call(f1mPrefix+"_neg", x1, r1),
  2158. );
  2159. }
  2160. function buildMul() {
  2161. const f = module.addFunction(prefix+"_mul");
  2162. f.addParam("x", "i32");
  2163. f.addParam("y", "i32");
  2164. f.addParam("r", "i32");
  2165. const c = f.getCodeBuilder();
  2166. const x0 = c.getLocal("x");
  2167. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2168. const y0 = c.getLocal("y");
  2169. const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8));
  2170. const r0 = c.getLocal("r");
  2171. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2172. const A = c.i32_const(module.alloc(f1n8));
  2173. const B = c.i32_const(module.alloc(f1n8));
  2174. const C = c.i32_const(module.alloc(f1n8));
  2175. const D = c.i32_const(module.alloc(f1n8));
  2176. f.addCode(
  2177. c.call(f1mPrefix + "_mul", x0, y0, A), // A = x0*y0
  2178. c.call(f1mPrefix + "_mul", x1, y1, B), // B = x1*y1
  2179. c.call(f1mPrefix + "_add", x0, x1, C), // C = x0 + x1
  2180. c.call(f1mPrefix + "_add", y0, y1, D), // D = y0 + y1
  2181. c.call(f1mPrefix + "_mul", C, D, C), // C = (x0 + x1)*(y0 + y1) = x0*y0+x0*y1+x1*y0+x1*y1
  2182. c.call(f1mPrefix + "_mul", B, c.i32_const(pNonResidue), r0), // r0 = nr*(x1*y1)
  2183. c.call(f1mPrefix + "_add", A, r0, r0), // r0 = x0*y0 + nr*(x1*y1)
  2184. c.call(f1mPrefix + "_add", A, B, r1), // r1 = x0*y0+x1*y1
  2185. c.call(f1mPrefix + "_sub", C, r1, r1) // r1 = x0*y0+x0*y1+x1*y0+x1*y1 - x0*y0+x1*y1 = x0*y1+x1*y0
  2186. );
  2187. }
  2188. function buildToMontgomery() {
  2189. const f = module.addFunction(prefix+"_toMontgomery");
  2190. f.addParam("x", "i32");
  2191. f.addParam("r", "i32");
  2192. const c = f.getCodeBuilder();
  2193. const x0 = c.getLocal("x");
  2194. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2195. const r0 = c.getLocal("r");
  2196. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2197. f.addCode(
  2198. c.call(f1mPrefix+"_toMontgomery", x0, r0),
  2199. c.call(f1mPrefix+"_toMontgomery", x1, r1)
  2200. );
  2201. }
  2202. function buildFromMontgomery() {
  2203. const f = module.addFunction(prefix+"_fromMontgomery");
  2204. f.addParam("x", "i32");
  2205. f.addParam("r", "i32");
  2206. const c = f.getCodeBuilder();
  2207. const x0 = c.getLocal("x");
  2208. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2209. const r0 = c.getLocal("r");
  2210. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2211. f.addCode(
  2212. c.call(f1mPrefix+"_fromMontgomery", x0, r0),
  2213. c.call(f1mPrefix+"_fromMontgomery", x1, r1)
  2214. );
  2215. }
  2216. function buildCopy() {
  2217. const f = module.addFunction(prefix+"_copy");
  2218. f.addParam("x", "i32");
  2219. f.addParam("r", "i32");
  2220. const c = f.getCodeBuilder();
  2221. const x0 = c.getLocal("x");
  2222. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2223. const r0 = c.getLocal("r");
  2224. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2225. f.addCode(
  2226. c.call(f1mPrefix+"_copy", x0, r0),
  2227. c.call(f1mPrefix+"_copy", x1, r1)
  2228. );
  2229. }
  2230. function buildZero() {
  2231. const f = module.addFunction(prefix+"_zero");
  2232. f.addParam("x", "i32");
  2233. const c = f.getCodeBuilder();
  2234. const x0 = c.getLocal("x");
  2235. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2236. f.addCode(
  2237. c.call(f1mPrefix+"_zero", x0),
  2238. c.call(f1mPrefix+"_zero", x1)
  2239. );
  2240. }
  2241. function buildOne() {
  2242. const f = module.addFunction(prefix+"_one");
  2243. f.addParam("x", "i32");
  2244. const c = f.getCodeBuilder();
  2245. const x0 = c.getLocal("x");
  2246. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2247. f.addCode(
  2248. c.call(f1mPrefix+"_one", x0),
  2249. c.call(f1mPrefix+"_zero", x1)
  2250. );
  2251. }
  2252. function buildEq() {
  2253. const f = module.addFunction(prefix+"_eq");
  2254. f.addParam("x", "i32");
  2255. f.addParam("y", "i32");
  2256. f.setReturnType("i32");
  2257. const c = f.getCodeBuilder();
  2258. const x0 = c.getLocal("x");
  2259. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2260. const y0 = c.getLocal("y");
  2261. const y1 = c.i32_add(c.getLocal("y"), c.i32_const(f1n8));
  2262. f.addCode(
  2263. c.i32_and(
  2264. c.call(f1mPrefix+"_eq", x0, y0),
  2265. c.call(f1mPrefix+"_eq", x1, y1)
  2266. )
  2267. );
  2268. }
  2269. function buildIsZero() {
  2270. const f = module.addFunction(prefix+"_isZero");
  2271. f.addParam("x", "i32");
  2272. f.setReturnType("i32");
  2273. const c = f.getCodeBuilder();
  2274. const x0 = c.getLocal("x");
  2275. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2276. f.addCode(
  2277. c.i32_and(
  2278. c.call(f1mPrefix+"_isZero", x0),
  2279. c.call(f1mPrefix+"_isZero", x1)
  2280. )
  2281. );
  2282. }
  2283. function buildInverse() {
  2284. const f = module.addFunction(prefix+"_inverse");
  2285. f.addParam("x", "i32");
  2286. f.addParam("r", "i32");
  2287. const c = f.getCodeBuilder();
  2288. const x0 = c.getLocal("x");
  2289. const x1 = c.i32_add(c.getLocal("x"), c.i32_const(f1n8));
  2290. const r0 = c.getLocal("r");
  2291. const r1 = c.i32_add(c.getLocal("r"), c.i32_const(f1n8));
  2292. const t0 = c.i32_const(module.alloc(f1n8));
  2293. const t1 = c.i32_const(module.alloc(f1n8));
  2294. const t2 = c.i32_const(module.alloc(f1n8));
  2295. const t3 = c.i32_const(module.alloc(f1n8));
  2296. f.addCode(
  2297. c.call(f1mPrefix+"_mul", x0, x0, t0),
  2298. c.call(f1mPrefix+"_mul", x1, x1, t1),
  2299. c.call(f1mPrefix+"_mul", t1, c.i32_const(pNonResidue), t2),
  2300. c.call(f1mPrefix+"_sub", t0, t2, t2),
  2301. c.call(f1mPrefix+"_inverse", t2, t3),
  2302. c.call(f1mPrefix+"_mul", x0, t3, r0),
  2303. c.call(f1mPrefix+"_mul", x1, t3, r1),
  2304. c.call(f1mPrefix+"_neg", r1, r1),
  2305. );
  2306. }
  2307. buildIsZero();
  2308. buildZero();
  2309. buildOne();
  2310. buildCopy();
  2311. buildMul();
  2312. buildAdd();
  2313. buildSub();
  2314. buildNeg();
  2315. buildToMontgomery();
  2316. buildFromMontgomery();
  2317. buildEq();
  2318. buildInverse();
  2319. module.exportFunction(prefix + "_isZero");
  2320. module.exportFunction(prefix + "_zero");
  2321. module.exportFunction(prefix + "_one");
  2322. module.exportFunction(prefix + "_copy");
  2323. module.exportFunction(prefix + "_mul");
  2324. module.exportFunction(prefix + "_add");
  2325. module.exportFunction(prefix + "_sub");
  2326. module.exportFunction(prefix + "_neg");
  2327. module.exportFunction(prefix + "_fromMontgomery");
  2328. module.exportFunction(prefix + "_toMontgomery");
  2329. module.exportFunction(prefix + "_eq");
  2330. module.exportFunction(prefix + "_inverse");
  2331. return prefix;
  2332. };
  2333. },{}],8:[function(require,module,exports){
  2334. const bigInt = require("big-integer");
  2335. const utils = require("./utils.js");
  2336. module.exports = function buildFFT(module, prefix, f1mPrefix) {
  2337. const n64 = module.modules[f1mPrefix].n64;
  2338. const n8 = n64*8;
  2339. const q = module.modules[f1mPrefix].q;
  2340. let rem = q.minus(bigInt(1));
  2341. let maxBits = 0;
  2342. while (!rem.isOdd()) {
  2343. maxBits ++;
  2344. rem = rem.shiftRight(1);
  2345. }
  2346. let nr = bigInt(2);
  2347. while ( nr.modPow(q.shiftRight(1), q).equals(1) ) nr = nr.add(1);
  2348. const w = new Array(maxBits+1);
  2349. w[maxBits] = nr.modPow(rem, q);
  2350. let n=maxBits-1;
  2351. while (n>=0) {
  2352. w[n] = w[n+1].modPow(2, q);
  2353. n--;
  2354. }
  2355. const bytes = [];
  2356. const R = bigInt(1).shiftLeft(n8*8).mod(q);
  2357. for (let i=0; i<w.length; i++) {
  2358. const m = w[i].times(R).mod(q);
  2359. bytes.push(...utils.bigInt2BytesLE(m, n8));
  2360. }
  2361. const ROOTs = module.alloc(bytes);
  2362. const i2 = new Array(maxBits+1);
  2363. i2[0] = bigInt(1);
  2364. for (let i=1; i<=maxBits; i++) {
  2365. i2[i] = i2[i-1].times(2);
  2366. }
  2367. const bytesi2 =[];
  2368. for (let i=0; i<=maxBits; i++) {
  2369. const m = i2[i].modInv(q).times(R).mod(q);
  2370. bytesi2.push(...utils.bigInt2BytesLE(m, n8));
  2371. }
  2372. const INV2 = module.alloc(bytesi2);
  2373. function rev(x) {
  2374. let r=0;
  2375. for (let i=0; i<8; i++) {
  2376. if (x & (1 << i)) {
  2377. r = r | (0x80 >> i);
  2378. }
  2379. }
  2380. return r;
  2381. }
  2382. const rtable = Array(256);
  2383. for (let i=0; i<256; i++) {
  2384. rtable[i] = rev(i);
  2385. }
  2386. const REVTABLE = module.alloc(rtable);
  2387. function buildLog2() {
  2388. const f = module.addFunction(prefix+"__log2");
  2389. f.addParam("n", "i32");
  2390. f.setReturnType("i32");
  2391. f.addLocal("bits", "i32");
  2392. f.addLocal("aux", "i32");
  2393. const c = f.getCodeBuilder();
  2394. f.addCode(
  2395. c.setLocal(
  2396. "aux",
  2397. c.i32_shr_u(
  2398. c.getLocal("n"),
  2399. c.i32_const(1)
  2400. )
  2401. )
  2402. );
  2403. f.addCode(c.setLocal("bits", c.i32_const(0)));
  2404. f.addCode(c.block(c.loop(
  2405. c.br_if(
  2406. 1,
  2407. c.i32_eqz(c.getLocal("aux"))
  2408. ),
  2409. c.setLocal(
  2410. "aux",
  2411. c.i32_shr_u(
  2412. c.getLocal("aux"),
  2413. c.i32_const(1)
  2414. )
  2415. ),
  2416. c.setLocal(
  2417. "bits",
  2418. c.i32_add(
  2419. c.getLocal("bits"),
  2420. c.i32_const(1)
  2421. )
  2422. ),
  2423. c.br(0)
  2424. )));
  2425. f.addCode(c.if(
  2426. c.i32_ne(
  2427. c.getLocal("n"),
  2428. c.i32_shl(
  2429. c.i32_const(1),
  2430. c.getLocal("bits")
  2431. )
  2432. ),
  2433. c.unreachable()
  2434. ));
  2435. f.addCode(c.if(
  2436. c.i32_gt_u(
  2437. c.getLocal("bits"),
  2438. c.i32_const(maxBits)
  2439. ),
  2440. c.unreachable()
  2441. ));
  2442. f.addCode(c.getLocal("bits"));
  2443. }
  2444. function buildFFT() {
  2445. const f = module.addFunction(prefix+"_fft");
  2446. f.addParam("px", "i32");
  2447. f.addParam("n", "i32");
  2448. f.addParam("odd", "i32");
  2449. f.addLocal("bits", "i32");
  2450. const c = f.getCodeBuilder();
  2451. f.addCode(
  2452. c.setLocal(
  2453. "bits",
  2454. c.call(
  2455. prefix + "__log2",
  2456. c.getLocal("n")
  2457. )
  2458. )
  2459. );
  2460. f.addCode(c.call(
  2461. prefix+"__rawfft",
  2462. c.getLocal("px"),
  2463. c.getLocal("bits"),
  2464. c.getLocal("odd"),
  2465. ));
  2466. }
  2467. function buildIFFT() {
  2468. const f = module.addFunction(prefix+"_ifft");
  2469. f.addParam("px", "i32");
  2470. f.addParam("n", "i32");
  2471. f.addParam("odd", "i32");
  2472. f.addLocal("bits", "i32");
  2473. const c = f.getCodeBuilder();
  2474. f.addCode(
  2475. c.setLocal(
  2476. "bits",
  2477. c.call(
  2478. prefix + "__log2",
  2479. c.getLocal("n")
  2480. )
  2481. )
  2482. );
  2483. f.addCode(c.call(
  2484. prefix+"__rawfft",
  2485. c.getLocal("px"),
  2486. c.getLocal("bits"),
  2487. c.getLocal("odd")
  2488. ));
  2489. f.addCode(c.call(
  2490. prefix+"__finalInverse",
  2491. c.getLocal("px"),
  2492. c.getLocal("bits"),
  2493. ));
  2494. }
  2495. function buildRawFFT() {
  2496. const f = module.addFunction(prefix+"__rawfft");
  2497. f.addParam("px", "i32");
  2498. f.addParam("bits", "i32");
  2499. f.addParam("odd", "i32");
  2500. f.addLocal("s", "i32");
  2501. f.addLocal("k", "i32");
  2502. f.addLocal("j", "i32");
  2503. f.addLocal("m", "i32");
  2504. f.addLocal("mdiv2", "i32");
  2505. f.addLocal("n", "i32");
  2506. f.addLocal("pwm", "i32");
  2507. f.addLocal("idx1", "i32");
  2508. f.addLocal("idx2", "i32");
  2509. const c = f.getCodeBuilder();
  2510. const W = c.i32_const(module.alloc(n8));
  2511. const T = c.i32_const(module.alloc(n8));
  2512. const U = c.i32_const(module.alloc(n8));
  2513. f.addCode(
  2514. c.call(prefix + "__reversePermutation", c.getLocal("px"), c.getLocal("bits")),
  2515. c.setLocal("n", c.i32_shl(c.i32_const(1), c.getLocal("bits"))),
  2516. c.setLocal("s", c.i32_const(1)),
  2517. c.block(c.loop(
  2518. c.br_if(
  2519. 1,
  2520. c.i32_gt_u(
  2521. c.getLocal("s"),
  2522. c.getLocal("bits")
  2523. )
  2524. ),
  2525. c.setLocal("m", c.i32_shl(c.i32_const(1), c.getLocal("s"))),
  2526. c.setLocal("pwm",
  2527. c.i32_add(
  2528. c.i32_const(ROOTs),
  2529. c.i32_mul(
  2530. c.getLocal("s"),
  2531. c.i32_const(n8)
  2532. )
  2533. )
  2534. ),
  2535. c.setLocal("k", c.i32_const(0)),
  2536. c.block(c.loop(
  2537. c.br_if(
  2538. 1,
  2539. c.i32_ge_u(
  2540. c.getLocal("k"),
  2541. c.getLocal("n")
  2542. )
  2543. ),
  2544. c.if(
  2545. c.getLocal("odd"),
  2546. c.call(
  2547. f1mPrefix + "_copy",
  2548. c.i32_add(
  2549. c.getLocal("pwm"),
  2550. c.i32_const(n8)
  2551. ),
  2552. W
  2553. ),
  2554. c.call(f1mPrefix + "_one", W)
  2555. ),
  2556. c.setLocal("mdiv2", c.i32_shr_u(c.getLocal("m"), c.i32_const(1)) ),
  2557. c.setLocal("j", c.i32_const(0)),
  2558. c.block(c.loop(
  2559. c.br_if(
  2560. 1,
  2561. c.i32_ge_u(
  2562. c.getLocal("j"),
  2563. c.getLocal("mdiv2")
  2564. )
  2565. ),
  2566. c.setLocal(
  2567. "idx1",
  2568. c.i32_add(
  2569. c.getLocal("px"),
  2570. c.i32_mul(
  2571. c.i32_add(
  2572. c.getLocal("k"),
  2573. c.getLocal("j")
  2574. ),
  2575. c.i32_const(n8)
  2576. )
  2577. )
  2578. ),
  2579. c.setLocal(
  2580. "idx2",
  2581. c.i32_add(
  2582. c.getLocal("idx1"),
  2583. c.i32_mul(
  2584. c.getLocal("mdiv2"),
  2585. c.i32_const(n8)
  2586. )
  2587. )
  2588. ),
  2589. c.call(
  2590. f1mPrefix + "_mul",
  2591. W,
  2592. c.getLocal("idx2"),
  2593. T
  2594. ),
  2595. c.call(
  2596. f1mPrefix + "_copy",
  2597. c.getLocal("idx1"),
  2598. U
  2599. ),
  2600. c.call(
  2601. f1mPrefix + "_add",
  2602. U,
  2603. T,
  2604. c.getLocal("idx1"),
  2605. ),
  2606. c.call(
  2607. f1mPrefix + "_sub",
  2608. U,
  2609. T,
  2610. c.getLocal("idx2"),
  2611. ),
  2612. c.call(
  2613. f1mPrefix + "_mul",
  2614. W,
  2615. c.getLocal("pwm"),
  2616. W,
  2617. ),
  2618. c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))),
  2619. c.br(0)
  2620. )),
  2621. c.setLocal("k", c.i32_add(c.getLocal("k"), c.getLocal("m"))),
  2622. c.br(0)
  2623. )),
  2624. c.setLocal("s", c.i32_add(c.getLocal("s"), c.i32_const(1))),
  2625. c.br(0)
  2626. ))
  2627. );
  2628. }
  2629. function buildCopyInterleaved() {
  2630. const f = module.addFunction(prefix+"_copyNInterleaved");
  2631. f.addParam("ps", "i32");
  2632. f.addParam("pd", "i32");
  2633. f.addParam("n", "i32");
  2634. f.addLocal("pi", "i32");
  2635. f.addLocal("po", "i32");
  2636. f.addLocal("pn", "i32");
  2637. const c = f.getCodeBuilder();
  2638. f.addCode(
  2639. c.setLocal("pi", c.getLocal("ps")),
  2640. c.setLocal("po", c.getLocal("pd")),
  2641. c.setLocal(
  2642. "pn",
  2643. c.i32_add(
  2644. c.getLocal("ps"),
  2645. c.i32_mul(
  2646. c.getLocal("n"),
  2647. c.i32_const(n8)
  2648. )
  2649. )
  2650. ),
  2651. c.block(c.loop(
  2652. c.br_if(
  2653. 1,
  2654. c.i32_eq(
  2655. c.getLocal("pi"),
  2656. c.getLocal("pn")
  2657. )
  2658. ),
  2659. c.call(f1mPrefix + "_copy", c.getLocal("pi"), c.getLocal("po")),
  2660. c.setLocal("pi", c.i32_add(c.getLocal("pi"), c.i32_const(n8))),
  2661. c.setLocal("po", c.i32_add(c.getLocal("po"), c.i32_const(n8*2))),
  2662. c.br(0)
  2663. ))
  2664. );
  2665. }
  2666. function buildToMontgomery() {
  2667. const f = module.addFunction(prefix+"_toMontgomeryN");
  2668. f.addParam("ps", "i32");
  2669. f.addParam("pd", "i32");
  2670. f.addParam("n", "i32");
  2671. f.addLocal("pi", "i32");
  2672. f.addLocal("po", "i32");
  2673. f.addLocal("pn", "i32");
  2674. const c = f.getCodeBuilder();
  2675. f.addCode(
  2676. c.setLocal("pi", c.getLocal("ps")),
  2677. c.setLocal("po", c.getLocal("pd")),
  2678. c.setLocal(
  2679. "pn",
  2680. c.i32_add(
  2681. c.getLocal("ps"),
  2682. c.i32_mul(
  2683. c.getLocal("n"),
  2684. c.i32_const(n8)
  2685. )
  2686. )
  2687. ),
  2688. c.block(c.loop(
  2689. c.br_if(
  2690. 1,
  2691. c.i32_eq(
  2692. c.getLocal("pi"),
  2693. c.getLocal("pn")
  2694. )
  2695. ),
  2696. c.call(f1mPrefix + "_toMontgomery", c.getLocal("pi"), c.getLocal("po")),
  2697. c.setLocal("pi", c.i32_add(c.getLocal("pi"), c.i32_const(n8))),
  2698. c.setLocal("po", c.i32_add(c.getLocal("po"), c.i32_const(n8))),
  2699. c.br(0)
  2700. ))
  2701. );
  2702. }
  2703. function buildMulN() {
  2704. const f = module.addFunction(prefix+"_mulN");
  2705. f.addParam("px", "i32");
  2706. f.addParam("py", "i32");
  2707. f.addParam("n", "i32");
  2708. f.addParam("pd", "i32");
  2709. f.addLocal("pix", "i32");
  2710. f.addLocal("piy", "i32");
  2711. f.addLocal("po", "i32");
  2712. f.addLocal("lastpix", "i32");
  2713. const c = f.getCodeBuilder();
  2714. f.addCode(
  2715. c.setLocal("pix", c.getLocal("px")),
  2716. c.setLocal("piy", c.getLocal("py")),
  2717. c.setLocal("po", c.getLocal("pd")),
  2718. c.setLocal(
  2719. "lastpix",
  2720. c.i32_add(
  2721. c.getLocal("px"),
  2722. c.i32_mul(
  2723. c.getLocal("n"),
  2724. c.i32_const(n8)
  2725. )
  2726. )
  2727. ),
  2728. c.block(c.loop(
  2729. c.br_if(
  2730. 1,
  2731. c.i32_eq(
  2732. c.getLocal("pix"),
  2733. c.getLocal("lastpix")
  2734. )
  2735. ),
  2736. c.call(f1mPrefix + "_mul", c.getLocal("pix"), c.getLocal("piy"), c.getLocal("po")),
  2737. c.setLocal("pix", c.i32_add(c.getLocal("pix"), c.i32_const(n8))),
  2738. c.setLocal("piy", c.i32_add(c.getLocal("piy"), c.i32_const(n8))),
  2739. c.setLocal("po", c.i32_add(c.getLocal("po"), c.i32_const(n8))),
  2740. c.br(0)
  2741. ))
  2742. );
  2743. }
  2744. function buildFromMontgomery() {
  2745. const f = module.addFunction(prefix+"_fromMontgomeryN");
  2746. f.addParam("ps", "i32");
  2747. f.addParam("pd", "i32");
  2748. f.addParam("n", "i32");
  2749. f.addLocal("pi", "i32");
  2750. f.addLocal("po", "i32");
  2751. f.addLocal("pn", "i32");
  2752. const c = f.getCodeBuilder();
  2753. f.addCode(
  2754. c.setLocal("pi", c.getLocal("ps")),
  2755. c.setLocal("po", c.getLocal("pd")),
  2756. c.setLocal(
  2757. "pn",
  2758. c.i32_add(
  2759. c.getLocal("ps"),
  2760. c.i32_mul(
  2761. c.getLocal("n"),
  2762. c.i32_const(n8)
  2763. )
  2764. )
  2765. ),
  2766. c.block(c.loop(
  2767. c.br_if(
  2768. 1,
  2769. c.i32_eq(
  2770. c.getLocal("pi"),
  2771. c.getLocal("pn")
  2772. )
  2773. ),
  2774. c.call(f1mPrefix + "_fromMontgomery", c.getLocal("pi"), c.getLocal("po")),
  2775. c.setLocal("pi", c.i32_add(c.getLocal("pi"), c.i32_const(n8))),
  2776. c.setLocal("po", c.i32_add(c.getLocal("po"), c.i32_const(n8))),
  2777. c.br(0)
  2778. ))
  2779. );
  2780. }
  2781. function buildFinalInverse() {
  2782. const f = module.addFunction(prefix+"__finalInverse");
  2783. f.addParam("px", "i32");
  2784. f.addParam("bits", "i32");
  2785. f.addLocal("n", "i32");
  2786. f.addLocal("ndiv2", "i32");
  2787. f.addLocal("pInv2", "i32");
  2788. f.addLocal("i", "i32");
  2789. f.addLocal("mask", "i32");
  2790. f.addLocal("idx1", "i32");
  2791. f.addLocal("idx2", "i32");
  2792. const c = f.getCodeBuilder();
  2793. const T = c.i32_const(module.alloc(n8));
  2794. f.addCode(
  2795. c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))),
  2796. c.setLocal(
  2797. "pInv2",
  2798. c.i32_add(
  2799. c.i32_const(INV2),
  2800. c.i32_mul(
  2801. c.getLocal("bits"),
  2802. c.i32_const(n8)
  2803. )
  2804. )
  2805. ),
  2806. c.setLocal("mask", c.i32_sub( c.getLocal("n") , c.i32_const(1))),
  2807. c.setLocal("i", c.i32_const(1)),
  2808. c.setLocal(
  2809. "ndiv2",
  2810. c.i32_shr_u(
  2811. c.getLocal("n"),
  2812. c.i32_const(1)
  2813. )
  2814. ),
  2815. c.block(c.loop(
  2816. c.br_if(
  2817. 1,
  2818. c.i32_eq(
  2819. c.getLocal("i"),
  2820. c.getLocal("ndiv2")
  2821. )
  2822. ),
  2823. c.setLocal("idx1",
  2824. c.i32_add(
  2825. c.getLocal("px"),
  2826. c.i32_mul(
  2827. c.getLocal("i"),
  2828. c.i32_const(n8)
  2829. )
  2830. )
  2831. ),
  2832. c.setLocal("idx2",
  2833. c.i32_add(
  2834. c.getLocal("px"),
  2835. c.i32_mul(
  2836. c.i32_sub(
  2837. c.getLocal("n"),
  2838. c.getLocal("i")
  2839. ),
  2840. c.i32_const(n8)
  2841. )
  2842. )
  2843. ),
  2844. c.call(f1mPrefix + "_copy", c.getLocal("idx1"), T),
  2845. c.call(f1mPrefix + "_mul", c.getLocal("idx2") , c.getLocal("pInv2"), c.getLocal("idx1") ),
  2846. c.call(f1mPrefix + "_mul", T , c.getLocal("pInv2"), c.getLocal("idx2")),
  2847. // c.call(f1mPrefix + "_mul", c.getLocal("idx1") , c.getLocal("pInv2"), c.getLocal("idx1") ),
  2848. // c.call(f1mPrefix + "_mul", c.getLocal("idx2") , c.getLocal("pInv2"), c.getLocal("idx1") ),
  2849. c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))),
  2850. c.br(0)
  2851. )),
  2852. c.call(f1mPrefix + "_mul", c.getLocal("px") , c.getLocal("pInv2"), c.getLocal("px")),
  2853. c.setLocal("idx2",
  2854. c.i32_add(
  2855. c.getLocal("px"),
  2856. c.i32_mul(
  2857. c.getLocal("ndiv2"),
  2858. c.i32_const(n8)
  2859. )
  2860. )
  2861. ),
  2862. c.call(f1mPrefix + "_mul", c.getLocal("idx2"),c.getLocal("pInv2"), c.getLocal("idx2"))
  2863. );
  2864. }
  2865. function buildReversePermutation() {
  2866. const f = module.addFunction(prefix+"__reversePermutation");
  2867. f.addParam("px", "i32");
  2868. f.addParam("bits", "i32");
  2869. f.addLocal("n", "i32");
  2870. f.addLocal("i", "i32");
  2871. f.addLocal("ri", "i32");
  2872. f.addLocal("idx1", "i32");
  2873. f.addLocal("idx2", "i32");
  2874. const c = f.getCodeBuilder();
  2875. const T = c.i32_const(module.alloc(n8));
  2876. f.addCode(
  2877. c.setLocal("n", c.i32_shl( c.i32_const(1), c.getLocal("bits"))),
  2878. c.setLocal("i", c.i32_const(0)),
  2879. c.block(c.loop(
  2880. c.br_if(
  2881. 1,
  2882. c.i32_eq(
  2883. c.getLocal("i"),
  2884. c.getLocal("n")
  2885. )
  2886. ),
  2887. c.setLocal("idx1",
  2888. c.i32_add(
  2889. c.getLocal("px"),
  2890. c.i32_mul(
  2891. c.getLocal("i"),
  2892. c.i32_const(n8)
  2893. )
  2894. )
  2895. ),
  2896. c.setLocal("ri", c.call(prefix + "__rev", c.getLocal("i"), c.getLocal("bits"))),
  2897. c.setLocal("idx2",
  2898. c.i32_add(
  2899. c.getLocal("px"),
  2900. c.i32_mul(
  2901. c.getLocal("ri"),
  2902. c.i32_const(n8)
  2903. )
  2904. )
  2905. ),
  2906. c.if(
  2907. c.i32_lt_u(
  2908. c.getLocal("i"),
  2909. c.getLocal("ri")
  2910. ),
  2911. [
  2912. ...c.call(f1mPrefix + "_copy", c.getLocal("idx1"), T),
  2913. ...c.call(f1mPrefix + "_copy", c.getLocal("idx2") , c.getLocal("idx1")),
  2914. ...c.call(f1mPrefix + "_copy", T , c.getLocal("idx2"))
  2915. ]
  2916. ),
  2917. c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))),
  2918. c.br(0)
  2919. ))
  2920. );
  2921. }
  2922. function buildRev() {
  2923. const f = module.addFunction(prefix+"__rev");
  2924. f.addParam("x", "i32");
  2925. f.addParam("bits", "i32");
  2926. f.setReturnType("i32");
  2927. const c = f.getCodeBuilder();
  2928. f.addCode(
  2929. c.i32_rotl(
  2930. c.i32_add(
  2931. c.i32_add(
  2932. c.i32_shl(
  2933. c.i32_load8_u(
  2934. c.i32_and(
  2935. c.getLocal("x"),
  2936. c.i32_const(0xFF)
  2937. ),
  2938. REVTABLE,
  2939. 0
  2940. ),
  2941. c.i32_const(24)
  2942. ),
  2943. c.i32_shl(
  2944. c.i32_load8_u(
  2945. c.i32_and(
  2946. c.i32_shr_u(
  2947. c.getLocal("x"),
  2948. c.i32_const(8)
  2949. ),
  2950. c.i32_const(0xFF)
  2951. ),
  2952. REVTABLE,
  2953. 0
  2954. ),
  2955. c.i32_const(16)
  2956. ),
  2957. ),
  2958. c.i32_add(
  2959. c.i32_shl(
  2960. c.i32_load8_u(
  2961. c.i32_and(
  2962. c.i32_shr_u(
  2963. c.getLocal("x"),
  2964. c.i32_const(16)
  2965. ),
  2966. c.i32_const(0xFF)
  2967. ),
  2968. REVTABLE,
  2969. 0
  2970. ),
  2971. c.i32_const(8)
  2972. ),
  2973. c.i32_load8_u(
  2974. c.i32_and(
  2975. c.i32_shr_u(
  2976. c.getLocal("x"),
  2977. c.i32_const(24)
  2978. ),
  2979. c.i32_const(0xFF)
  2980. ),
  2981. REVTABLE,
  2982. 0
  2983. ),
  2984. )
  2985. ),
  2986. c.getLocal("bits")
  2987. )
  2988. );
  2989. }
  2990. buildRev();
  2991. buildReversePermutation();
  2992. buildRawFFT();
  2993. buildCopyInterleaved();
  2994. buildFromMontgomery();
  2995. buildToMontgomery();
  2996. buildFinalInverse();
  2997. buildLog2();
  2998. buildFFT();
  2999. buildIFFT();
  3000. buildMulN();
  3001. module.exportFunction(prefix+"_fft");
  3002. module.exportFunction(prefix+"_ifft");
  3003. module.exportFunction(prefix+"_toMontgomeryN");
  3004. module.exportFunction(prefix+"_fromMontgomeryN");
  3005. module.exportFunction(prefix+"_copyNInterleaved");
  3006. module.exportFunction(prefix+"_mulN");
  3007. };
  3008. },{"./utils.js":17,"big-integer":2}],9:[function(require,module,exports){
  3009. const utils = require("./utils.js");
  3010. module.exports = function buildInt(module, n64, _prefix) {
  3011. const prefix = _prefix || "int";
  3012. if (module.modules[prefix]) return prefix; // already builded
  3013. module.modules[prefix] = {};
  3014. const n32 = n64*2;
  3015. const n8 = n64*8;
  3016. const one = module.alloc(n8, utils.bigInt2BytesLE(1, n8));
  3017. function buildCopy() {
  3018. const f = module.addFunction(prefix+"_copy");
  3019. f.addParam("px", "i32");
  3020. f.addParam("pr", "i32");
  3021. const c = f.getCodeBuilder();
  3022. for (let i=0; i<n64; i++) {
  3023. f.addCode(
  3024. c.i64_store(
  3025. c.getLocal("pr"),
  3026. i*8,
  3027. c.i64_load(
  3028. c.getLocal("px"),
  3029. i*8
  3030. )
  3031. )
  3032. );
  3033. }
  3034. }
  3035. function buildZero() {
  3036. const f = module.addFunction(prefix+"_zero");
  3037. f.addParam("pr", "i32");
  3038. const c = f.getCodeBuilder();
  3039. for (let i=0; i<n64; i++) {
  3040. f.addCode(
  3041. c.i64_store(
  3042. c.getLocal("pr"),
  3043. i*8,
  3044. c.i64_const(0)
  3045. )
  3046. );
  3047. }
  3048. }
  3049. function buildOne() {
  3050. const f = module.addFunction(prefix+"_one");
  3051. f.addParam("pr", "i32");
  3052. const c = f.getCodeBuilder();
  3053. f.addCode(
  3054. c.i64_store(
  3055. c.getLocal("pr"),
  3056. 0,
  3057. c.i64_const(1)
  3058. )
  3059. );
  3060. for (let i=1; i<n64; i++) {
  3061. f.addCode(
  3062. c.i64_store(
  3063. c.getLocal("pr"),
  3064. i*8,
  3065. c.i64_const(0)
  3066. )
  3067. );
  3068. }
  3069. }
  3070. function buildIsZero() {
  3071. const f = module.addFunction(prefix+"_isZero");
  3072. f.addParam("px", "i32");
  3073. f.setReturnType("i32");
  3074. const c = f.getCodeBuilder();
  3075. function getCompCode(n) {
  3076. if (n==0) {
  3077. return c.ret(c.i64_eqz(
  3078. c.i64_load(c.getLocal("px"))
  3079. ));
  3080. }
  3081. return c.if(
  3082. c.i64_eqz(
  3083. c.i64_load(c.getLocal("px"), n*8 )
  3084. ),
  3085. getCompCode(n-1),
  3086. c.ret(c.i32_const(0))
  3087. );
  3088. }
  3089. f.addCode(getCompCode(n64-1));
  3090. f.addCode(c.ret(c.i32_const(0)));
  3091. }
  3092. function buildEq() {
  3093. const f = module.addFunction(prefix+"_eq");
  3094. f.addParam("px", "i32");
  3095. f.addParam("py", "i32");
  3096. f.setReturnType("i32");
  3097. const c = f.getCodeBuilder();
  3098. function getCompCode(n) {
  3099. if (n==0) {
  3100. return c.ret(c.i64_eq(
  3101. c.i64_load(c.getLocal("px")),
  3102. c.i64_load(c.getLocal("py"))
  3103. ));
  3104. }
  3105. return c.if(
  3106. c.i64_eq(
  3107. c.i64_load(c.getLocal("px"), n*8 ),
  3108. c.i64_load(c.getLocal("py"), n*8 )
  3109. ),
  3110. getCompCode(n-1),
  3111. c.ret(c.i32_const(0))
  3112. );
  3113. }
  3114. f.addCode(getCompCode(n64-1));
  3115. f.addCode(c.ret(c.i32_const(0)));
  3116. }
  3117. function buildGte() {
  3118. const f = module.addFunction(prefix+"_gte");
  3119. f.addParam("px", "i32");
  3120. f.addParam("py", "i32");
  3121. f.setReturnType("i32");
  3122. const c = f.getCodeBuilder();
  3123. function getCompCode(n) {
  3124. if (n==0) {
  3125. return c.ret(c.i64_ge_u(
  3126. c.i64_load(c.getLocal("px")),
  3127. c.i64_load(c.getLocal("py"))
  3128. ));
  3129. }
  3130. return c.if(
  3131. c.i64_lt_u(
  3132. c.i64_load(c.getLocal("px"), n*8 ),
  3133. c.i64_load(c.getLocal("py"), n*8 )
  3134. ),
  3135. c.ret(c.i32_const(0)),
  3136. c.if(
  3137. c.i64_gt_u(
  3138. c.i64_load(c.getLocal("px"), n*8 ),
  3139. c.i64_load(c.getLocal("py"), n*8 )
  3140. ),
  3141. c.ret(c.i32_const(1)),
  3142. getCompCode(n-1)
  3143. )
  3144. );
  3145. }
  3146. f.addCode(getCompCode(n64-1));
  3147. f.addCode(c.ret(c.i32_const(0)));
  3148. }
  3149. function buildAdd() {
  3150. const f = module.addFunction(prefix+"_add");
  3151. f.addParam("x", "i32");
  3152. f.addParam("y", "i32");
  3153. f.addParam("r", "i32");
  3154. f.setReturnType("i32");
  3155. f.addLocal("c", "i64");
  3156. const c = f.getCodeBuilder();
  3157. f.addCode(c.setLocal(
  3158. "c",
  3159. c.i64_add(
  3160. c.i64_load32_u(c.getLocal("x")),
  3161. c.i64_load32_u(c.getLocal("y"))
  3162. )
  3163. ));
  3164. f.addCode(c.i64_store32(
  3165. c.getLocal("r"),
  3166. c.getLocal("c"),
  3167. ));
  3168. for (let i=1; i<n32; i++) {
  3169. f.addCode(c.setLocal( "c",
  3170. c.i64_add(
  3171. c.i64_add(
  3172. c.i64_load32_u(c.getLocal("x"), 4*i),
  3173. c.i64_load32_u(c.getLocal("y"), 4*i)
  3174. ),
  3175. c.i64_shr_u (c.getLocal("c"), c.i64_const(32))
  3176. )
  3177. ));
  3178. f.addCode(c.i64_store32(
  3179. c.getLocal("r"),
  3180. i*4,
  3181. c.getLocal("c")
  3182. ));
  3183. }
  3184. f.addCode(c.i32_wrap_i64(c.i64_shr_u (c.getLocal("c"), c.i64_const(32))));
  3185. }
  3186. function buildSub() {
  3187. const f = module.addFunction(prefix+"_sub");
  3188. f.addParam("x", "i32");
  3189. f.addParam("y", "i32");
  3190. f.addParam("r", "i32");
  3191. f.setReturnType("i32");
  3192. f.addLocal("c", "i64");
  3193. const c = f.getCodeBuilder();
  3194. f.addCode(c.setLocal(
  3195. "c",
  3196. c.i64_sub(
  3197. c.i64_load32_u(c.getLocal("x")),
  3198. c.i64_load32_u(c.getLocal("y"))
  3199. )
  3200. ));
  3201. f.addCode(c.i64_store32(
  3202. c.getLocal("r"),
  3203. c.i64_and(
  3204. c.getLocal("c"),
  3205. c.i64_const("0xFFFFFFFF")
  3206. )
  3207. ));
  3208. for (let i=1; i<n32; i++) {
  3209. f.addCode(c.setLocal( "c",
  3210. c.i64_add(
  3211. c.i64_sub(
  3212. c.i64_load32_u(c.getLocal("x"), 4*i),
  3213. c.i64_load32_u(c.getLocal("y"), 4*i)
  3214. ),
  3215. c.i64_shr_s (c.getLocal("c"), c.i64_const(32))
  3216. )
  3217. ));
  3218. f.addCode(c.i64_store32(
  3219. c.getLocal("r"),
  3220. i*4,
  3221. c.i64_and( c.getLocal("c"), c.i64_const("0xFFFFFFFF"))
  3222. ));
  3223. }
  3224. f.addCode(c.i32_wrap_i64 ( c.i64_shr_s (c.getLocal("c"), c.i64_const(32))));
  3225. }
  3226. function buildMul() {
  3227. const mulBuff = module.alloc(n32*n32*8);
  3228. const f = module.addFunction(prefix+"_mul");
  3229. f.addParam("x", "i32");
  3230. f.addParam("y", "i32");
  3231. f.addParam("r", "i32");
  3232. f.addLocal("c", "i64");
  3233. const c = f.getCodeBuilder();
  3234. for (let i=0; i<n32; i++) {
  3235. for (let j=0; j<n32; j++) {
  3236. f.addCode(c.i64_store(
  3237. c.i32_const(mulBuff),
  3238. (i*n32+j)*8,
  3239. c.i64_mul(
  3240. c.i64_load32_u( c.getLocal("x"), i*4),
  3241. c.i64_load32_u( c.getLocal("y"), j*4)
  3242. )
  3243. ));
  3244. }
  3245. }
  3246. for (let i=0; i<n32; i++) {
  3247. f.addCode(c.i64_shr_u(c.getLocal("c"), c.i64_const(32)));
  3248. for (let j=0; j<i; j++) {
  3249. f.addCode(c.i64_add(
  3250. [],
  3251. c.i64_load32_u(
  3252. c.i32_const(mulBuff),
  3253. j*(n32*8) + i*8-4 - j*8
  3254. )
  3255. ));
  3256. }
  3257. for (let j=0; j<i+1; j++) {
  3258. f.addCode(c.i64_add(
  3259. [],
  3260. c.i64_load32_u(
  3261. c.i32_const(mulBuff),
  3262. j*(n32*8) + i*8 - j*8
  3263. )
  3264. ));
  3265. }
  3266. f.addCode(c.setLocal("c", []));
  3267. f.addCode(
  3268. c.i64_store32(
  3269. c.getLocal("r"),
  3270. i*4,
  3271. c.getLocal("c")
  3272. )
  3273. );
  3274. }
  3275. for (let i=0; i<n32; i++) {
  3276. f.addCode(c.i64_shr_u(c.getLocal("c"), c.i64_const(32)));
  3277. for (let j=i; j<n32; j++) {
  3278. f.addCode(c.i64_add(
  3279. [],
  3280. c.i64_load32_u(
  3281. c.i32_const(mulBuff),
  3282. j*(n32*8) + n32*8-4 + i*8- j*8
  3283. )
  3284. ));
  3285. }
  3286. for (let j=i+1; j<n32; j++) {
  3287. f.addCode(c.i64_add(
  3288. [],
  3289. c.i64_load32_u(
  3290. c.i32_const(mulBuff),
  3291. j*(n32*8) + n32*8 + i*8 - j*8
  3292. )
  3293. ));
  3294. }
  3295. f.addCode(c.setLocal("c", []));
  3296. f.addCode(
  3297. c.i64_store32(
  3298. c.getLocal("r"),
  3299. i*4 + n32*4,
  3300. c.getLocal("c")
  3301. )
  3302. );
  3303. }
  3304. }
  3305. function _buildMul1() {
  3306. const f = module.addFunction(prefix+"__mul1");
  3307. f.addParam("px", "i32");
  3308. f.addParam("y", "i64");
  3309. f.addParam("pr", "i32");
  3310. f.addLocal("c", "i64");
  3311. const c = f.getCodeBuilder();
  3312. f.addCode(c.setLocal(
  3313. "c",
  3314. c.i64_mul(
  3315. c.i64_load32_u(c.getLocal("px"), 0, 0),
  3316. c.getLocal("y")
  3317. )
  3318. ));
  3319. f.addCode(c.i64_store32(
  3320. c.getLocal("pr"),
  3321. 0,
  3322. 0,
  3323. c.getLocal("c"),
  3324. ));
  3325. for (let i=1; i<n32; i++) {
  3326. f.addCode(c.setLocal( "c",
  3327. c.i64_add(
  3328. c.i64_mul(
  3329. c.i64_load32_u(c.getLocal("px"), 4*i, 0),
  3330. c.getLocal("y")
  3331. ),
  3332. c.i64_shr_u (c.getLocal("c"), c.i64_const(32))
  3333. )
  3334. ));
  3335. f.addCode(c.i64_store32(
  3336. c.getLocal("pr"),
  3337. i*4,
  3338. 0,
  3339. c.getLocal("c")
  3340. ));
  3341. }
  3342. }
  3343. function _buildAdd1() {
  3344. const f = module.addFunction(prefix+"__add1");
  3345. f.addParam("x", "i32");
  3346. f.addParam("y", "i64");
  3347. f.addLocal("c", "i64");
  3348. f.addLocal("px", "i32");
  3349. const c = f.getCodeBuilder();
  3350. f.addCode(c.setLocal("px", c.getLocal("x")));
  3351. f.addCode(c.setLocal(
  3352. "c",
  3353. c.i64_add(
  3354. c.i64_load32_u(c.getLocal("px"), 0, 0),
  3355. c.getLocal("y")
  3356. )
  3357. ));
  3358. f.addCode(c.i64_store32(
  3359. c.getLocal("px"),
  3360. 0,
  3361. 0,
  3362. c.getLocal("c"),
  3363. ));
  3364. f.addCode(c.setLocal(
  3365. "c",
  3366. c.i64_shr_u(
  3367. c.getLocal("c"),
  3368. c.i64_const(32)
  3369. )
  3370. ));
  3371. f.addCode(c.block(c.loop(
  3372. c.br_if(
  3373. 1,
  3374. c.i64_eqz(c.getLocal("c"))
  3375. ),
  3376. c.setLocal(
  3377. "px",
  3378. c.i32_add(
  3379. c.getLocal("px"),
  3380. c.i32_const(4)
  3381. )
  3382. ),
  3383. c.setLocal(
  3384. "c",
  3385. c.i64_add(
  3386. c.i64_load32_u(c.getLocal("px"), 0, 0),
  3387. c.getLocal("c")
  3388. )
  3389. ),
  3390. c.i64_store32(
  3391. c.getLocal("px"),
  3392. 0,
  3393. 0,
  3394. c.getLocal("c"),
  3395. ),
  3396. c.setLocal(
  3397. "c",
  3398. c.i64_shr_u(
  3399. c.getLocal("c"),
  3400. c.i64_const(32)
  3401. )
  3402. ),
  3403. c.br(0)
  3404. )));
  3405. }
  3406. function buildDiv() {
  3407. _buildMul1();
  3408. _buildAdd1();
  3409. const f = module.addFunction(prefix+"_div");
  3410. f.addParam("x", "i32");
  3411. f.addParam("y", "i32");
  3412. f.addParam("c", "i32");
  3413. f.addParam("r", "i32");
  3414. f.addLocal("rr", "i32");
  3415. f.addLocal("cc", "i32");
  3416. f.addLocal("eX", "i32");
  3417. f.addLocal("eY", "i32");
  3418. f.addLocal("sy", "i64");
  3419. f.addLocal("sx", "i64");
  3420. f.addLocal("ec", "i32");
  3421. const c = f.getCodeBuilder();
  3422. const Y = c.i32_const(module.alloc(n8));
  3423. const Caux = c.i32_const(module.alloc(n8));
  3424. const Raux = c.i32_const(module.alloc(n8));
  3425. const C = c.getLocal("cc");
  3426. const R = c.getLocal("rr");
  3427. const pr1 = module.alloc(n8*2);
  3428. const R1 = c.i32_const(pr1);
  3429. const R2 = c.i32_const(pr1+n8);
  3430. // Ic c is 0 then store it in an auxiliary buffer
  3431. f.addCode(c.if(
  3432. c.getLocal("c"),
  3433. c.setLocal("cc", c.getLocal("c")),
  3434. c.setLocal("cc", Caux)
  3435. ));
  3436. // Ic r is 0 then store it in an auxiliary buffer
  3437. f.addCode(c.if(
  3438. c.getLocal("r"),
  3439. c.setLocal("rr", c.getLocal("r")),
  3440. c.setLocal("rr", Raux)
  3441. ));
  3442. // Copy
  3443. f.addCode(c.call(prefix + "_copy", c.getLocal("x"), R));
  3444. f.addCode(c.call(prefix + "_copy", c.getLocal("y"), Y));
  3445. f.addCode(c.call(prefix + "_zero", C));
  3446. f.addCode(c.call(prefix + "_zero", R1));
  3447. f.addCode(c.setLocal("eX", c.i32_const(n8-1)));
  3448. f.addCode(c.setLocal("eY", c.i32_const(n8-1)));
  3449. // while (eY>3)&&(Y[eY]==0) ey--;
  3450. f.addCode(c.block(c.loop(
  3451. c.br_if(
  3452. 1,
  3453. c.i32_or(
  3454. c.i32_load8_u(
  3455. c.i32_add(Y , c.getLocal("eY")),
  3456. 0,
  3457. 0
  3458. ),
  3459. c.i32_eq(
  3460. c.getLocal("eY"),
  3461. c.i32_const(3)
  3462. )
  3463. )
  3464. ),
  3465. c.setLocal("eY", c.i32_sub(c.getLocal("eY"), c.i32_const(1))),
  3466. c.br(0)
  3467. )));
  3468. f.addCode(
  3469. c.setLocal(
  3470. "sy",
  3471. c.i64_add(
  3472. c.i64_load32_u(
  3473. c.i32_sub(
  3474. c.i32_add( Y, c.getLocal("eY")),
  3475. c.i32_const(3)
  3476. ),
  3477. 0,
  3478. 0
  3479. ),
  3480. c.i64_const(1)
  3481. )
  3482. )
  3483. );
  3484. // Force a divide by 0 if quotien is 0
  3485. f.addCode(
  3486. c.if(
  3487. c.i64_eq(
  3488. c.getLocal("sy"),
  3489. c.i64_const(1)
  3490. ),
  3491. c.drop(c.i64_div_u(c.i64_const(0), c.i64_const(0)))
  3492. )
  3493. );
  3494. f.addCode(c.block(c.loop(
  3495. // while (eX>7)&&(Y[eX]==0) ex--;
  3496. c.block(c.loop(
  3497. c.br_if(
  3498. 1,
  3499. c.i32_or(
  3500. c.i32_load8_u(
  3501. c.i32_add(R , c.getLocal("eX")),
  3502. 0,
  3503. 0
  3504. ),
  3505. c.i32_eq(
  3506. c.getLocal("eX"),
  3507. c.i32_const(7)
  3508. )
  3509. )
  3510. ),
  3511. c.setLocal("eX", c.i32_sub(c.getLocal("eX"), c.i32_const(1))),
  3512. c.br(0)
  3513. )),
  3514. c.setLocal(
  3515. "sx",
  3516. c.i64_load(
  3517. c.i32_sub(
  3518. c.i32_add( R, c.getLocal("eX")),
  3519. c.i32_const(7)
  3520. ),
  3521. 0,
  3522. 0
  3523. )
  3524. ),
  3525. c.setLocal(
  3526. "sx",
  3527. c.i64_div_u(
  3528. c.getLocal("sx"),
  3529. c.getLocal("sy")
  3530. )
  3531. ),
  3532. c.setLocal(
  3533. "ec",
  3534. c.i32_sub(
  3535. c.i32_sub(
  3536. c.getLocal("eX"),
  3537. c.getLocal("eY")
  3538. ),
  3539. c.i32_const(4)
  3540. )
  3541. ),
  3542. // While greater than 32 bits or ec is neg, shr and inc exp
  3543. c.block(c.loop(
  3544. c.br_if(
  3545. 1,
  3546. c.i32_and(
  3547. c.i64_eqz(
  3548. c.i64_and(
  3549. c.getLocal("sx"),
  3550. c.i64_const("0xFFFFFFFF00000000")
  3551. )
  3552. ),
  3553. c.i32_ge_s(
  3554. c.getLocal("ec"),
  3555. c.i32_const(0)
  3556. )
  3557. )
  3558. ),
  3559. c.setLocal(
  3560. "sx",
  3561. c.i64_shr_u(
  3562. c.getLocal("sx"),
  3563. c.i64_const(8)
  3564. )
  3565. ),
  3566. c.setLocal(
  3567. "ec",
  3568. c.i32_add(
  3569. c.getLocal("ec"),
  3570. c.i32_const(1)
  3571. )
  3572. ),
  3573. c.br(0)
  3574. )),
  3575. c.if(
  3576. c.i64_eqz(c.getLocal("sx")),
  3577. [
  3578. ...c.br_if(
  3579. 2,
  3580. c.i32_eqz(c.call(prefix + "_gte", R, Y))
  3581. ),
  3582. ...c.setLocal("sx", c.i64_const(1)),
  3583. ...c.setLocal("ec", c.i32_const(0))
  3584. ]
  3585. ),
  3586. c.call(prefix + "__mul1", Y, c.getLocal("sx"), R2),
  3587. c.drop(c.call(
  3588. prefix + "_sub",
  3589. R,
  3590. c.i32_sub(R2, c.getLocal("ec")),
  3591. R
  3592. )),
  3593. c.call(
  3594. prefix + "__add1",
  3595. c.i32_add(C, c.getLocal("ec")),
  3596. c.getLocal("sx")
  3597. ),
  3598. c.br(0)
  3599. )));
  3600. }
  3601. function buildInverseMod() {
  3602. const f = module.addFunction(prefix+"_inverseMod");
  3603. f.addParam("px", "i32");
  3604. f.addParam("pm", "i32");
  3605. f.addParam("pr", "i32");
  3606. f.addLocal("t", "i32");
  3607. f.addLocal("newt", "i32");
  3608. f.addLocal("r", "i32");
  3609. f.addLocal("qq", "i32");
  3610. f.addLocal("qr", "i32");
  3611. f.addLocal("newr", "i32");
  3612. f.addLocal("swp", "i32");
  3613. f.addLocal("x", "i32");
  3614. f.addLocal("signt", "i32");
  3615. f.addLocal("signnewt", "i32");
  3616. f.addLocal("signx", "i32");
  3617. const c = f.getCodeBuilder();
  3618. const aux1 = c.i32_const(module.alloc(n8));
  3619. const aux2 = c.i32_const(module.alloc(n8));
  3620. const aux3 = c.i32_const(module.alloc(n8));
  3621. const aux4 = c.i32_const(module.alloc(n8));
  3622. const aux5 = c.i32_const(module.alloc(n8));
  3623. const aux6 = c.i32_const(module.alloc(n8));
  3624. const mulBuff = c.i32_const(module.alloc(n8*2));
  3625. const aux7 = c.i32_const(module.alloc(n8));
  3626. f.addCode(
  3627. c.setLocal("t", aux1),
  3628. c.call(prefix + "_zero", aux1),
  3629. c.setLocal("signt", c.i32_const(0)),
  3630. );
  3631. f.addCode(
  3632. c.setLocal("r", aux2),
  3633. c.call(prefix + "_copy", c.getLocal("pm"), aux2)
  3634. );
  3635. f.addCode(
  3636. c.setLocal("newt", aux3),
  3637. c.call(prefix + "_one", aux3),
  3638. c.setLocal("signnewt", c.i32_const(0)),
  3639. );
  3640. f.addCode(
  3641. c.setLocal("newr", aux4),
  3642. c.call(prefix + "_copy", c.getLocal("px"), aux4)
  3643. );
  3644. f.addCode(c.setLocal("qq", aux5));
  3645. f.addCode(c.setLocal("qr", aux6));
  3646. f.addCode(c.setLocal("x", aux7));
  3647. f.addCode(c.block(c.loop(
  3648. c.br_if(
  3649. 1,
  3650. c.call(prefix + "_isZero", c.getLocal("newr") )
  3651. ),
  3652. c.call(prefix + "_div", c.getLocal("r"), c.getLocal("newr"), c.getLocal("qq"), c.getLocal("qr")),
  3653. c.call(prefix + "_mul", c.getLocal("qq"), c.getLocal("newt"), mulBuff),
  3654. c.if(
  3655. c.getLocal("signt"),
  3656. c.if(
  3657. c.getLocal("signnewt"),
  3658. c.if (
  3659. c.call(prefix + "_gte", mulBuff, c.getLocal("t")),
  3660. [
  3661. ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))),
  3662. ...c.setLocal("signx", c.i32_const(0))
  3663. ],
  3664. [
  3665. ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))),
  3666. ...c.setLocal("signx", c.i32_const(1))
  3667. ],
  3668. ),
  3669. [
  3670. ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))),
  3671. ...c.setLocal("signx", c.i32_const(1))
  3672. ]
  3673. ),
  3674. c.if(
  3675. c.getLocal("signnewt"),
  3676. [
  3677. ...c.drop(c.call(prefix + "_add", mulBuff, c.getLocal("t"), c.getLocal("x"))),
  3678. ...c.setLocal("signx", c.i32_const(0))
  3679. ],
  3680. c.if (
  3681. c.call(prefix + "_gte", c.getLocal("t"), mulBuff),
  3682. [
  3683. ...c.drop(c.call(prefix + "_sub", c.getLocal("t"), mulBuff, c.getLocal("x"))),
  3684. ...c.setLocal("signx", c.i32_const(0))
  3685. ],
  3686. [
  3687. ...c.drop(c.call(prefix + "_sub", mulBuff, c.getLocal("t"), c.getLocal("x"))),
  3688. ...c.setLocal("signx", c.i32_const(1))
  3689. ]
  3690. )
  3691. )
  3692. ),
  3693. c.setLocal("swp", c.getLocal("t")),
  3694. c.setLocal("t", c.getLocal("newt")),
  3695. c.setLocal("newt", c.getLocal("x")),
  3696. c.setLocal("x", c.getLocal("swp")),
  3697. c.setLocal("signt", c.getLocal("signnewt")),
  3698. c.setLocal("signnewt", c.getLocal("signx")),
  3699. c.setLocal("swp", c.getLocal("r")),
  3700. c.setLocal("r", c.getLocal("newr")),
  3701. c.setLocal("newr", c.getLocal("qr")),
  3702. c.setLocal("qr", c.getLocal("swp")),
  3703. c.br(0)
  3704. )));
  3705. f.addCode(c.if(
  3706. c.getLocal("signt"),
  3707. c.drop(c.call(prefix + "_sub", c.getLocal("pm"), c.getLocal("t"), c.getLocal("pr"))),
  3708. c.call(prefix + "_copy", c.getLocal("t"), c.getLocal("pr"))
  3709. ));
  3710. }
  3711. buildCopy();
  3712. buildZero();
  3713. buildIsZero();
  3714. buildOne();
  3715. buildEq();
  3716. buildGte();
  3717. buildAdd();
  3718. buildSub();
  3719. buildMul();
  3720. buildDiv();
  3721. buildInverseMod();
  3722. module.exportFunction(prefix+"_copy");
  3723. module.exportFunction(prefix+"_zero");
  3724. module.exportFunction(prefix+"_one");
  3725. module.exportFunction(prefix+"_isZero");
  3726. module.exportFunction(prefix+"_eq");
  3727. module.exportFunction(prefix+"_gte");
  3728. module.exportFunction(prefix+"_add");
  3729. module.exportFunction(prefix+"_sub");
  3730. module.exportFunction(prefix+"_mul");
  3731. module.exportFunction(prefix+"_div");
  3732. module.exportFunction(prefix+"_inverseMod");
  3733. return prefix;
  3734. };
  3735. },{"./utils.js":17}],10:[function(require,module,exports){
  3736. module.exports = function buildMultiexp(module, prefix, curvePrefix, pointFieldPrefix, scalarPrefix) {
  3737. const pointFieldN64 = module.modules[pointFieldPrefix].n64;
  3738. const pointFieldN8 = pointFieldN64*8;
  3739. const pointN64 = module.modules[curvePrefix].n64;
  3740. const pointN8 = pointN64*8;
  3741. const scalarN64 = module.modules[scalarPrefix].n64;
  3742. const scalarN8 = scalarN64*8;
  3743. function buildPackBits() {
  3744. const f = module.addFunction(prefix+"__packbits");
  3745. f.addParam("pscalars", "i32");
  3746. f.addParam("w", "i32"); // 8 max
  3747. f.addParam("pr", "i32"); // P to result scalarN8*8 bytes
  3748. f.addLocal("i", "i32");
  3749. f.addLocal("j", "i32");
  3750. f.addLocal("w1", "i64");
  3751. f.addLocal("w2", "i64");
  3752. const c = f.getCodeBuilder();
  3753. f.addCode(c.setLocal("i", c.i32_const(0)));
  3754. f.addCode(c.block(c.loop(
  3755. c.br_if(
  3756. 1,
  3757. c.i32_eq(
  3758. c.getLocal("i"),
  3759. c.i32_const(scalarN8)
  3760. )
  3761. ),
  3762. c.setLocal("w2", c.i64_const(0)),
  3763. c.setLocal("j", c.i32_const(0)),
  3764. c.block(c.loop(
  3765. c.br_if(
  3766. 1,
  3767. c.i32_eq(
  3768. c.getLocal("j"),
  3769. c.getLocal("w")
  3770. )
  3771. ),
  3772. c.setLocal(
  3773. "w1",
  3774. c.i64_load8_u(
  3775. c.i32_add(
  3776. c.getLocal("pscalars"),
  3777. c.i32_add(
  3778. c.i32_mul(
  3779. c.getLocal("j"),
  3780. c.i32_const(scalarN8)
  3781. ),
  3782. c.getLocal("i")
  3783. )
  3784. )
  3785. )
  3786. ),
  3787. c.setLocal(
  3788. "w1",
  3789. c.i64_and(
  3790. c.i64_or(
  3791. c.getLocal("w1"),
  3792. c.i64_shl(
  3793. c.getLocal("w1"),
  3794. c.i64_const(28)
  3795. )
  3796. ),
  3797. c.i64_const("0x0000000F0000000F")
  3798. )
  3799. ),
  3800. c.setLocal(
  3801. "w1",
  3802. c.i64_and(
  3803. c.i64_or(
  3804. c.getLocal("w1"),
  3805. c.i64_shl(
  3806. c.getLocal("w1"),
  3807. c.i64_const(14)
  3808. )
  3809. ),
  3810. c.i64_const("0x0003000300030003")
  3811. )
  3812. ),
  3813. c.setLocal(
  3814. "w1",
  3815. c.i64_and(
  3816. c.i64_or(
  3817. c.getLocal("w1"),
  3818. c.i64_shl(
  3819. c.getLocal("w1"),
  3820. c.i64_const(7)
  3821. )
  3822. ),
  3823. c.i64_const("0x0101010101010101")
  3824. )
  3825. ),
  3826. c.setLocal(
  3827. "w2",
  3828. c.i64_or(
  3829. c.getLocal("w2"),
  3830. c.i64_shl(
  3831. c.getLocal("w1"),
  3832. c.i64_extend_i32_u(c.getLocal("j"))
  3833. )
  3834. )
  3835. ),
  3836. c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))),
  3837. c.br(0)
  3838. )),
  3839. c.i64_store(
  3840. c.i32_add(
  3841. c.getLocal("pr"),
  3842. c.i32_mul(
  3843. c.getLocal("i"),
  3844. c.i32_const(8)
  3845. )
  3846. ),
  3847. c.getLocal("w2")
  3848. ),
  3849. c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))),
  3850. c.br(0)
  3851. )));
  3852. }
  3853. const c1 = [];
  3854. const c2 = [];
  3855. function nbits(_b) {
  3856. let c=0;
  3857. let r=_b;
  3858. while(r) {
  3859. if (r&1) c++;
  3860. r = r>>1;
  3861. }
  3862. return c;
  3863. }
  3864. function split(_b) {
  3865. const nb1 = nbits(_b) >> 1;
  3866. let r = _b;
  3867. let c = 0;
  3868. if (nb1 == 0) return null;
  3869. let mask = 0xFFFFFFFF;
  3870. while (c<nb1) {
  3871. if (r&1) c++;
  3872. mask = mask << 1;
  3873. r = r>>1;
  3874. }
  3875. return [(_b & mask), (_b & (~mask))];
  3876. }
  3877. for (let i=0; i<256; i++) {
  3878. const a = split(i);
  3879. if (a) {
  3880. c1[i] = a[0];
  3881. c2[i] = a[1];
  3882. } else {
  3883. c1[i] = 0;
  3884. c2[i] = 0;
  3885. }
  3886. }
  3887. const ptable = module.alloc(pointN8*256);
  3888. const pset = module.alloc(32);
  3889. const composite1 = module.alloc(256, c1);
  3890. const composite2 = module.alloc(256, c2);
  3891. function buildSetSet() {
  3892. const f = module.addFunction(prefix+"__set_set");
  3893. f.addParam("idx", "i32");
  3894. f.addLocal("word", "i32");
  3895. f.addLocal("mask", "i32");
  3896. const c = f.getCodeBuilder();
  3897. f.addCode(
  3898. c.setLocal(
  3899. "word",
  3900. c.i32_shl(
  3901. c.i32_shr_u(
  3902. c.getLocal("idx"),
  3903. c.i32_const(5)
  3904. ),
  3905. c.i32_const(2)
  3906. )
  3907. )
  3908. );
  3909. f.addCode(
  3910. c.setLocal(
  3911. "mask",
  3912. c.i32_shl(
  3913. c.i32_const(1),
  3914. c.i32_and(
  3915. c.getLocal("idx"),
  3916. c.i32_const("0x1F")
  3917. )
  3918. )
  3919. )
  3920. );
  3921. f.addCode(
  3922. c.i32_store(
  3923. c.getLocal("word"),
  3924. pset,
  3925. c.i32_or(
  3926. c.i32_load(
  3927. c.getLocal("word"),
  3928. pset
  3929. ),
  3930. c.getLocal("mask")
  3931. )
  3932. )
  3933. );
  3934. }
  3935. function buildSetIsSet() {
  3936. const f = module.addFunction(prefix+"__set_isSet");
  3937. f.addParam("idx", "i32");
  3938. f.setReturnType("i32");
  3939. f.addLocal("word", "i32");
  3940. f.addLocal("mask", "i32");
  3941. const c = f.getCodeBuilder();
  3942. f.addCode(
  3943. c.setLocal(
  3944. "word",
  3945. c.i32_shl(
  3946. c.i32_shr_u(
  3947. c.getLocal("idx"),
  3948. c.i32_const(5)
  3949. ),
  3950. c.i32_const(2)
  3951. )
  3952. )
  3953. );
  3954. f.addCode(
  3955. c.setLocal(
  3956. "mask",
  3957. c.i32_shl(
  3958. c.i32_const(1),
  3959. c.i32_and(
  3960. c.getLocal("idx"),
  3961. c.i32_const("0x1F")
  3962. )
  3963. )
  3964. )
  3965. );
  3966. f.addCode(
  3967. c.i32_and(
  3968. c.i32_load(
  3969. c.getLocal("word"),
  3970. pset
  3971. ),
  3972. c.getLocal("mask")
  3973. )
  3974. );
  3975. }
  3976. function buildPTableReset() {
  3977. const f = module.addFunction(prefix+"__ptable_reset");
  3978. f.addParam("ppoints", "i32");
  3979. f.addParam("w", "i32"); // Window size Max 8
  3980. f.addLocal("ps", "i32");
  3981. f.addLocal("pd", "i32");
  3982. f.addLocal("i", "i32");
  3983. f.addLocal("isZero", "i32");
  3984. const c = f.getCodeBuilder();
  3985. f.addCode(c.setLocal("ps", c.getLocal("ppoints")));
  3986. f.addCode(c.call( curvePrefix + "_zero", c.i32_const(ptable) ));
  3987. f.addCode(c.setLocal("i", c.i32_const(0)));
  3988. f.addCode(c.block(c.loop(
  3989. c.br_if(
  3990. 1,
  3991. c.i32_eq(
  3992. c.getLocal("i"),
  3993. c.getLocal("w")
  3994. )
  3995. ),
  3996. c.setLocal(
  3997. "pd",
  3998. c.i32_add(
  3999. c.i32_const(ptable),
  4000. c.i32_mul(
  4001. c.i32_shl(
  4002. c.i32_const(1),
  4003. c.getLocal("i")
  4004. ),
  4005. c.i32_const(pointN8)
  4006. )
  4007. )
  4008. ),
  4009. c.setLocal("isZero", c.call(pointFieldPrefix + "_isZero", c.getLocal("ps"))),
  4010. c.call( pointFieldPrefix + "_copy", c.getLocal("ps"), c.getLocal("pd")),
  4011. c.setLocal("ps", c.i32_add(c.getLocal("ps"), c.i32_const(pointFieldN8))),
  4012. c.setLocal("pd", c.i32_add(c.getLocal("pd"), c.i32_const(pointFieldN8))),
  4013. c.call( pointFieldPrefix + "_copy", c.getLocal("ps"), c.getLocal("pd")),
  4014. c.setLocal("ps", c.i32_add(c.getLocal("ps"), c.i32_const(pointFieldN8))),
  4015. c.setLocal("pd", c.i32_add(c.getLocal("pd"), c.i32_const(pointFieldN8))),
  4016. c.if(
  4017. c.getLocal("isZero"),
  4018. c.call( pointFieldPrefix + "_zero", c.getLocal("pd")),
  4019. c.call( pointFieldPrefix + "_one", c.getLocal("pd")),
  4020. ),
  4021. c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))),
  4022. c.br(0)
  4023. )));
  4024. // Reset the set
  4025. f.addCode(c.i64_store( c.i32_const(pset ),c.i64_const("0x0000000100010117")));
  4026. f.addCode(c.i64_store( c.i32_const(pset+ 8),c.i64_const("0x0000000000000001")));
  4027. f.addCode(c.i64_store( c.i32_const(pset+16),c.i64_const("0x0000000000000001")));
  4028. f.addCode(c.i64_store( c.i32_const(pset+24),c.i64_const("0x0000000000000000")));
  4029. }
  4030. function buildPTableGet() {
  4031. const f = module.addFunction(prefix+"__ptable_get");
  4032. f.addParam("idx", "i32");
  4033. f.setReturnType("i32");
  4034. f.addLocal("pr", "i32");
  4035. f.addLocal("p1", "i32");
  4036. f.addLocal("p2", "i32");
  4037. const c = f.getCodeBuilder();
  4038. f.addCode(
  4039. c.setLocal(
  4040. "pr",
  4041. c.i32_add(
  4042. c.i32_const(ptable),
  4043. c.i32_mul(
  4044. c.getLocal("idx"),
  4045. c.i32_const(pointN8)
  4046. )
  4047. )
  4048. )
  4049. );
  4050. f.addCode(c.if(
  4051. c.i32_eqz(
  4052. c.call(
  4053. prefix + "__set_isSet",
  4054. c.getLocal("idx")
  4055. ),
  4056. ),
  4057. [
  4058. ...c.setLocal(
  4059. "p1",
  4060. c.call(
  4061. prefix + "__ptable_get",
  4062. c.i32_load8_u(
  4063. c.getLocal("idx"),
  4064. composite1
  4065. )
  4066. )
  4067. ),
  4068. ...c.setLocal(
  4069. "p2",
  4070. c.call(
  4071. prefix + "__ptable_get",
  4072. c.i32_load8_u(
  4073. c.getLocal("idx"),
  4074. composite2
  4075. )
  4076. )
  4077. ),
  4078. ...c.call(
  4079. curvePrefix + "_add",
  4080. c.getLocal("p1"),
  4081. c.getLocal("p2"),
  4082. c.getLocal("pr")
  4083. ),
  4084. ...c.call(
  4085. prefix + "__set_set",
  4086. c.getLocal("idx")
  4087. )
  4088. ]
  4089. ));
  4090. f.addCode(c.getLocal("pr"));
  4091. }
  4092. function buildMulw() {
  4093. const f = module.addFunction(prefix+"__mulw");
  4094. f.addParam("pscalars", "i32");
  4095. f.addParam("ppoints", "i32");
  4096. f.addParam("w", "i32"); // Window size Max 8
  4097. f.addParam("pr", "i32");
  4098. f.addLocal("i", "i32");
  4099. const c = f.getCodeBuilder();
  4100. const psels = module.alloc(scalarN8 * 8);
  4101. f.addCode(c.call(
  4102. prefix + "__packbits",
  4103. c.getLocal("pscalars"),
  4104. c.getLocal("w"),
  4105. c.i32_const(psels)
  4106. ));
  4107. f.addCode(c.call(
  4108. curvePrefix + "_zero",
  4109. c.getLocal("pr"),
  4110. ));
  4111. f.addCode(c.call(
  4112. prefix + "__ptable_reset",
  4113. c.getLocal("ppoints"),
  4114. c.getLocal("w")
  4115. ));
  4116. f.addCode(c.setLocal("i", c.i32_const(0)));
  4117. f.addCode(c.block(c.loop(
  4118. c.br_if(
  4119. 1,
  4120. c.i32_eq(
  4121. c.getLocal("i"),
  4122. c.i32_const(scalarN8 * 8)
  4123. )
  4124. ),
  4125. c.call(curvePrefix + "_double",
  4126. c.getLocal("pr"),
  4127. c.getLocal("pr"),
  4128. ),
  4129. c.call(curvePrefix + "_add",
  4130. c.getLocal("pr"),
  4131. c.call(
  4132. prefix + "__ptable_get",
  4133. c.i32_load8_u(
  4134. c.i32_sub(
  4135. c.i32_const(psels + scalarN8 * 8 -1),
  4136. c.getLocal("i")
  4137. )
  4138. )
  4139. ),
  4140. c.getLocal("pr"),
  4141. ),
  4142. c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))),
  4143. c.br(0)
  4144. )));
  4145. }
  4146. function buildMultiexp() {
  4147. const f = module.addFunction(prefix+"_multiexp");
  4148. f.addParam("pscalars", "i32");
  4149. f.addParam("ppoints", "i32");
  4150. f.addParam("n", "i32"); // Number of points
  4151. f.addParam("w", "i32"); // Window size Max 8
  4152. f.addParam("pr", "i32");
  4153. f.addLocal("ps", "i32");
  4154. f.addLocal("pp", "i32");
  4155. f.addLocal("wf", "i32");
  4156. f.addLocal("lastps", "i32");
  4157. const c = f.getCodeBuilder();
  4158. const aux = c.i32_const(module.alloc(pointN8));
  4159. f.addCode(c.setLocal("ps", c.getLocal("pscalars")));
  4160. f.addCode(c.setLocal("pp", c.getLocal("ppoints")));
  4161. f.addCode(c.setLocal(
  4162. "lastps",
  4163. c.i32_add(
  4164. c.getLocal("ps"),
  4165. c.i32_mul(
  4166. c.i32_mul(
  4167. c.i32_div_u(
  4168. c.getLocal("n"),
  4169. c.getLocal("w")
  4170. ),
  4171. c.getLocal("w")
  4172. ),
  4173. c.i32_const(scalarN8)
  4174. )
  4175. )
  4176. ));
  4177. f.addCode(c.block(c.loop(
  4178. c.br_if(
  4179. 1,
  4180. c.i32_eq(
  4181. c.getLocal("ps"),
  4182. c.getLocal("lastps")
  4183. )
  4184. ),
  4185. c.call(prefix + "__mulw", c.getLocal("ps"), c.getLocal("pp"), c.getLocal("w"), aux),
  4186. c.call(curvePrefix + "_add", aux, c.getLocal("pr"), c.getLocal("pr")),
  4187. c.setLocal(
  4188. "ps",
  4189. c.i32_add(
  4190. c.getLocal("ps"),
  4191. c.i32_mul(
  4192. c.i32_const(scalarN8),
  4193. c.getLocal("w")
  4194. )
  4195. )
  4196. ),
  4197. c.setLocal(
  4198. "pp",
  4199. c.i32_add(
  4200. c.getLocal("pp"),
  4201. c.i32_mul(
  4202. c.i32_const(pointFieldN8*2),
  4203. c.getLocal("w")
  4204. )
  4205. )
  4206. ),
  4207. c.br(0)
  4208. )));
  4209. f.addCode(c.setLocal("wf", c.i32_rem_u(c.getLocal("n"), c.getLocal("w"))));
  4210. f.addCode(c.if(
  4211. c.getLocal("wf"),
  4212. [
  4213. ...c.call(prefix + "__mulw", c.getLocal("ps"), c.getLocal("pp"), c.getLocal("wf"), aux),
  4214. ...c.call(curvePrefix + "_add", aux, c.getLocal("pr"), c.getLocal("pr")),
  4215. ]
  4216. ));
  4217. }
  4218. buildSetSet();
  4219. buildSetIsSet();
  4220. buildPTableReset();
  4221. buildPTableGet();
  4222. buildPackBits();
  4223. buildMulw();
  4224. buildMultiexp();
  4225. module.exportFunction(prefix+"_multiexp");
  4226. };
  4227. },{}],11:[function(require,module,exports){
  4228. module.exports = function buildPol(module, prefix, prefixField) {
  4229. const n64 = module.modules[prefixField].n64;
  4230. const n8 = n64*8;
  4231. function buildZero() {
  4232. const f = module.addFunction(prefix+"_zero");
  4233. f.addParam("px", "i32");
  4234. f.addParam("n", "i32");
  4235. f.addLocal("lastp", "i32");
  4236. f.addLocal("p", "i32");
  4237. const c = f.getCodeBuilder();
  4238. f.addCode(
  4239. c.setLocal("p", c.getLocal("px")),
  4240. c.setLocal(
  4241. "lastp",
  4242. c.i32_add(
  4243. c.getLocal("px"),
  4244. c.i32_mul(
  4245. c.getLocal("n"),
  4246. c.i32_const(n8)
  4247. )
  4248. )
  4249. ),
  4250. c.block(c.loop(
  4251. c.br_if(
  4252. 1,
  4253. c.i32_eq(
  4254. c.getLocal("p"),
  4255. c.getLocal("lastp")
  4256. )
  4257. ),
  4258. c.call(prefixField + "_zero", c.getLocal("p")),
  4259. c.setLocal("p", c.i32_add(c.getLocal("p"), c.i32_const(n8))),
  4260. c.br(0)
  4261. ))
  4262. );
  4263. }
  4264. function buildConstructLC() {
  4265. const f = module.addFunction(prefix+"_constructLC");
  4266. f.addParam("ppolynomials", "i32");
  4267. f.addParam("psignals", "i32");
  4268. f.addParam("nSignals", "i32");
  4269. f.addParam("pres", "i32");
  4270. f.addLocal("i", "i32");
  4271. f.addLocal("j", "i32");
  4272. f.addLocal("pp", "i32");
  4273. f.addLocal("ps", "i32");
  4274. f.addLocal("pd", "i32");
  4275. f.addLocal("ncoefs", "i32");
  4276. const c = f.getCodeBuilder();
  4277. const aux = c.i32_const(module.alloc(n8));
  4278. f.addCode(
  4279. c.setLocal("i", c.i32_const(0)),
  4280. c.setLocal("pp", c.getLocal("ppolynomials")),
  4281. c.setLocal("ps", c.getLocal("psignals")),
  4282. c.block(c.loop(
  4283. c.br_if(
  4284. 1,
  4285. c.i32_eq(
  4286. c.getLocal("i"),
  4287. c.getLocal("nSignals")
  4288. )
  4289. ),
  4290. c.setLocal("ncoefs", c.i32_load(c.getLocal("pp"))),
  4291. c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))),
  4292. c.setLocal("j", c.i32_const(0)),
  4293. c.block(c.loop(
  4294. c.br_if(
  4295. 1,
  4296. c.i32_eq(
  4297. c.getLocal("j"),
  4298. c.getLocal("ncoefs")
  4299. )
  4300. ),
  4301. c.setLocal(
  4302. "pd",
  4303. c.i32_add(
  4304. c.getLocal("pres"),
  4305. c.i32_mul(
  4306. c.i32_load(c.getLocal("pp")),
  4307. c.i32_const(n8)
  4308. )
  4309. )
  4310. ),
  4311. c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(4))),
  4312. c.call(
  4313. prefixField + "_mul",
  4314. c.getLocal("ps"),
  4315. c.getLocal("pp"),
  4316. aux
  4317. ),
  4318. c.call(
  4319. prefixField + "_add",
  4320. aux,
  4321. c.getLocal("pd"),
  4322. c.getLocal("pd")
  4323. ),
  4324. c.setLocal("pp", c.i32_add(c.getLocal("pp"), c.i32_const(n8))),
  4325. c.setLocal("j", c.i32_add(c.getLocal("j"), c.i32_const(1))),
  4326. c.br(0)
  4327. )),
  4328. c.setLocal("ps", c.i32_add(c.getLocal("ps"), c.i32_const(n8))),
  4329. c.setLocal("i", c.i32_add(c.getLocal("i"), c.i32_const(1))),
  4330. c.br(0)
  4331. ))
  4332. );
  4333. }
  4334. buildZero();
  4335. buildConstructLC();
  4336. module.exportFunction(prefix + "_zero");
  4337. module.exportFunction(prefix + "_constructLC");
  4338. return prefix;
  4339. };
  4340. },{}],12:[function(require,module,exports){
  4341. const bigInt = require("big-integer");
  4342. const utils = require("./utils.js");
  4343. module.exports = function buildTestF1(module) {
  4344. const q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583");
  4345. const pR2 = module.modules.f1m.pR2;
  4346. const n8 = module.modules.f1m.n64*8;
  4347. const pR3 = module.alloc(utils.bigInt2BytesLE(bigInt.one.shiftLeft(256).square().mod(q).shiftRight(128), n8));
  4348. function buildTestF1() {
  4349. const f = module.addFunction("testF1");
  4350. f.addParam("n", "i32");
  4351. f.addLocal("i", "i32");
  4352. const c = f.getCodeBuilder();
  4353. const pAux1 = module.alloc(n8);
  4354. f.addCode(c.setLocal("i", c.getLocal("n")));
  4355. f.addCode(c.block(c.loop(
  4356. // c.call("f1m_add", c.i32_const(pR2), c.i32_const(pR2), c.i32_const(pAux1)),
  4357. c.call("f1m_mul", c.i32_const(pR2), c.i32_const(pR2), c.i32_const(pAux1)),
  4358. // c.call("int_div", c.i32_const(pR2), c.i32_const(pR3), c.i32_const(pAux1), c.i32_const(0)),
  4359. c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))),
  4360. c.br_if(1, c.i32_eqz ( c.getLocal("i") )),
  4361. c.br(0)
  4362. )));
  4363. }
  4364. buildTestF1();
  4365. module.exportFunction("testF1");
  4366. };
  4367. },{"./utils.js":17,"big-integer":2}],13:[function(require,module,exports){
  4368. const bigInt = require("big-integer");
  4369. module.exports = function buildTestAddG1(module) {
  4370. function buildTestAddG1() {
  4371. const f = module.addFunction("testAddG1");
  4372. f.addParam("n", "i32");
  4373. f.addParam("pP", "i32");
  4374. f.addParam("pR", "i32");
  4375. f.addLocal("i", "i32");
  4376. const c = f.getCodeBuilder();
  4377. f.addCode(c.call("g1_zero", c.getLocal("pR")));
  4378. f.addCode(c.setLocal("i", c.getLocal("n")));
  4379. f.addCode(c.block(c.loop(
  4380. c.call("g1_add", c.getLocal("pP"), c.getLocal("pR"), c.getLocal("pR")),
  4381. c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))),
  4382. c.br_if(1, c.i32_eqz ( c.getLocal("i") )),
  4383. c.br(0)
  4384. )));
  4385. }
  4386. buildTestAddG1();
  4387. module.exportFunction("testAddG1");
  4388. };
  4389. },{"big-integer":2}],14:[function(require,module,exports){
  4390. module.exports = function buildTimesScalar(module, fnName, elementLen, opAB, opAA, fPrefix) {
  4391. const f = module.addFunction(fnName);
  4392. f.addParam("base", "i32");
  4393. f.addParam("scalar", "i32");
  4394. f.addParam("scalarLength", "i32");
  4395. f.addParam("r", "i32");
  4396. f.addLocal("i", "i32");
  4397. f.addLocal("b", "i32");
  4398. const c = f.getCodeBuilder();
  4399. const aux = c.i32_const(module.alloc(elementLen));
  4400. f.addCode(c.call(fPrefix + "_copy", c.getLocal("base"), aux));
  4401. f.addCode(c.call(fPrefix + "_zero", c.getLocal("r")));
  4402. f.addCode(c.setLocal("i", c.getLocal("scalarLength")));
  4403. f.addCode(c.block(c.loop(
  4404. c.setLocal("i", c.i32_sub(c.getLocal("i"), c.i32_const(1))),
  4405. c.setLocal(
  4406. "b",
  4407. c.i32_load8_u(
  4408. c.i32_add(
  4409. c.getLocal("scalar"),
  4410. c.getLocal("i")
  4411. )
  4412. )
  4413. ),
  4414. ...innerLoop(),
  4415. c.br_if(1, c.i32_eqz ( c.getLocal("i") )),
  4416. c.br(0)
  4417. )));
  4418. function innerLoop() {
  4419. const code = [];
  4420. for (let i=0; i<8; i++) {
  4421. code.push(
  4422. ...c.call(opAA, c.getLocal("r"), c.getLocal("r")),
  4423. ...c.if(
  4424. c.i32_ge_u( c.getLocal("b"), c.i32_const(0x80 >> i)),
  4425. [
  4426. ...c.setLocal(
  4427. "b",
  4428. c.i32_sub(
  4429. c.getLocal("b"),
  4430. c.i32_const(0x80 >> i)
  4431. )
  4432. ),
  4433. ...c.call(opAB, aux, c.getLocal("r"), c.getLocal("r"))
  4434. ]
  4435. )
  4436. );
  4437. }
  4438. return code;
  4439. }
  4440. };
  4441. },{}],15:[function(require,module,exports){
  4442. /* globals WebAssembly */
  4443. const bigInt = require("big-integer");
  4444. const ModuleBuilder = require("./wasmbuilder/index.js");
  4445. const buildF1 = require("./build_f1.js");
  4446. const buildTestF1 = require("./build_testf1.js");
  4447. async function build(q) {
  4448. const f1 = new F1(q);
  4449. f1.q = bigInt(q);
  4450. f1.n64 = Math.floor((f1.q.minus(1).bitLength() - 1)/64) +1;
  4451. f1.n32 = f1.n64*2;
  4452. f1.n8 = f1.n64*8;
  4453. f1.memory = new WebAssembly.Memory({initial:1});
  4454. f1.i32 = new Uint32Array(f1.memory.buffer);
  4455. const moduleBuilder = new ModuleBuilder();
  4456. buildF1(moduleBuilder, f1.q);
  4457. buildTestF1(moduleBuilder);
  4458. const code = moduleBuilder.build();
  4459. const wasmModule = await WebAssembly.compile(code);
  4460. f1.instance = await WebAssembly.instantiate(wasmModule, {
  4461. env: {
  4462. "memory": f1.memory
  4463. }
  4464. });
  4465. Object.assign(f1, f1.instance.exports);
  4466. return f1;
  4467. }
  4468. class F1 {
  4469. constructor() {
  4470. }
  4471. alloc(length) {
  4472. const res = this.i32[0];
  4473. this.i32[0] += length;
  4474. return res;
  4475. }
  4476. putInt(pos, _a) {
  4477. const a = bigInt(_a);
  4478. if (pos & 0x7) throw new Error("Pointer must be aligned");
  4479. if (a.bitLength > this.n64*64) {
  4480. return this.putInt(a.mod(this.q));
  4481. }
  4482. for (let i=0; i<this.n32; i++) {
  4483. this.i32[(pos>>2)+i] = a.shiftRight(i*32).and(0xFFFFFFFF).toJSNumber();
  4484. }
  4485. }
  4486. allocInt(_a) {
  4487. const p = this.alloc(this.n8);
  4488. if (_a) this.putInt(p, _a);
  4489. return p;
  4490. }
  4491. putInt2(pos, _a) {
  4492. const a = bigInt(_a);
  4493. if (pos & 0x7) throw new Error("Pointer must be aligned");
  4494. if (a.bitLength > this.n64*64*2) {
  4495. return this.putInt(a.mod(this.q));
  4496. }
  4497. for (let i=0; i<this.n32*2; i++) {
  4498. this.i32[(pos>>2)+i] = a.shiftRight(i*32).and(0xFFFFFFFF).toJSNumber();
  4499. }
  4500. }
  4501. getInt(pos) {
  4502. if (pos & 0x7) throw new Error("Pointer must be aligned");
  4503. let acc = bigInt(this.i32[(pos>>2)+this.n32-1]);
  4504. for (let i=this.n32-2; i>=0; i--) {
  4505. acc = acc.shiftLeft(32);
  4506. acc = acc.add(this.i32[(pos>>2)+i]);
  4507. }
  4508. return acc;
  4509. }
  4510. getInt2(pos) {
  4511. if (pos & 0x7) throw new Error("Pointer must be aligned");
  4512. const last = this.n32*2-1;
  4513. let acc = bigInt(this.i32[(pos>>2)+last]);
  4514. for (let i=last; i>=0; i--) {
  4515. acc = acc.shiftLeft(32);
  4516. acc = acc.add(this.i32[(pos>>2)+i]);
  4517. }
  4518. return acc;
  4519. }
  4520. allocInt2(_a) {
  4521. const p = this.alloc(this.n8*2);
  4522. if (_a) this.putInt2(p, _a);
  4523. return p;
  4524. }
  4525. test_F1(n) {
  4526. const start = new Date().getTime();
  4527. this.instance.exports.testF1(n);
  4528. const end = new Date().getTime();
  4529. const time = end - start;
  4530. return time;
  4531. }
  4532. /*
  4533. function test(n) {
  4534. const q = 21888242871839275222246405745257275088696311157297823662689037894645226208583n;
  4535. let a = (1n << 512n)%q ;
  4536. let b = a >> 128n;
  4537. let c;
  4538. const start = new Date().getTime();
  4539. for (let i=0; i<n; i++) c = a+b;
  4540. const end = new Date().getTime();
  4541. const time = end - start;
  4542. console.log(time);
  4543. }
  4544. */
  4545. }
  4546. module.exports = build;
  4547. },{"./build_f1.js":5,"./build_testf1.js":12,"./wasmbuilder/index.js":20,"big-integer":2}],16:[function(require,module,exports){
  4548. /* globals WebAssembly, Blob, Worker, navigator, Promise, window */
  4549. const bigInt = require("big-integer");
  4550. const ModuleBuilder = require("./wasmbuilder/index.js");
  4551. const buildF1m = require("./build_f1m.js");
  4552. const buildF2m = require("./build_f2m.js");
  4553. const buildF1 = require("./build_f1.js");
  4554. const buildCurve = require("./build_curve.js");
  4555. const buildTest = require("./build_testg1");
  4556. const buildFFT = require("./build_fft");
  4557. const buildMultiexp = require("./build_multiexp");
  4558. const buildPol = require("./build_pol");
  4559. const utils = require("./utils");
  4560. const assert = require("assert");
  4561. class Deferred {
  4562. constructor() {
  4563. this.promise = new Promise((resolve, reject)=> {
  4564. this.reject = reject;
  4565. this.resolve = resolve;
  4566. });
  4567. }
  4568. }
  4569. /*
  4570. function delay(ms) {
  4571. return new Promise(resolve => setTimeout(resolve, ms));
  4572. }
  4573. */
  4574. function thread(self) {
  4575. let instance;
  4576. let memory;
  4577. let i32;
  4578. async function init(data) {
  4579. const code = new Uint8Array(data.code);
  4580. const wasmModule = await WebAssembly.compile(code);
  4581. memory = new WebAssembly.Memory({initial:data.init});
  4582. i32 = new Uint32Array(memory.buffer);
  4583. instance = await WebAssembly.instantiate(wasmModule, {
  4584. env: {
  4585. "memory": memory
  4586. }
  4587. });
  4588. }
  4589. function alloc(length) {
  4590. while (i32[0] & 3) i32[0]++; // Return always aligned pointers
  4591. const res = i32[0];
  4592. i32[0] += length;
  4593. return res;
  4594. }
  4595. function putBin(b) {
  4596. const p = alloc(b.byteLength);
  4597. const s32 = new Uint32Array(b);
  4598. i32.set(s32, p/4);
  4599. return p;
  4600. }
  4601. function getBin(p, l) {
  4602. return memory.buffer.slice(p, p+l);
  4603. }
  4604. self.onmessage = function(e) {
  4605. if (e.data.command == "INIT") {
  4606. init(e.data).then(function() {
  4607. self.postMessage(e.data.result);
  4608. });
  4609. } else if (e.data.command == "G1_MULTIEXP") {
  4610. const oldAlloc = i32[0];
  4611. const pScalars = putBin(e.data.scalars);
  4612. const pPoints = putBin(e.data.points);
  4613. const pRes = alloc(96);
  4614. instance.exports.g1_zero(pRes);
  4615. instance.exports.g1_multiexp(pScalars, pPoints, e.data.n, 5, pRes);
  4616. e.data.result = getBin(pRes, 96);
  4617. i32[0] = oldAlloc;
  4618. self.postMessage(e.data.result, [e.data.result]);
  4619. } else if (e.data.command == "G2_MULTIEXP") {
  4620. const oldAlloc = i32[0];
  4621. const pScalars = putBin(e.data.scalars);
  4622. const pPoints = putBin(e.data.points);
  4623. const pRes = alloc(192);
  4624. instance.exports.g2_zero(pRes);
  4625. instance.exports.g2_multiexp(pScalars, pPoints, e.data.n, 5, pRes);
  4626. e.data.result = getBin(pRes, 192);
  4627. i32[0] = oldAlloc;
  4628. self.postMessage(e.data.result, [e.data.result]);
  4629. } else if (e.data.command == "CALC_H") {
  4630. const oldAlloc = i32[0];
  4631. const pSignals = putBin(e.data.signals);
  4632. const pPolsA = putBin(e.data.polsA);
  4633. const pPolsB = putBin(e.data.polsB);
  4634. const nSignals = e.data.nSignals;
  4635. const domainSize = e.data.domainSize;
  4636. const pSignalsM = alloc(nSignals*32);
  4637. const pPolA = alloc(domainSize*32);
  4638. const pPolB = alloc(domainSize*32);
  4639. const pPolA2 = alloc(domainSize*32*2);
  4640. const pPolB2 = alloc(domainSize*32*2);
  4641. instance.exports.fft_toMontgomeryN(pSignals, pSignalsM, nSignals);
  4642. instance.exports.pol_zero(pPolA, domainSize);
  4643. instance.exports.pol_zero(pPolB, domainSize);
  4644. instance.exports.pol_constructLC(pPolsA, pSignalsM, nSignals, pPolA);
  4645. instance.exports.pol_constructLC(pPolsB, pSignalsM, nSignals, pPolB);
  4646. instance.exports.fft_copyNInterleaved(pPolA, pPolA2, domainSize);
  4647. instance.exports.fft_copyNInterleaved(pPolB, pPolB2, domainSize);
  4648. instance.exports.fft_ifft(pPolA, domainSize, 0);
  4649. instance.exports.fft_ifft(pPolB, domainSize, 0);
  4650. instance.exports.fft_fft(pPolA, domainSize, 1);
  4651. instance.exports.fft_fft(pPolB, domainSize, 1);
  4652. instance.exports.fft_copyNInterleaved(pPolA, pPolA2+32, domainSize);
  4653. instance.exports.fft_copyNInterleaved(pPolB, pPolB2+32, domainSize);
  4654. instance.exports.fft_mulN(pPolA2, pPolB2, domainSize*2, pPolA2);
  4655. instance.exports.fft_ifft(pPolA2, domainSize*2, 0);
  4656. instance.exports.fft_fromMontgomeryN(pPolA2+domainSize*32, pPolA2+domainSize*32, nSignals);
  4657. e.data.result = getBin(pPolA2+domainSize*32, domainSize*32);
  4658. i32[0] = oldAlloc;
  4659. self.postMessage(e.data.result, [e.data.result]);
  4660. }
  4661. };
  4662. }
  4663. async function build() {
  4664. const groth16 = new Groth16();
  4665. groth16.q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583");
  4666. groth16.r = bigInt("21888242871839275222246405745257275088548364400416034343698204186575808495617");
  4667. groth16.n64 = Math.floor((groth16.q.minus(1).bitLength() - 1)/64) +1;
  4668. groth16.n32 = groth16.n64*2;
  4669. groth16.n8 = groth16.n64*8;
  4670. groth16.memory = new WebAssembly.Memory({initial:1000});
  4671. groth16.i32 = new Uint32Array(groth16.memory.buffer);
  4672. const moduleBuilder = new ModuleBuilder();
  4673. moduleBuilder.setMemory(1000);
  4674. buildF1m(moduleBuilder, groth16.q, "f1m");
  4675. buildF1(moduleBuilder, groth16.r, "fr", "frm");
  4676. buildCurve(moduleBuilder, "g1", "f1m");
  4677. buildMultiexp(moduleBuilder, "g1", "g1", "f1m", "fr");
  4678. buildFFT(moduleBuilder, "fft", "frm");
  4679. buildPol(moduleBuilder, "pol", "frm");
  4680. const pNonResidueF2 = moduleBuilder.alloc(
  4681. utils.bigInt2BytesLE(
  4682. bigInt("15537367993719455909907449462855742678907882278146377936676643359958227611562"), // -1 in montgomery
  4683. groth16.n8
  4684. )
  4685. );
  4686. buildF2m(moduleBuilder, pNonResidueF2, "f2m", "f1m");
  4687. buildCurve(moduleBuilder, "g2", "f2m");
  4688. buildMultiexp(moduleBuilder, "g2", "g2", "f2m", "fr");
  4689. buildTest(moduleBuilder);
  4690. const code = moduleBuilder.build();
  4691. const wasmModule = await WebAssembly.compile(code);
  4692. groth16.instance = await WebAssembly.instantiate(wasmModule, {
  4693. env: {
  4694. "memory": groth16.memory
  4695. }
  4696. });
  4697. groth16.pq = moduleBuilder.modules.f1m.pq;
  4698. groth16.pr = moduleBuilder.modules.frm.pq;
  4699. groth16.pr0 = groth16.alloc(192);
  4700. groth16.pr1 = groth16.alloc(192);
  4701. groth16.workers = [];
  4702. groth16.pendingDeferreds = [];
  4703. groth16.working = [];
  4704. const concurrency = navigator.hardwareConcurrency || 8;
  4705. for (let i = 0; i<concurrency+2; i++) {
  4706. const blob = new Blob(["(", thread.toString(), ")(self);"], { type: "text/javascript" });
  4707. const url = URL.createObjectURL(blob);
  4708. groth16.workers[i] = new Worker(url);
  4709. groth16.workers[i].onmessage = function(e) {
  4710. groth16.working[i]=false;
  4711. groth16.pendingDeferreds[i].resolve(e.data);
  4712. groth16.processWorks();
  4713. };
  4714. groth16.working[i]=false;
  4715. }
  4716. const initPromises = [];
  4717. for (let i=0; i<groth16.workers.length;i++) {
  4718. const copyCode = code.slice(0).buffer;
  4719. initPromises.push(groth16.postAction(i, {
  4720. command: "INIT",
  4721. init: 1000,
  4722. code: copyCode
  4723. }, [copyCode]));
  4724. }
  4725. await Promise.all(initPromises);
  4726. return groth16;
  4727. }
  4728. class Groth16 {
  4729. constructor() {
  4730. this.actionQueue = [];
  4731. }
  4732. postAction(workerId, e, transfers, _deferred) {
  4733. assert(this.working[workerId] == false);
  4734. this.working[workerId] = true;
  4735. this.pendingDeferreds[workerId] = _deferred ? _deferred : new Deferred();
  4736. this.workers[workerId].postMessage(e, transfers);
  4737. return this.pendingDeferreds[workerId].promise;
  4738. }
  4739. processWorks() {
  4740. for (let i=0; (i<this.workers.length)&&(this.actionQueue.length > 0); i++) {
  4741. if (this.working[i] == false) {
  4742. const work = this.actionQueue.shift();
  4743. this.postAction(i, work.data, work.transfers, work.deferred);
  4744. }
  4745. }
  4746. }
  4747. queueAction(actionData, transfers) {
  4748. const d = new Deferred();
  4749. this.actionQueue.push({
  4750. data: actionData,
  4751. transfers: transfers,
  4752. deferred: d
  4753. });
  4754. this.processWorks();
  4755. return d.promise;
  4756. }
  4757. alloc(length) {
  4758. while (this.i32[0] & 3) this.i32[0]++; // Return always aligned pointers
  4759. const res = this.i32[0];
  4760. this.i32[0] += length;
  4761. return res;
  4762. }
  4763. putBin(p, b) {
  4764. const s32 = new Uint32Array(b);
  4765. this.i32.set(s32, p/4);
  4766. }
  4767. getBin(p, l) {
  4768. return this.memory.buffer.slice(p, p+l);
  4769. }
  4770. bin2int(b) {
  4771. const i32 = new Uint32Array(b);
  4772. let acc = bigInt(i32[7]);
  4773. for (let i=6; i>=0; i--) {
  4774. acc = acc.shiftLeft(32);
  4775. acc = acc.add(i32[i]);
  4776. }
  4777. return acc.toString();
  4778. }
  4779. bin2g1(b) {
  4780. return [
  4781. this.bin2int(b.slice(0,32)),
  4782. this.bin2int(b.slice(32,64)),
  4783. this.bin2int(b.slice(64,96)),
  4784. ];
  4785. }
  4786. bin2g2(b) {
  4787. return [
  4788. [
  4789. this.bin2int(b.slice(0,32)),
  4790. this.bin2int(b.slice(32,64))
  4791. ],
  4792. [
  4793. this.bin2int(b.slice(64,96)),
  4794. this.bin2int(b.slice(96,128))
  4795. ],
  4796. [
  4797. this.bin2int(b.slice(128,160)),
  4798. this.bin2int(b.slice(160,192))
  4799. ],
  4800. ];
  4801. }
  4802. async g1_multiexp(scalars, points) {
  4803. const nPoints = scalars.byteLength /32;
  4804. const nPointsPerThread = Math.floor(nPoints / this.workers.length);
  4805. const opPromises = [];
  4806. for (let i=0; i<this.workers.length; i++) {
  4807. const th_nPoints =
  4808. i < this.workers.length -1 ?
  4809. nPointsPerThread :
  4810. nPoints - (nPointsPerThread * (this.workers.length -1));
  4811. const scalars_th = scalars.slice(i*nPointsPerThread*32, i*nPointsPerThread*32 + th_nPoints*32);
  4812. const points_th = points.slice(i*nPointsPerThread*64, i*nPointsPerThread*64 + th_nPoints*64);
  4813. opPromises.push(
  4814. this.queueAction({
  4815. command: "G1_MULTIEXP",
  4816. scalars: scalars_th,
  4817. points: points_th,
  4818. n: th_nPoints
  4819. }, [scalars_th, points_th])
  4820. );
  4821. }
  4822. const results = await Promise.all(opPromises);
  4823. this.instance.exports.g1_zero(this.pr0);
  4824. for (let i=0; i<results.length; i++) {
  4825. this.putBin(this.pr1, results[i]);
  4826. this.instance.exports.g1_add(this.pr0, this.pr1, this.pr0);
  4827. }
  4828. return this.getBin(this.pr0, 96);
  4829. }
  4830. async g2_multiexp(scalars, points) {
  4831. const nPoints = scalars.byteLength /32;
  4832. const nPointsPerThread = Math.floor(nPoints / this.workers.length);
  4833. const opPromises = [];
  4834. for (let i=0; i<this.workers.length; i++) {
  4835. const th_nPoints =
  4836. i < this.workers.length -1 ?
  4837. nPointsPerThread :
  4838. nPoints - (nPointsPerThread * (this.workers.length -1));
  4839. const scalars_th = scalars.slice(i*nPointsPerThread*32, i*nPointsPerThread*32 + th_nPoints*32);
  4840. const points_th = points.slice(i*nPointsPerThread*128, i*nPointsPerThread*128 + th_nPoints*128);
  4841. opPromises.push(
  4842. this.queueAction({
  4843. command: "G2_MULTIEXP",
  4844. scalars: scalars_th,
  4845. points: points_th,
  4846. n: th_nPoints
  4847. }, [scalars_th, points_th])
  4848. );
  4849. }
  4850. const results = await Promise.all(opPromises);
  4851. this.instance.exports.g2_zero(this.pr0);
  4852. for (let i=0; i<results.length; i++) {
  4853. this.putBin(this.pr1, results[i]);
  4854. this.instance.exports.g2_add(this.pr0, this.pr1, this.pr0);
  4855. }
  4856. return this.getBin(this.pr0, 192);
  4857. }
  4858. g1_affine(p) {
  4859. this.putBin(this.pr0, p);
  4860. this.instance.exports.g1_affine(this.pr0, this.pr0);
  4861. return this.getBin(this.pr0, 96);
  4862. }
  4863. g2_affine(p) {
  4864. this.putBin(this.pr0, p);
  4865. this.instance.exports.g2_affine(this.pr0, this.pr0);
  4866. return this.getBin(this.pr0, 192);
  4867. }
  4868. g1_fromMontgomery(p) {
  4869. this.putBin(this.pr0, p);
  4870. this.instance.exports.g1_fromMontgomery(this.pr0, this.pr0);
  4871. return this.getBin(this.pr0, 96);
  4872. }
  4873. g2_fromMontgomery(p) {
  4874. this.putBin(this.pr0, p);
  4875. this.instance.exports.g2_fromMontgomery(this.pr0, this.pr0);
  4876. return this.getBin(this.pr0, 192);
  4877. }
  4878. loadPoint1(b) {
  4879. const p = this.alloc(96);
  4880. this.putBin(p, b);
  4881. this.instance.exports.f1m_one(p+64);
  4882. return p;
  4883. }
  4884. loadPoint2(b) {
  4885. const p = this.alloc(192);
  4886. this.putBin(p, b);
  4887. this.instance.exports.f2m_one(p+128);
  4888. return p;
  4889. }
  4890. async calcH(signals, polsA, polsB, nSignals, domainSize) {
  4891. return this.queueAction({
  4892. command: "CALC_H",
  4893. signals: signals,
  4894. polsA: polsA,
  4895. polsB: polsB,
  4896. nSignals: nSignals,
  4897. domainSize: domainSize
  4898. }, [signals, polsA, polsB]);
  4899. }
  4900. async proof(signals, pkey) {
  4901. const pkey32 = new Uint32Array(pkey);
  4902. const nSignals = pkey32[0];
  4903. const nPublic = pkey32[1];
  4904. const domainSize = pkey32[2];
  4905. const pPolsA = pkey32[3];
  4906. const pPolsB = pkey32[4];
  4907. const pPointsA = pkey32[5];
  4908. const pPointsB1 = pkey32[6];
  4909. const pPointsB2 = pkey32[7];
  4910. const pPointsC = pkey32[8];
  4911. const pHExps = pkey32[9];
  4912. const polsA = pkey.slice(pPolsA, pPolsA + pPolsB);
  4913. const polsB = pkey.slice(pPolsB, pPolsB + pPointsA);
  4914. const pointsA = pkey.slice(pPointsA, pPointsA + nSignals*64);
  4915. const pointsB1 = pkey.slice(pPointsB1, pPointsB1 + nSignals*64);
  4916. const pointsB2 = pkey.slice(pPointsB2, pPointsB2 + nSignals*128);
  4917. const pointsC = pkey.slice(pPointsC, pPointsC + (nSignals-nPublic-1)*64);
  4918. const pointsHExps = pkey.slice(pHExps, pHExps + domainSize*64);
  4919. const alfa1 = pkey.slice(10*4, 10*4 + 64);
  4920. const beta1 = pkey.slice(10*4 + 64, 10*4 + 128);
  4921. const delta1 = pkey.slice(10*4 + 128, 10*4 + 192);
  4922. const beta2 = pkey.slice(10*4 + 192, 10*4 + 320);
  4923. const delta2 = pkey.slice(10*4 + 320, 10*4 + 448);
  4924. const pH = this.calcH(signals.slice(0), polsA, polsB, nSignals, domainSize).then( (h) => {
  4925. return this.g1_multiexp(h, pointsHExps);
  4926. });
  4927. const pA = this.g1_multiexp(signals.slice(0), pointsA);
  4928. const pB1 = this.g1_multiexp(signals.slice(0), pointsB1);
  4929. const pB2 = this.g2_multiexp(signals.slice(0), pointsB2);
  4930. const pC = this.g1_multiexp(signals.slice((nPublic+1)*32), pointsC);
  4931. const res = await Promise.all([pA, pB1, pB2, pC, pH]);
  4932. const pi_a = this.alloc(96);
  4933. const pi_b = this.alloc(192);
  4934. const pi_c = this.alloc(96);
  4935. const pib1 = this.alloc(96);
  4936. this.putBin(pi_a, res[0]);
  4937. this.putBin(pib1, res[1]);
  4938. this.putBin(pi_b, res[2]);
  4939. this.putBin(pi_c, res[3]);
  4940. const pAlfa1 = this.loadPoint1(alfa1);
  4941. const pBeta1 = this.loadPoint1(beta1);
  4942. const pDelta1 = this.loadPoint1(delta1);
  4943. const pBeta2 = this.loadPoint2(beta2);
  4944. const pDelta2 = this.loadPoint2(delta2);
  4945. let rnd = new Uint32Array(8);
  4946. const aux1 = this.alloc(96);
  4947. const aux2 = this.alloc(192);
  4948. window.crypto.getRandomValues(rnd);
  4949. const pr = this.alloc(32);
  4950. this.putBin(pr, rnd);
  4951. // this.instance.exports.frm_normalize(pr);
  4952. window.crypto.getRandomValues(rnd);
  4953. const ps = this.alloc(32);
  4954. this.putBin(ps, rnd);
  4955. // this.instance.exports.frm_normalize(ps);
  4956. //this.instance.exports.frm_zero(pr);
  4957. //this.instance.exports.frm_zero(ps);
  4958. // pi_a = pi_a + Alfa1 + r*Delta1
  4959. this.instance.exports.g1_add(pAlfa1, pi_a, pi_a);
  4960. // this.instance.exports.g1_mulscalar(pr, pDelta1, 1, 1, aux1);
  4961. this.instance.exports.g1_timesScalar(pDelta1, pr, 32, aux1);
  4962. this.instance.exports.g1_add(aux1, pi_a, pi_a);
  4963. // pi_b = pi_b + Beta2 + s*Delta2
  4964. this.instance.exports.g2_add(pBeta2, pi_b, pi_b);
  4965. this.instance.exports.g2_timesScalar(pDelta2, ps, 32, aux2);
  4966. this.instance.exports.g2_add(aux2, pi_b, pi_b);
  4967. // pib1 = pib1 + Beta1 + s*Delta1
  4968. this.instance.exports.g1_add(pBeta1, pib1, pib1);
  4969. this.instance.exports.g1_timesScalar(pDelta1, ps, 32, aux1);
  4970. this.instance.exports.g1_add(aux1, pib1, pib1);
  4971. // pi_c = pi_c + pH
  4972. this.putBin(aux1, res[4]);
  4973. this.instance.exports.g1_add(aux1, pi_c, pi_c);
  4974. // pi_c = pi_c + s*pi_a
  4975. this.instance.exports.g1_timesScalar(pi_a, ps, 32, aux1);
  4976. this.instance.exports.g1_add(aux1, pi_c, pi_c);
  4977. // pi_c = pi_c + r*pib1
  4978. this.instance.exports.g1_timesScalar(pib1, pr, 32, aux1);
  4979. this.instance.exports.g1_add(aux1, pi_c, pi_c);
  4980. // pi_c = pi_c - r*s*delta1
  4981. const prs = this.alloc(64);
  4982. this.instance.exports.int_mul(pr, ps, prs);
  4983. this.instance.exports.g1_timesScalar(pDelta1, prs, 64, aux1);
  4984. this.instance.exports.g1_neg(aux1, aux1);
  4985. this.instance.exports.g1_add(aux1, pi_c, pi_c);
  4986. this.instance.exports.g1_affine(pi_a, pi_a);
  4987. this.instance.exports.g2_affine(pi_b, pi_b);
  4988. this.instance.exports.g1_affine(pi_c, pi_c);
  4989. this.instance.exports.g1_fromMontgomery(pi_a, pi_a);
  4990. this.instance.exports.g2_fromMontgomery(pi_b, pi_b);
  4991. this.instance.exports.g1_fromMontgomery(pi_c, pi_c);
  4992. return {
  4993. pi_a: this.bin2g1(this.getBin(pi_a, 96)),
  4994. pi_b: this.bin2g2(this.getBin(pi_b, 192)),
  4995. pi_c: this.bin2g1(this.getBin(pi_c, 96)),
  4996. };
  4997. }
  4998. }
  4999. module.exports = build;
  5000. },{"./build_curve.js":4,"./build_f1.js":5,"./build_f1m.js":6,"./build_f2m.js":7,"./build_fft":8,"./build_multiexp":10,"./build_pol":11,"./build_testg1":13,"./utils":17,"./wasmbuilder/index.js":20,"assert":24,"big-integer":2}],17:[function(require,module,exports){
  5001. const bigInt = require("big-integer");
  5002. exports.bigInt2BytesLE = function bigInt2BytesLE(_a, len) {
  5003. const b = Array(len);
  5004. let v = bigInt(_a);
  5005. for (let i=0; i<len; i++) {
  5006. b[i] = v.and(0xFF).toJSNumber();
  5007. v = v.shiftRight(8);
  5008. }
  5009. return b;
  5010. };
  5011. exports.bigInt2U32LE = function bigInt2BytesLE(_a, len) {
  5012. const b = Array(len);
  5013. let v = bigInt(_a);
  5014. for (let i=0; i<len; i++) {
  5015. b[i] = v.and(0xFFFFFFFF).toJSNumber();
  5016. v = v.shiftRight(32);
  5017. }
  5018. return b;
  5019. };
  5020. },{"big-integer":2}],18:[function(require,module,exports){
  5021. const utils = require("./utils.js");
  5022. class CodeBuilder {
  5023. constructor(func) {
  5024. this.func = func;
  5025. this.functionName = func.functionName;
  5026. this.module = func.module;
  5027. }
  5028. setLocal(localName, valCode) {
  5029. const idx = this.func.localIdxByName[localName];
  5030. if (idx === undefined)
  5031. throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
  5032. return [...valCode, 0x21, ...utils.varuint32( idx )];
  5033. }
  5034. teeLocal(localName, valCode) {
  5035. const idx = this.func.localIdxByName[localName];
  5036. if (idx === undefined)
  5037. throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
  5038. return [...valCode, 0x22, ...utils.varuint32( idx )];
  5039. }
  5040. getLocal(localName) {
  5041. const idx = this.func.localIdxByName[localName];
  5042. if (idx === undefined)
  5043. throw new Error(`Local Variable not defined: Function: ${this.functionName} local: ${localName} `);
  5044. return [0x20, ...utils.varuint32( idx )];
  5045. }
  5046. i64_load8_s(idxCode, _offset, _align) {
  5047. const offset = _offset || 0;
  5048. const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
  5049. return [...idxCode, 0x30, align, ...utils.varuint32(offset)];
  5050. }
  5051. i64_load8_u(idxCode, _offset, _align) {
  5052. const offset = _offset || 0;
  5053. const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
  5054. return [...idxCode, 0x31, align, ...utils.varuint32(offset)];
  5055. }
  5056. i64_load16_s(idxCode, _offset, _align) {
  5057. const offset = _offset || 0;
  5058. const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
  5059. return [...idxCode, 0x32, align, ...utils.varuint32(offset)];
  5060. }
  5061. i64_load16_u(idxCode, _offset, _align) {
  5062. const offset = _offset || 0;
  5063. const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
  5064. return [...idxCode, 0x33, align, ...utils.varuint32(offset)];
  5065. }
  5066. i64_load32_s(idxCode, _offset, _align) {
  5067. const offset = _offset || 0;
  5068. const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
  5069. return [...idxCode, 0x34, align, ...utils.varuint32(offset)];
  5070. }
  5071. i64_load32_u(idxCode, _offset, _align) {
  5072. const offset = _offset || 0;
  5073. const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
  5074. return [...idxCode, 0x35, align, ...utils.varuint32(offset)];
  5075. }
  5076. i64_load(idxCode, _offset, _align) {
  5077. const offset = _offset || 0;
  5078. const align = (_align === undefined) ? 3 : _align; // 32 bits alignment by default
  5079. return [...idxCode, 0x29, align, ...utils.varuint32(offset)];
  5080. }
  5081. i64_store32(idxCode, _offset, _align, _codeVal) {
  5082. let offset, align, codeVal;
  5083. if (Array.isArray(_offset)) {
  5084. offset = 0;
  5085. align = 2;
  5086. codeVal = _offset;
  5087. } else if (Array.isArray(_align)) {
  5088. offset = _offset;
  5089. align = 2;
  5090. codeVal = _align;
  5091. } else if (Array.isArray(_codeVal)) {
  5092. offset = _offset;
  5093. align = _align;
  5094. codeVal = _codeVal;
  5095. }
  5096. return [...idxCode, ...codeVal, 0x3e, align, ...utils.varuint32(offset)];
  5097. }
  5098. i64_store(idxCode, _offset, _align, _codeVal) {
  5099. let offset, align, codeVal;
  5100. if (Array.isArray(_offset)) {
  5101. offset = 0;
  5102. align = 3;
  5103. codeVal = _offset;
  5104. } else if (Array.isArray(_align)) {
  5105. offset = _offset;
  5106. align = 3;
  5107. codeVal = _align;
  5108. } else if (Array.isArray(_codeVal)) {
  5109. offset = _offset;
  5110. align = _align;
  5111. codeVal = _codeVal;
  5112. }
  5113. return [...idxCode, ...codeVal, 0x37, align, ...utils.varuint32(offset)];
  5114. }
  5115. i32_load8_s(idxCode, _offset, _align) {
  5116. const offset = _offset || 0;
  5117. const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
  5118. return [...idxCode, 0x2c, align, ...utils.varuint32(offset)];
  5119. }
  5120. i32_load8_u(idxCode, _offset, _align) {
  5121. const offset = _offset || 0;
  5122. const align = (_align === undefined) ? 0 : _align; // 32 bits alignment by default
  5123. return [...idxCode, 0x2d, align, ...utils.varuint32(offset)];
  5124. }
  5125. i32_load16_s(idxCode, _offset, _align) {
  5126. const offset = _offset || 0;
  5127. const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
  5128. return [...idxCode, 0x2e, align, ...utils.varuint32(offset)];
  5129. }
  5130. i32_load16_u(idxCode, _offset, _align) {
  5131. const offset = _offset || 0;
  5132. const align = (_align === undefined) ? 1 : _align; // 32 bits alignment by default
  5133. return [...idxCode, 0x2f, align, ...utils.varuint32(offset)];
  5134. }
  5135. i32_load(idxCode, _offset, _align) {
  5136. const offset = _offset || 0;
  5137. const align = (_align === undefined) ? 2 : _align; // 32 bits alignment by default
  5138. return [...idxCode, 0x28, align, ...utils.varuint32(offset)];
  5139. }
  5140. i32_store(idxCode, _offset, _align, _codeVal) {
  5141. let offset, align, codeVal;
  5142. if (Array.isArray(_offset)) {
  5143. offset = 0;
  5144. align = 2;
  5145. codeVal = _offset;
  5146. } else if (Array.isArray(_align)) {
  5147. offset = _offset;
  5148. align = 2;
  5149. codeVal = _align;
  5150. } else if (Array.isArray(_codeVal)) {
  5151. offset = _offset;
  5152. align = _align;
  5153. codeVal = _codeVal;
  5154. }
  5155. return [...idxCode, ...codeVal, 0x36, align, ...utils.varuint32(offset)];
  5156. }
  5157. call(fnName, ...args) {
  5158. const idx = this.module.functionIdxByName[fnName];
  5159. if (idx === undefined)
  5160. throw new Error(`Function not defined: Function: ${fnName}`);
  5161. return [...[].concat(...args), 0x10, ...utils.varuint32(idx)];
  5162. }
  5163. if(condCode, thenCode, elseCode) {
  5164. if (elseCode) {
  5165. return [...condCode, 0x04, 0x40, ...thenCode, 0x05, ...elseCode, 0x0b];
  5166. } else {
  5167. return [...condCode, 0x04, 0x40, ...thenCode, 0x0b];
  5168. }
  5169. }
  5170. block(bCode) { return [0x02, 0x40, ...bCode, 0x0b]; }
  5171. loop(...args) {
  5172. return [0x03, 0x40, ...[].concat(...[...args]), 0x0b];
  5173. }
  5174. br_if(relPath, condCode) { return [...condCode, 0x0d, ...utils.varuint32(relPath)]; }
  5175. br(relPath) { return [0x0c, ...utils.varuint32(relPath)]; }
  5176. ret(rCode) { return [...rCode, 0x0f]; }
  5177. drop(dCode) { return [...dCode, 0x1a]; }
  5178. i64_const(num) { return [0x42, ...utils.varint64(num)]; }
  5179. i32_const(num) { return [0x41, ...utils.varint32(num)]; }
  5180. i64_eqz(opcode) { return [...opcode, 0x50]; }
  5181. i64_eq(op1code, op2code) { return [...op1code, ...op2code, 0x51]; }
  5182. i64_ne(op1code, op2code) { return [...op1code, ...op2code, 0x52]; }
  5183. i64_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x53]; }
  5184. i64_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x54]; }
  5185. i64_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x55]; }
  5186. i64_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x56]; }
  5187. i64_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x57]; }
  5188. i64_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x58]; }
  5189. i64_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x59]; }
  5190. i64_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x5a]; }
  5191. i64_add(op1code, op2code) { return [...op1code, ...op2code, 0x7c]; }
  5192. i64_sub(op1code, op2code) { return [...op1code, ...op2code, 0x7d]; }
  5193. i64_mul(op1code, op2code) { return [...op1code, ...op2code, 0x7e]; }
  5194. i64_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x80]; }
  5195. i64_and(op1code, op2code) { return [...op1code, ...op2code, 0x83]; }
  5196. i64_or(op1code, op2code) { return [...op1code, ...op2code, 0x84]; }
  5197. i64_shl(op1code, op2code) { return [...op1code, ...op2code, 0x86]; }
  5198. i64_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x87]; }
  5199. i64_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x88]; }
  5200. i64_extend_i32_u(op1code) { return [...op1code, 0xad]; }
  5201. i32_eqz(op1code) { return [...op1code, 0x45]; }
  5202. i32_eq(op1code, op2code) { return [...op1code, ...op2code, 0x46]; }
  5203. i32_ne(op1code, op2code) { return [...op1code, ...op2code, 0x47]; }
  5204. i32_lt_s(op1code, op2code) { return [...op1code, ...op2code, 0x48]; }
  5205. i32_lt_u(op1code, op2code) { return [...op1code, ...op2code, 0x49]; }
  5206. i32_gt_s(op1code, op2code) { return [...op1code, ...op2code, 0x4a]; }
  5207. i32_gt_u(op1code, op2code) { return [...op1code, ...op2code, 0x4b]; }
  5208. i32_le_s(op1code, op2code) { return [...op1code, ...op2code, 0x4c]; }
  5209. i32_le_u(op1code, op2code) { return [...op1code, ...op2code, 0x4d]; }
  5210. i32_ge_s(op1code, op2code) { return [...op1code, ...op2code, 0x4e]; }
  5211. i32_ge_u(op1code, op2code) { return [...op1code, ...op2code, 0x4f]; }
  5212. i32_add(op1code, op2code) { return [...op1code, ...op2code, 0x6a]; }
  5213. i32_sub(op1code, op2code) { return [...op1code, ...op2code, 0x6b]; }
  5214. i32_mul(op1code, op2code) { return [...op1code, ...op2code, 0x6c]; }
  5215. i32_div_s(op1code, op2code) { return [...op1code, ...op2code, 0x6d]; }
  5216. i32_div_u(op1code, op2code) { return [...op1code, ...op2code, 0x6e]; }
  5217. i32_rem_s(op1code, op2code) { return [...op1code, ...op2code, 0x6f]; }
  5218. i32_rem_u(op1code, op2code) { return [...op1code, ...op2code, 0x70]; }
  5219. i32_and(op1code, op2code) { return [...op1code, ...op2code, 0x71]; }
  5220. i32_or(op1code, op2code) { return [...op1code, ...op2code, 0x72]; }
  5221. i32_shl(op1code, op2code) { return [...op1code, ...op2code, 0x74]; }
  5222. i32_shr_s(op1code, op2code) { return [...op1code, ...op2code, 0x75]; }
  5223. i32_shr_u(op1code, op2code) { return [...op1code, ...op2code, 0x76]; }
  5224. i32_rotl(op1code, op2code) { return [...op1code, ...op2code, 0x77]; }
  5225. i32_rotr(op1code, op2code) { return [...op1code, ...op2code, 0x78]; }
  5226. i32_wrap_i64(op1code) { return [...op1code, 0xa7]; }
  5227. unreachable() { return [ 0x0 ]; }
  5228. }
  5229. module.exports = CodeBuilder;
  5230. },{"./utils.js":22}],19:[function(require,module,exports){
  5231. const CodeBuilder = require("./codebuilder.js");
  5232. const utils = require("./utils.js");
  5233. const typeCodes = {
  5234. "i32": 0x7f,
  5235. "i64": 0x7e,
  5236. "f32": 0x7d,
  5237. "f64": 0x7c,
  5238. "anyfunc": 0x70,
  5239. "func": 0x60,
  5240. "emptyblock": 0x40
  5241. };
  5242. class FunctionBuilder {
  5243. constructor (module, fnName, fnType, moduleName, fieldName) {
  5244. if (fnType == "import") {
  5245. this.fnType = "import";
  5246. this.moduleName = moduleName;
  5247. this.fieldName = fieldName;
  5248. } else if (fnType == "internal") {
  5249. this.fnType = "internal";
  5250. } else {
  5251. throw new Error("Invalid function fnType: " + fnType);
  5252. }
  5253. this.module = module;
  5254. this.fnName = fnName;
  5255. this.params = [];
  5256. this.locals = [];
  5257. this.localIdxByName = {};
  5258. this.code = [];
  5259. this.returnType = null;
  5260. this.nextLocal =0;
  5261. }
  5262. addParam(paramName, paramType) {
  5263. if (this.localIdxByName[paramName])
  5264. throw new Error(`param already exists. Function: ${this.fnName}, Param: ${paramName} `);
  5265. const idx = this.nextLocal++;
  5266. this.localIdxByName[paramName] = idx;
  5267. this.params.push({
  5268. type: paramType
  5269. });
  5270. }
  5271. addLocal(localName, localType, _length) {
  5272. const length = _length || 1;
  5273. if (this.localIdxByName[localName])
  5274. throw new Error(`local already exists. Function: ${this.fnName}, Param: ${localName} `);
  5275. const idx = this.nextLocal++;
  5276. this.localIdxByName[localName] = idx;
  5277. this.locals.push({
  5278. type: localType,
  5279. length: length
  5280. });
  5281. }
  5282. setReturnType(returnType) {
  5283. if (this.returnType)
  5284. throw new Error(`returnType already defined. Function: ${this.fnName}`);
  5285. this.returnType = returnType;
  5286. }
  5287. getSignature() {
  5288. const params = [...utils.varuint32(this.params.length), ...this.params.map((p) => typeCodes[p.type])];
  5289. const returns = this.returnType ? [0x01, typeCodes[this.returnType]] : [0];
  5290. return [0x60, ...params, ...returns];
  5291. }
  5292. getBody() {
  5293. const locals = this.locals.map((l) => [
  5294. ...utils.varuint32(l.length),
  5295. typeCodes[l.type]
  5296. ]);
  5297. const body = [
  5298. ...utils.varuint32(this.locals.length),
  5299. ...[].concat(...locals),
  5300. ...this.code,
  5301. 0x0b
  5302. ];
  5303. return [
  5304. ...utils.varuint32(body.length),
  5305. ...body
  5306. ];
  5307. }
  5308. addCode(...code) {
  5309. this.code.push(...[].concat(...[...code]));
  5310. }
  5311. getCodeBuilder() {
  5312. return new CodeBuilder(this);
  5313. }
  5314. }
  5315. module.exports = FunctionBuilder;
  5316. },{"./codebuilder.js":18,"./utils.js":22}],20:[function(require,module,exports){
  5317. module.exports = require("./modulebuilder");
  5318. },{"./modulebuilder":21}],21:[function(require,module,exports){
  5319. const FunctionBuilder = require("./functionbuilder.js");
  5320. const utils = require("./utils.js");
  5321. class ModuleBuilder {
  5322. constructor() {
  5323. this.functions = [];
  5324. this.functionIdxByName = {};
  5325. this.nImportFunctions = 0;
  5326. this.nInternalFunctions =0;
  5327. this.memory = {
  5328. pagesSize: 1,
  5329. moduleName: "env",
  5330. fieldName: "memory"
  5331. };
  5332. this.free = 8;
  5333. this.datas = [];
  5334. this.modules = {};
  5335. this.exports = [];
  5336. }
  5337. build() {
  5338. this._setSignatures();
  5339. return new Uint8Array([
  5340. ...utils.u32(0x6d736100),
  5341. ...utils.u32(1),
  5342. ...this._buildType(),
  5343. ...this._buildImport(),
  5344. ...this._buildFunctionDeclarations(),
  5345. ...this._buildExports(),
  5346. ...this._buildCode(),
  5347. ...this._buildData()
  5348. ]);
  5349. }
  5350. addFunction(fnName) {
  5351. if (typeof(this.functionIdxByName[fnName]) !== "undefined")
  5352. throw new Error(`Function already defined: ${fnName}`);
  5353. const idx = this.functions.length;
  5354. this.functionIdxByName[fnName] = idx;
  5355. this.functions.push(new FunctionBuilder(this, fnName, "internal"));
  5356. this.nInternalFunctions++;
  5357. return this.functions[idx];
  5358. }
  5359. addIimportFunction(fnName, moduleName, _fieldName) {
  5360. if (typeof(this.functionIdxByName[fnName]) !== "undefined")
  5361. throw new Error(`Function already defined: ${fnName}`);
  5362. if ( (this.functions.length>0)
  5363. &&(this.functions[this.functions.length-1].type == "internal"))
  5364. throw new Error(`Import functions must be declared before internal: ${fnName}`);
  5365. let fieldName = _fieldName || fnName;
  5366. const idx = this.functions.length;
  5367. this.functionIdxByName[fnName] = idx;
  5368. this.functions.push(new FunctionBuilder(this, fnName, "import", moduleName, fieldName));
  5369. this.nImportFunctions ++;
  5370. return this.functions[idx];
  5371. }
  5372. setMemory(pagesSize, moduleName, fieldName) {
  5373. this.memory = {
  5374. pagesSize: pagesSize,
  5375. moduleName: moduleName || "env",
  5376. fieldName: fieldName || "memory"
  5377. };
  5378. }
  5379. exportFunction(fnName, _exportName) {
  5380. const exportName = _exportName || fnName;
  5381. if (typeof(this.functionIdxByName[fnName]) === "undefined")
  5382. throw new Error(`Function not defined: ${fnName}`);
  5383. const idx = this.functionIdxByName[fnName];
  5384. if (exportName != fnName) {
  5385. this.functionIdxByName[exportName] = idx;
  5386. }
  5387. this.exports.push({
  5388. exportName: exportName,
  5389. idx: idx
  5390. });
  5391. }
  5392. addData(offset, bytes) {
  5393. this.datas.push({
  5394. offset: offset,
  5395. bytes: bytes
  5396. });
  5397. }
  5398. alloc(a, b) {
  5399. let size;
  5400. let bytes;
  5401. if (Array.isArray(a) && (typeof(b) === "undefined")) {
  5402. size = a.length;
  5403. bytes = a;
  5404. } else {
  5405. size = a;
  5406. bytes = b;
  5407. }
  5408. const p = this.free;
  5409. this.free += size;
  5410. if (bytes) {
  5411. this.addData(p, bytes);
  5412. }
  5413. return p;
  5414. }
  5415. _setSignatures() {
  5416. this.signatures = [];
  5417. const signatureIdxByName = {};
  5418. for (let i=0; i<this.functions.length; i++) {
  5419. const signature = this.functions[i].getSignature();
  5420. const signatureName = "s_"+utils.toHexString(signature);
  5421. if (typeof(signatureIdxByName[signatureName]) === "undefined") {
  5422. signatureIdxByName[signatureName] = this.signatures.length;
  5423. this.signatures.push(signature);
  5424. }
  5425. this.functions[i].signatureIdx = signatureIdxByName[signatureName];
  5426. }
  5427. }
  5428. _buildSection(sectionType, section) {
  5429. return [sectionType, ...utils.varuint32(section.length), ...section];
  5430. }
  5431. _buildType() {
  5432. return this._buildSection(
  5433. 0x01,
  5434. [
  5435. ...utils.varuint32(this.signatures.length),
  5436. ...[].concat(...this.signatures)
  5437. ]
  5438. );
  5439. }
  5440. _buildImport() {
  5441. const entries = [];
  5442. entries.push([
  5443. ...utils.string(this.memory.moduleName),
  5444. ...utils.string(this.memory.fieldName),
  5445. 0x02,
  5446. 0x00, //Flags no init valua
  5447. ...utils.varuint32(this.memory.pagesSize)
  5448. ]);
  5449. for (let i=0; i< this.nImportFunctions; i++) {
  5450. entries.push([
  5451. ...utils.string(this.functions[i].moduleName),
  5452. ...utils.string(this.functions[i].fieldName),
  5453. 0x00,
  5454. ...utils.varuint32(this.functions[i].signatureIdx)
  5455. ]);
  5456. }
  5457. return this._buildSection(
  5458. 0x02,
  5459. utils.varuint32(entries.length).concat(...entries)
  5460. );
  5461. }
  5462. _buildFunctionDeclarations() {
  5463. const entries = [];
  5464. for (let i=this.nImportFunctions; i< this.nInternalFunctions; i++) {
  5465. entries.push(...utils.varuint32(this.functions[i].signatureIdx));
  5466. }
  5467. return this._buildSection(
  5468. 0x03,
  5469. [
  5470. ...utils.varuint32(entries.length),
  5471. ...[...entries]
  5472. ]
  5473. );
  5474. }
  5475. _buildExports() {
  5476. const entries = [];
  5477. for (let i=0; i< this.exports.length; i++) {
  5478. entries.push([
  5479. ...utils.string(this.exports[i].exportName),
  5480. 0x00,
  5481. ...utils.varuint32(this.exports[i].idx)
  5482. ]);
  5483. }
  5484. return this._buildSection(
  5485. 0x07,
  5486. utils.varuint32(entries.length).concat(...entries)
  5487. );
  5488. }
  5489. _buildCode() {
  5490. const entries = [];
  5491. for (let i=this.nImportFunctions; i< this.nInternalFunctions; i++) {
  5492. entries.push(this.functions[i].getBody());
  5493. }
  5494. return this._buildSection(
  5495. 0x0a,
  5496. utils.varuint32(entries.length).concat(...entries)
  5497. );
  5498. }
  5499. _buildData() {
  5500. const entries = [];
  5501. entries.push([
  5502. 0x00,
  5503. 0x41,
  5504. 0x00,
  5505. 0x0b,
  5506. 0x04,
  5507. ...utils.u32(this.free)
  5508. ]);
  5509. for (let i=0; i< this.datas.length; i++) {
  5510. entries.push([
  5511. 0x00,
  5512. 0x41,
  5513. ...utils.varint32(this.datas[i].offset),
  5514. 0x0b,
  5515. ...utils.varuint32(this.datas[i].bytes.length),
  5516. ...this.datas[i].bytes,
  5517. ]);
  5518. }
  5519. return this._buildSection(
  5520. 0x0b,
  5521. utils.varuint32(entries.length).concat(...entries)
  5522. );
  5523. }
  5524. }
  5525. module.exports = ModuleBuilder;
  5526. },{"./functionbuilder.js":19,"./utils.js":22}],22:[function(require,module,exports){
  5527. var bigInt = require("big-integer");
  5528. function toNumber(n) {
  5529. let v;
  5530. if (typeof n=="string") {
  5531. if (n.slice(0,2).toLowerCase() == "0x") {
  5532. v = bigInt(n.slice(2),16);
  5533. } else {
  5534. v = bigInt(n);
  5535. }
  5536. } else {
  5537. v = bigInt(n);
  5538. }
  5539. return v;
  5540. }
  5541. function u32(n) {
  5542. const b = [];
  5543. const v = toNumber(n);
  5544. b.push(v.and(0xFF).toJSNumber());
  5545. b.push(v.shiftRight(8).and(0xFF).toJSNumber());
  5546. b.push(v.shiftRight(16).and(0xFF).toJSNumber());
  5547. b.push(v.shiftRight(24).and(0xFF).toJSNumber());
  5548. return b;
  5549. }
  5550. function u64(n) {
  5551. const b = [];
  5552. const v = toNumber(n);
  5553. b.push(v.and(0xFF).toJSNumber());
  5554. b.push(v.shiftRight(8).and(0xFF).toJSNumber());
  5555. b.push(v.shiftRight(16).and(0xFF).toJSNumber());
  5556. b.push(v.shiftRight(24).and(0xFF).toJSNumber());
  5557. b.push(v.shiftRight(32).and(0xFF).toJSNumber());
  5558. b.push(v.shiftRight(40).and(0xFF).toJSNumber());
  5559. b.push(v.shiftRight(48).and(0xFF).toJSNumber());
  5560. b.push(v.shiftRight(56).and(0xFF).toJSNumber());
  5561. return b;
  5562. }
  5563. function toUTF8Array(str) {
  5564. var utf8 = [];
  5565. for (var i=0; i < str.length; i++) {
  5566. var charcode = str.charCodeAt(i);
  5567. if (charcode < 0x80) utf8.push(charcode);
  5568. else if (charcode < 0x800) {
  5569. utf8.push(0xc0 | (charcode >> 6),
  5570. 0x80 | (charcode & 0x3f));
  5571. }
  5572. else if (charcode < 0xd800 || charcode >= 0xe000) {
  5573. utf8.push(0xe0 | (charcode >> 12),
  5574. 0x80 | ((charcode>>6) & 0x3f),
  5575. 0x80 | (charcode & 0x3f));
  5576. }
  5577. // surrogate pair
  5578. else {
  5579. i++;
  5580. // UTF-16 encodes 0x10000-0x10FFFF by
  5581. // subtracting 0x10000 and splitting the
  5582. // 20 bits of 0x0-0xFFFFF into two halves
  5583. charcode = 0x10000 + (((charcode & 0x3ff)<<10)
  5584. | (str.charCodeAt(i) & 0x3ff));
  5585. utf8.push(0xf0 | (charcode >>18),
  5586. 0x80 | ((charcode>>12) & 0x3f),
  5587. 0x80 | ((charcode>>6) & 0x3f),
  5588. 0x80 | (charcode & 0x3f));
  5589. }
  5590. }
  5591. return utf8;
  5592. }
  5593. function string(str) {
  5594. const bytes = toUTF8Array(str);
  5595. return [ ...varuint32(bytes.length), ...bytes ];
  5596. }
  5597. function varuint(n) {
  5598. const code = [];
  5599. let v = toNumber(n);
  5600. if (v.isNegative()) throw new Error("Number cannot be negative");
  5601. while (!v.isZero()) {
  5602. code.push(v.and(0x7F).toJSNumber());
  5603. v = v.shiftRight(7);
  5604. }
  5605. if (code.length==0) code.push(0);
  5606. for (let i=0; i<code.length-1; i++) {
  5607. code[i] = code[i] | 0x80;
  5608. }
  5609. return code;
  5610. }
  5611. function varint(_n) {
  5612. let n, sign;
  5613. const bits = _n.bitLength().toJSNumber();
  5614. if (_n<0) {
  5615. sign = true;
  5616. n = bigInt.one.shiftLeft(bits).add(_n);
  5617. } else {
  5618. sign = false;
  5619. n = toNumber(_n);
  5620. }
  5621. const paddingBits = 7 - (bits % 7);
  5622. const padding = bigInt.one.shiftLeft(paddingBits).minus(1).shiftLeft(bits);
  5623. const paddingMask = ((1 << (7 - paddingBits))-1) | 0x80;
  5624. const code = varuint(n.add(padding));
  5625. if (!sign) {
  5626. code[code.length-1] = code[code.length-1] & paddingMask;
  5627. }
  5628. return code;
  5629. }
  5630. function varint32(n) {
  5631. let v = toNumber(n);
  5632. if (v.greater(bigInt("FFFFFFFF", 16))) throw new Error("Number too big");
  5633. if (v.greater(bigInt("7FFFFFFF", 16))) v = v.minus(bigInt("100000000",16));
  5634. if (v.lesser(bigInt("-80000000", 16))) throw new Error("Number too small");
  5635. return varint(v);
  5636. }
  5637. function varint64(n) {
  5638. let v = toNumber(n);
  5639. if (v.greater(bigInt("FFFFFFFFFFFFFFFF", 16))) throw new Error("Number too big");
  5640. if (v.greater(bigInt("7FFFFFFFFFFFFFFF", 16))) v = v.minus(bigInt("10000000000000000",16));
  5641. if (v.lesser(bigInt("-8000000000000000", 16))) throw new Error("Number too small");
  5642. return varint(v);
  5643. }
  5644. function varuint32(n) {
  5645. let v = toNumber(n);
  5646. if (v.greater(bigInt("FFFFFFFF", 16))) throw new Error("Number too big");
  5647. return varuint(v);
  5648. }
  5649. function varuint64(n) {
  5650. let v = toNumber(n);
  5651. if (v.greater(bigInt("FFFFFFFFFFFFFFFF", 16))) throw new Error("Number too big");
  5652. return varuint(v);
  5653. }
  5654. function toHexString(byteArray) {
  5655. return Array.from(byteArray, function(byte) {
  5656. return ("0" + (byte & 0xFF).toString(16)).slice(-2);
  5657. }).join("");
  5658. }
  5659. module.exports.toNumber = toNumber;
  5660. module.exports.u32 = u32;
  5661. module.exports.u64 = u64;
  5662. module.exports.varuint32 = varuint32;
  5663. module.exports.varuint64 = varuint64;
  5664. module.exports.varint32 = varint32;
  5665. module.exports.varint64 = varint64;
  5666. module.exports.string = string;
  5667. module.exports.toHexString = toHexString;
  5668. },{"big-integer":2}],23:[function(require,module,exports){
  5669. /* globals window */
  5670. console.log("Loading groth16/1...");
  5671. const buildF1 = require("./index.js").buildF1;
  5672. const buildBn128 = require("./index.js").buildBn128;
  5673. const buildGroth16 = require("./index.js").buildGroth16;
  5674. const bigInt = require("big-integer");
  5675. buildGroth16().then( (_groth16) => {
  5676. window.groth16 = _groth16;
  5677. });
  5678. window.bigInt = bigInt;
  5679. window.q = bigInt("21888242871839275222246405745257275088696311157297823662689037894645226208583");
  5680. buildF1(window.q).then( (_f1) => { window.F1 = _f1; });
  5681. buildBn128().then( (_bn128) => {
  5682. window.bn128 = _bn128;
  5683. window.pg = window.bn128.g1_allocPoint(
  5684. [ bigInt(1), bigInt(2), bigInt(1)]
  5685. );
  5686. window.pArr = window.bn128.alloc(32*4);
  5687. for (let i=0; i<4; i++) {
  5688. window.bn128.putInt(window.pArr+i*32, i);
  5689. }
  5690. fetch("proving_key.bin").then( (response) => {
  5691. return response.arrayBuffer();
  5692. }).then( (b) => {
  5693. window.provingKey = b;
  5694. window.pProvingKey = window.bn128.putBin(b);
  5695. window.pPointsA = window.pProvingKey + window.bn128.i32[(window.pProvingKey>>2) + 6];
  5696. window.pPointsB2 = window.pProvingKey + window.bn128.i32[(window.pProvingKey>>2) + 7];
  5697. window.nSignals = window.bn128.i32[(window.pProvingKey>>2)];
  5698. });
  5699. fetch("witness.bin").then( (response) => {
  5700. return response.arrayBuffer();
  5701. }).then( (b) => {
  5702. window.signals = b;
  5703. window.pWitness = window.bn128.putBin(b)+4;
  5704. });
  5705. });
  5706. window.calcProof = function() {
  5707. const signals =window.signals.slice(4, 4+window.nSignals*32);
  5708. const start = new Date().getTime();
  5709. window.groth16.proof(signals, window.provingKey).then((p)=> {
  5710. const end = new Date().getTime();
  5711. const time = end - start;
  5712. console.log(JSON.stringify(p, null, 1));
  5713. console.log(time);
  5714. document.getElementById("result").innerHTML = time;
  5715. });
  5716. };
  5717. window.calcPolA = function() {
  5718. const signals =window.signals.slice(4, 4+window.nSignals*32);
  5719. const pkey32 = new Uint32Array(window.provingKey);
  5720. const nSignals = pkey32[0];
  5721. const domainSize = pkey32[2];
  5722. const ppPolsA = pkey32[3];
  5723. const ppPolsB = pkey32[4];
  5724. const ppPolsC = pkey32[5];
  5725. const polsA = window.provingKey.slice(ppPolsA, ppPolsA + ppPolsB);
  5726. const polsB = window.provingKey.slice(ppPolsB, ppPolsB + ppPolsC);
  5727. const pSignals = window.groth16.alloc(signals.byteLength);
  5728. window.groth16.putBin(pSignals, signals);
  5729. const pPolsA = window.groth16.alloc(polsA.byteLength);
  5730. window.groth16.putBin(pPolsA, polsA);
  5731. const pPolsB = window.groth16.alloc(polsB.byteLength);
  5732. window.groth16.putBin(pPolsB, polsB);
  5733. const pSignalsM = window.groth16.alloc(nSignals*32);
  5734. const pPolA = window.groth16.alloc(domainSize*32);
  5735. const pPolB = window.groth16.alloc(domainSize*32);
  5736. const pPolA2 = window.groth16.alloc(domainSize*32*2);
  5737. const pPolB2 = window.groth16.alloc(domainSize*32*2);
  5738. window.groth16.instance.exports.fft_toMontgomeryN(pSignals, pSignalsM, nSignals);
  5739. window.groth16.instance.exports.pol_zero(pPolA, domainSize);
  5740. window.groth16.instance.exports.pol_zero(pPolB, domainSize);
  5741. window.groth16.instance.exports.pol_constructLC(pPolsA, pSignalsM, nSignals, pPolA);
  5742. window.groth16.instance.exports.pol_constructLC(pPolsB, pSignalsM, nSignals, pPolB);
  5743. window.groth16.instance.exports.fft_fromMontgomeryN(pPolA, pPolA, domainSize);
  5744. for (let i=0; i<10; i++) {
  5745. const a = window.groth16.bin2int(window.groth16.getBin(pPolA + i*32, 32));
  5746. console.log(a.toString());
  5747. }
  5748. };
  5749. window.calcPA_p = function() {
  5750. const witness =window.witness.slice(4, 4+window.nSignals*32);
  5751. const oPointsA = new Uint32Array(window.provingKey)[6];
  5752. const pointsA =window.provingKey.slice(oPointsA, oPointsA + window.nSignals*64);
  5753. window.groth16.g1_multiexp(witness, pointsA).then( function(r) {
  5754. const p1 = window.groth16.g1_affine(r);
  5755. const p2 = window.groth16.g1_fromMontgomery(p1);
  5756. const p = window.groth16.bin2g1(p2);
  5757. console.log(p);
  5758. });
  5759. };
  5760. window.calcPA = function(_n, _w) {
  5761. const n = _n || window.nSignals;
  5762. const w = _w || 5;
  5763. const pA = window.bn128.alloc(32*3);
  5764. window.bn128.g1_zero(pA);
  5765. window.bn128.g1_multiexp(
  5766. window.pWitness,
  5767. window.pPointsA,
  5768. n,
  5769. w,
  5770. pA
  5771. );
  5772. window.bn128.g1_affine(pA, pA);
  5773. window.bn128.g1_fromMontgomery(pA, pA);
  5774. const res = window.bn128.g1_getPoint(pA);
  5775. console.log(res[0].toString());
  5776. console.log(res[1].toString());
  5777. console.log(res[2].toString());
  5778. };
  5779. window.calcPB2 = function(_n, _w) {
  5780. const n = _n || window.nSignals;
  5781. const w = _w || 5;
  5782. const pB2 = window.bn128.alloc(32*6);
  5783. window.bn128.g2_zero(pB2);
  5784. window.bn128.g2_multiexp(
  5785. window.pWitness,
  5786. window.pPointsB2,
  5787. n,
  5788. w,
  5789. pB2
  5790. );
  5791. window.bn128.g2_affine(pB2, pB2);
  5792. window.bn128.g2_fromMontgomery(pB2, pB2);
  5793. const res = window.bn128.g2_getPoint(pB2);
  5794. console.log(res[0][0].toString());
  5795. console.log(res[0][1].toString());
  5796. console.log(res[1][0].toString());
  5797. console.log(res[1][1].toString());
  5798. console.log(res[2][0].toString());
  5799. console.log(res[2][1].toString());
  5800. };
  5801. window.test = function() {
  5802. const t = window.F1.test_F1(100000000);
  5803. document.getElementById("result").innerHTML = t;
  5804. };
  5805. },{"./index.js":1,"big-integer":2}],24:[function(require,module,exports){
  5806. (function (global){
  5807. 'use strict';
  5808. // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  5809. // original notice:
  5810. /*!
  5811. * The buffer module from node.js, for the browser.
  5812. *
  5813. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  5814. * @license MIT
  5815. */
  5816. function compare(a, b) {
  5817. if (a === b) {
  5818. return 0;
  5819. }
  5820. var x = a.length;
  5821. var y = b.length;
  5822. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  5823. if (a[i] !== b[i]) {
  5824. x = a[i];
  5825. y = b[i];
  5826. break;
  5827. }
  5828. }
  5829. if (x < y) {
  5830. return -1;
  5831. }
  5832. if (y < x) {
  5833. return 1;
  5834. }
  5835. return 0;
  5836. }
  5837. function isBuffer(b) {
  5838. if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
  5839. return global.Buffer.isBuffer(b);
  5840. }
  5841. return !!(b != null && b._isBuffer);
  5842. }
  5843. // based on node assert, original notice:
  5844. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  5845. //
  5846. // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  5847. //
  5848. // Originally from narwhal.js (http://narwhaljs.org)
  5849. // Copyright (c) 2009 Thomas Robinson <280north.com>
  5850. //
  5851. // Permission is hereby granted, free of charge, to any person obtaining a copy
  5852. // of this software and associated documentation files (the 'Software'), to
  5853. // deal in the Software without restriction, including without limitation the
  5854. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  5855. // sell copies of the Software, and to permit persons to whom the Software is
  5856. // furnished to do so, subject to the following conditions:
  5857. //
  5858. // The above copyright notice and this permission notice shall be included in
  5859. // all copies or substantial portions of the Software.
  5860. //
  5861. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  5862. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  5863. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  5864. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  5865. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  5866. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  5867. var util = require('util/');
  5868. var hasOwn = Object.prototype.hasOwnProperty;
  5869. var pSlice = Array.prototype.slice;
  5870. var functionsHaveNames = (function () {
  5871. return function foo() {}.name === 'foo';
  5872. }());
  5873. function pToString (obj) {
  5874. return Object.prototype.toString.call(obj);
  5875. }
  5876. function isView(arrbuf) {
  5877. if (isBuffer(arrbuf)) {
  5878. return false;
  5879. }
  5880. if (typeof global.ArrayBuffer !== 'function') {
  5881. return false;
  5882. }
  5883. if (typeof ArrayBuffer.isView === 'function') {
  5884. return ArrayBuffer.isView(arrbuf);
  5885. }
  5886. if (!arrbuf) {
  5887. return false;
  5888. }
  5889. if (arrbuf instanceof DataView) {
  5890. return true;
  5891. }
  5892. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  5893. return true;
  5894. }
  5895. return false;
  5896. }
  5897. // 1. The assert module provides functions that throw
  5898. // AssertionError's when particular conditions are not met. The
  5899. // assert module must conform to the following interface.
  5900. var assert = module.exports = ok;
  5901. // 2. The AssertionError is defined in assert.
  5902. // new assert.AssertionError({ message: message,
  5903. // actual: actual,
  5904. // expected: expected })
  5905. var regex = /\s*function\s+([^\(\s]*)\s*/;
  5906. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  5907. function getName(func) {
  5908. if (!util.isFunction(func)) {
  5909. return;
  5910. }
  5911. if (functionsHaveNames) {
  5912. return func.name;
  5913. }
  5914. var str = func.toString();
  5915. var match = str.match(regex);
  5916. return match && match[1];
  5917. }
  5918. assert.AssertionError = function AssertionError(options) {
  5919. this.name = 'AssertionError';
  5920. this.actual = options.actual;
  5921. this.expected = options.expected;
  5922. this.operator = options.operator;
  5923. if (options.message) {
  5924. this.message = options.message;
  5925. this.generatedMessage = false;
  5926. } else {
  5927. this.message = getMessage(this);
  5928. this.generatedMessage = true;
  5929. }
  5930. var stackStartFunction = options.stackStartFunction || fail;
  5931. if (Error.captureStackTrace) {
  5932. Error.captureStackTrace(this, stackStartFunction);
  5933. } else {
  5934. // non v8 browsers so we can have a stacktrace
  5935. var err = new Error();
  5936. if (err.stack) {
  5937. var out = err.stack;
  5938. // try to strip useless frames
  5939. var fn_name = getName(stackStartFunction);
  5940. var idx = out.indexOf('\n' + fn_name);
  5941. if (idx >= 0) {
  5942. // once we have located the function frame
  5943. // we need to strip out everything before it (and its line)
  5944. var next_line = out.indexOf('\n', idx + 1);
  5945. out = out.substring(next_line + 1);
  5946. }
  5947. this.stack = out;
  5948. }
  5949. }
  5950. };
  5951. // assert.AssertionError instanceof Error
  5952. util.inherits(assert.AssertionError, Error);
  5953. function truncate(s, n) {
  5954. if (typeof s === 'string') {
  5955. return s.length < n ? s : s.slice(0, n);
  5956. } else {
  5957. return s;
  5958. }
  5959. }
  5960. function inspect(something) {
  5961. if (functionsHaveNames || !util.isFunction(something)) {
  5962. return util.inspect(something);
  5963. }
  5964. var rawname = getName(something);
  5965. var name = rawname ? ': ' + rawname : '';
  5966. return '[Function' + name + ']';
  5967. }
  5968. function getMessage(self) {
  5969. return truncate(inspect(self.actual), 128) + ' ' +
  5970. self.operator + ' ' +
  5971. truncate(inspect(self.expected), 128);
  5972. }
  5973. // At present only the three keys mentioned above are used and
  5974. // understood by the spec. Implementations or sub modules can pass
  5975. // other keys to the AssertionError's constructor - they will be
  5976. // ignored.
  5977. // 3. All of the following functions must throw an AssertionError
  5978. // when a corresponding condition is not met, with a message that
  5979. // may be undefined if not provided. All assertion methods provide
  5980. // both the actual and expected values to the assertion error for
  5981. // display purposes.
  5982. function fail(actual, expected, message, operator, stackStartFunction) {
  5983. throw new assert.AssertionError({
  5984. message: message,
  5985. actual: actual,
  5986. expected: expected,
  5987. operator: operator,
  5988. stackStartFunction: stackStartFunction
  5989. });
  5990. }
  5991. // EXTENSION! allows for well behaved errors defined elsewhere.
  5992. assert.fail = fail;
  5993. // 4. Pure assertion tests whether a value is truthy, as determined
  5994. // by !!guard.
  5995. // assert.ok(guard, message_opt);
  5996. // This statement is equivalent to assert.equal(true, !!guard,
  5997. // message_opt);. To test strictly for the value true, use
  5998. // assert.strictEqual(true, guard, message_opt);.
  5999. function ok(value, message) {
  6000. if (!value) fail(value, true, message, '==', assert.ok);
  6001. }
  6002. assert.ok = ok;
  6003. // 5. The equality assertion tests shallow, coercive equality with
  6004. // ==.
  6005. // assert.equal(actual, expected, message_opt);
  6006. assert.equal = function equal(actual, expected, message) {
  6007. if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  6008. };
  6009. // 6. The non-equality assertion tests for whether two objects are not equal
  6010. // with != assert.notEqual(actual, expected, message_opt);
  6011. assert.notEqual = function notEqual(actual, expected, message) {
  6012. if (actual == expected) {
  6013. fail(actual, expected, message, '!=', assert.notEqual);
  6014. }
  6015. };
  6016. // 7. The equivalence assertion tests a deep equality relation.
  6017. // assert.deepEqual(actual, expected, message_opt);
  6018. assert.deepEqual = function deepEqual(actual, expected, message) {
  6019. if (!_deepEqual(actual, expected, false)) {
  6020. fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  6021. }
  6022. };
  6023. assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  6024. if (!_deepEqual(actual, expected, true)) {
  6025. fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  6026. }
  6027. };
  6028. function _deepEqual(actual, expected, strict, memos) {
  6029. // 7.1. All identical values are equivalent, as determined by ===.
  6030. if (actual === expected) {
  6031. return true;
  6032. } else if (isBuffer(actual) && isBuffer(expected)) {
  6033. return compare(actual, expected) === 0;
  6034. // 7.2. If the expected value is a Date object, the actual value is
  6035. // equivalent if it is also a Date object that refers to the same time.
  6036. } else if (util.isDate(actual) && util.isDate(expected)) {
  6037. return actual.getTime() === expected.getTime();
  6038. // 7.3 If the expected value is a RegExp object, the actual value is
  6039. // equivalent if it is also a RegExp object with the same source and
  6040. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  6041. } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  6042. return actual.source === expected.source &&
  6043. actual.global === expected.global &&
  6044. actual.multiline === expected.multiline &&
  6045. actual.lastIndex === expected.lastIndex &&
  6046. actual.ignoreCase === expected.ignoreCase;
  6047. // 7.4. Other pairs that do not both pass typeof value == 'object',
  6048. // equivalence is determined by ==.
  6049. } else if ((actual === null || typeof actual !== 'object') &&
  6050. (expected === null || typeof expected !== 'object')) {
  6051. return strict ? actual === expected : actual == expected;
  6052. // If both values are instances of typed arrays, wrap their underlying
  6053. // ArrayBuffers in a Buffer each to increase performance
  6054. // This optimization requires the arrays to have the same type as checked by
  6055. // Object.prototype.toString (aka pToString). Never perform binary
  6056. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  6057. // bit patterns are not identical.
  6058. } else if (isView(actual) && isView(expected) &&
  6059. pToString(actual) === pToString(expected) &&
  6060. !(actual instanceof Float32Array ||
  6061. actual instanceof Float64Array)) {
  6062. return compare(new Uint8Array(actual.buffer),
  6063. new Uint8Array(expected.buffer)) === 0;
  6064. // 7.5 For all other Object pairs, including Array objects, equivalence is
  6065. // determined by having the same number of owned properties (as verified
  6066. // with Object.prototype.hasOwnProperty.call), the same set of keys
  6067. // (although not necessarily the same order), equivalent values for every
  6068. // corresponding key, and an identical 'prototype' property. Note: this
  6069. // accounts for both named and indexed properties on Arrays.
  6070. } else if (isBuffer(actual) !== isBuffer(expected)) {
  6071. return false;
  6072. } else {
  6073. memos = memos || {actual: [], expected: []};
  6074. var actualIndex = memos.actual.indexOf(actual);
  6075. if (actualIndex !== -1) {
  6076. if (actualIndex === memos.expected.indexOf(expected)) {
  6077. return true;
  6078. }
  6079. }
  6080. memos.actual.push(actual);
  6081. memos.expected.push(expected);
  6082. return objEquiv(actual, expected, strict, memos);
  6083. }
  6084. }
  6085. function isArguments(object) {
  6086. return Object.prototype.toString.call(object) == '[object Arguments]';
  6087. }
  6088. function objEquiv(a, b, strict, actualVisitedObjects) {
  6089. if (a === null || a === undefined || b === null || b === undefined)
  6090. return false;
  6091. // if one is a primitive, the other must be same
  6092. if (util.isPrimitive(a) || util.isPrimitive(b))
  6093. return a === b;
  6094. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  6095. return false;
  6096. var aIsArgs = isArguments(a);
  6097. var bIsArgs = isArguments(b);
  6098. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  6099. return false;
  6100. if (aIsArgs) {
  6101. a = pSlice.call(a);
  6102. b = pSlice.call(b);
  6103. return _deepEqual(a, b, strict);
  6104. }
  6105. var ka = objectKeys(a);
  6106. var kb = objectKeys(b);
  6107. var key, i;
  6108. // having the same number of owned properties (keys incorporates
  6109. // hasOwnProperty)
  6110. if (ka.length !== kb.length)
  6111. return false;
  6112. //the same set of keys (although not necessarily the same order),
  6113. ka.sort();
  6114. kb.sort();
  6115. //~~~cheap key test
  6116. for (i = ka.length - 1; i >= 0; i--) {
  6117. if (ka[i] !== kb[i])
  6118. return false;
  6119. }
  6120. //equivalent values for every corresponding key, and
  6121. //~~~possibly expensive deep test
  6122. for (i = ka.length - 1; i >= 0; i--) {
  6123. key = ka[i];
  6124. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  6125. return false;
  6126. }
  6127. return true;
  6128. }
  6129. // 8. The non-equivalence assertion tests for any deep inequality.
  6130. // assert.notDeepEqual(actual, expected, message_opt);
  6131. assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  6132. if (_deepEqual(actual, expected, false)) {
  6133. fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  6134. }
  6135. };
  6136. assert.notDeepStrictEqual = notDeepStrictEqual;
  6137. function notDeepStrictEqual(actual, expected, message) {
  6138. if (_deepEqual(actual, expected, true)) {
  6139. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  6140. }
  6141. }
  6142. // 9. The strict equality assertion tests strict equality, as determined by ===.
  6143. // assert.strictEqual(actual, expected, message_opt);
  6144. assert.strictEqual = function strictEqual(actual, expected, message) {
  6145. if (actual !== expected) {
  6146. fail(actual, expected, message, '===', assert.strictEqual);
  6147. }
  6148. };
  6149. // 10. The strict non-equality assertion tests for strict inequality, as
  6150. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  6151. assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  6152. if (actual === expected) {
  6153. fail(actual, expected, message, '!==', assert.notStrictEqual);
  6154. }
  6155. };
  6156. function expectedException(actual, expected) {
  6157. if (!actual || !expected) {
  6158. return false;
  6159. }
  6160. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  6161. return expected.test(actual);
  6162. }
  6163. try {
  6164. if (actual instanceof expected) {
  6165. return true;
  6166. }
  6167. } catch (e) {
  6168. // Ignore. The instanceof check doesn't work for arrow functions.
  6169. }
  6170. if (Error.isPrototypeOf(expected)) {
  6171. return false;
  6172. }
  6173. return expected.call({}, actual) === true;
  6174. }
  6175. function _tryBlock(block) {
  6176. var error;
  6177. try {
  6178. block();
  6179. } catch (e) {
  6180. error = e;
  6181. }
  6182. return error;
  6183. }
  6184. function _throws(shouldThrow, block, expected, message) {
  6185. var actual;
  6186. if (typeof block !== 'function') {
  6187. throw new TypeError('"block" argument must be a function');
  6188. }
  6189. if (typeof expected === 'string') {
  6190. message = expected;
  6191. expected = null;
  6192. }
  6193. actual = _tryBlock(block);
  6194. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  6195. (message ? ' ' + message : '.');
  6196. if (shouldThrow && !actual) {
  6197. fail(actual, expected, 'Missing expected exception' + message);
  6198. }
  6199. var userProvidedMessage = typeof message === 'string';
  6200. var isUnwantedException = !shouldThrow && util.isError(actual);
  6201. var isUnexpectedException = !shouldThrow && actual && !expected;
  6202. if ((isUnwantedException &&
  6203. userProvidedMessage &&
  6204. expectedException(actual, expected)) ||
  6205. isUnexpectedException) {
  6206. fail(actual, expected, 'Got unwanted exception' + message);
  6207. }
  6208. if ((shouldThrow && actual && expected &&
  6209. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  6210. throw actual;
  6211. }
  6212. }
  6213. // 11. Expected to throw an error:
  6214. // assert.throws(block, Error_opt, message_opt);
  6215. assert.throws = function(block, /*optional*/error, /*optional*/message) {
  6216. _throws(true, block, error, message);
  6217. };
  6218. // EXTENSION! This is annoying to write outside this module.
  6219. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  6220. _throws(false, block, error, message);
  6221. };
  6222. assert.ifError = function(err) { if (err) throw err; };
  6223. var objectKeys = Object.keys || function (obj) {
  6224. var keys = [];
  6225. for (var key in obj) {
  6226. if (hasOwn.call(obj, key)) keys.push(key);
  6227. }
  6228. return keys;
  6229. };
  6230. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  6231. },{"util/":27}],25:[function(require,module,exports){
  6232. if (typeof Object.create === 'function') {
  6233. // implementation from standard node.js 'util' module
  6234. module.exports = function inherits(ctor, superCtor) {
  6235. ctor.super_ = superCtor
  6236. ctor.prototype = Object.create(superCtor.prototype, {
  6237. constructor: {
  6238. value: ctor,
  6239. enumerable: false,
  6240. writable: true,
  6241. configurable: true
  6242. }
  6243. });
  6244. };
  6245. } else {
  6246. // old school shim for old browsers
  6247. module.exports = function inherits(ctor, superCtor) {
  6248. ctor.super_ = superCtor
  6249. var TempCtor = function () {}
  6250. TempCtor.prototype = superCtor.prototype
  6251. ctor.prototype = new TempCtor()
  6252. ctor.prototype.constructor = ctor
  6253. }
  6254. }
  6255. },{}],26:[function(require,module,exports){
  6256. module.exports = function isBuffer(arg) {
  6257. return arg && typeof arg === 'object'
  6258. && typeof arg.copy === 'function'
  6259. && typeof arg.fill === 'function'
  6260. && typeof arg.readUInt8 === 'function';
  6261. }
  6262. },{}],27:[function(require,module,exports){
  6263. (function (process,global){
  6264. // Copyright Joyent, Inc. and other Node contributors.
  6265. //
  6266. // Permission is hereby granted, free of charge, to any person obtaining a
  6267. // copy of this software and associated documentation files (the
  6268. // "Software"), to deal in the Software without restriction, including
  6269. // without limitation the rights to use, copy, modify, merge, publish,
  6270. // distribute, sublicense, and/or sell copies of the Software, and to permit
  6271. // persons to whom the Software is furnished to do so, subject to the
  6272. // following conditions:
  6273. //
  6274. // The above copyright notice and this permission notice shall be included
  6275. // in all copies or substantial portions of the Software.
  6276. //
  6277. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  6278. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  6279. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  6280. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  6281. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  6282. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  6283. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  6284. var formatRegExp = /%[sdj%]/g;
  6285. exports.format = function(f) {
  6286. if (!isString(f)) {
  6287. var objects = [];
  6288. for (var i = 0; i < arguments.length; i++) {
  6289. objects.push(inspect(arguments[i]));
  6290. }
  6291. return objects.join(' ');
  6292. }
  6293. var i = 1;
  6294. var args = arguments;
  6295. var len = args.length;
  6296. var str = String(f).replace(formatRegExp, function(x) {
  6297. if (x === '%%') return '%';
  6298. if (i >= len) return x;
  6299. switch (x) {
  6300. case '%s': return String(args[i++]);
  6301. case '%d': return Number(args[i++]);
  6302. case '%j':
  6303. try {
  6304. return JSON.stringify(args[i++]);
  6305. } catch (_) {
  6306. return '[Circular]';
  6307. }
  6308. default:
  6309. return x;
  6310. }
  6311. });
  6312. for (var x = args[i]; i < len; x = args[++i]) {
  6313. if (isNull(x) || !isObject(x)) {
  6314. str += ' ' + x;
  6315. } else {
  6316. str += ' ' + inspect(x);
  6317. }
  6318. }
  6319. return str;
  6320. };
  6321. // Mark that a method should not be used.
  6322. // Returns a modified function which warns once by default.
  6323. // If --no-deprecation is set, then it is a no-op.
  6324. exports.deprecate = function(fn, msg) {
  6325. // Allow for deprecating things in the process of starting up.
  6326. if (isUndefined(global.process)) {
  6327. return function() {
  6328. return exports.deprecate(fn, msg).apply(this, arguments);
  6329. };
  6330. }
  6331. if (process.noDeprecation === true) {
  6332. return fn;
  6333. }
  6334. var warned = false;
  6335. function deprecated() {
  6336. if (!warned) {
  6337. if (process.throwDeprecation) {
  6338. throw new Error(msg);
  6339. } else if (process.traceDeprecation) {
  6340. console.trace(msg);
  6341. } else {
  6342. console.error(msg);
  6343. }
  6344. warned = true;
  6345. }
  6346. return fn.apply(this, arguments);
  6347. }
  6348. return deprecated;
  6349. };
  6350. var debugs = {};
  6351. var debugEnviron;
  6352. exports.debuglog = function(set) {
  6353. if (isUndefined(debugEnviron))
  6354. debugEnviron = process.env.NODE_DEBUG || '';
  6355. set = set.toUpperCase();
  6356. if (!debugs[set]) {
  6357. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  6358. var pid = process.pid;
  6359. debugs[set] = function() {
  6360. var msg = exports.format.apply(exports, arguments);
  6361. console.error('%s %d: %s', set, pid, msg);
  6362. };
  6363. } else {
  6364. debugs[set] = function() {};
  6365. }
  6366. }
  6367. return debugs[set];
  6368. };
  6369. /**
  6370. * Echos the value of a value. Trys to print the value out
  6371. * in the best way possible given the different types.
  6372. *
  6373. * @param {Object} obj The object to print out.
  6374. * @param {Object} opts Optional options object that alters the output.
  6375. */
  6376. /* legacy: obj, showHidden, depth, colors*/
  6377. function inspect(obj, opts) {
  6378. // default options
  6379. var ctx = {
  6380. seen: [],
  6381. stylize: stylizeNoColor
  6382. };
  6383. // legacy...
  6384. if (arguments.length >= 3) ctx.depth = arguments[2];
  6385. if (arguments.length >= 4) ctx.colors = arguments[3];
  6386. if (isBoolean(opts)) {
  6387. // legacy...
  6388. ctx.showHidden = opts;
  6389. } else if (opts) {
  6390. // got an "options" object
  6391. exports._extend(ctx, opts);
  6392. }
  6393. // set default options
  6394. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  6395. if (isUndefined(ctx.depth)) ctx.depth = 2;
  6396. if (isUndefined(ctx.colors)) ctx.colors = false;
  6397. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  6398. if (ctx.colors) ctx.stylize = stylizeWithColor;
  6399. return formatValue(ctx, obj, ctx.depth);
  6400. }
  6401. exports.inspect = inspect;
  6402. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  6403. inspect.colors = {
  6404. 'bold' : [1, 22],
  6405. 'italic' : [3, 23],
  6406. 'underline' : [4, 24],
  6407. 'inverse' : [7, 27],
  6408. 'white' : [37, 39],
  6409. 'grey' : [90, 39],
  6410. 'black' : [30, 39],
  6411. 'blue' : [34, 39],
  6412. 'cyan' : [36, 39],
  6413. 'green' : [32, 39],
  6414. 'magenta' : [35, 39],
  6415. 'red' : [31, 39],
  6416. 'yellow' : [33, 39]
  6417. };
  6418. // Don't use 'blue' not visible on cmd.exe
  6419. inspect.styles = {
  6420. 'special': 'cyan',
  6421. 'number': 'yellow',
  6422. 'boolean': 'yellow',
  6423. 'undefined': 'grey',
  6424. 'null': 'bold',
  6425. 'string': 'green',
  6426. 'date': 'magenta',
  6427. // "name": intentionally not styling
  6428. 'regexp': 'red'
  6429. };
  6430. function stylizeWithColor(str, styleType) {
  6431. var style = inspect.styles[styleType];
  6432. if (style) {
  6433. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  6434. '\u001b[' + inspect.colors[style][1] + 'm';
  6435. } else {
  6436. return str;
  6437. }
  6438. }
  6439. function stylizeNoColor(str, styleType) {
  6440. return str;
  6441. }
  6442. function arrayToHash(array) {
  6443. var hash = {};
  6444. array.forEach(function(val, idx) {
  6445. hash[val] = true;
  6446. });
  6447. return hash;
  6448. }
  6449. function formatValue(ctx, value, recurseTimes) {
  6450. // Provide a hook for user-specified inspect functions.
  6451. // Check that value is an object with an inspect function on it
  6452. if (ctx.customInspect &&
  6453. value &&
  6454. isFunction(value.inspect) &&
  6455. // Filter out the util module, it's inspect function is special
  6456. value.inspect !== exports.inspect &&
  6457. // Also filter out any prototype objects using the circular check.
  6458. !(value.constructor && value.constructor.prototype === value)) {
  6459. var ret = value.inspect(recurseTimes, ctx);
  6460. if (!isString(ret)) {
  6461. ret = formatValue(ctx, ret, recurseTimes);
  6462. }
  6463. return ret;
  6464. }
  6465. // Primitive types cannot have properties
  6466. var primitive = formatPrimitive(ctx, value);
  6467. if (primitive) {
  6468. return primitive;
  6469. }
  6470. // Look up the keys of the object.
  6471. var keys = Object.keys(value);
  6472. var visibleKeys = arrayToHash(keys);
  6473. if (ctx.showHidden) {
  6474. keys = Object.getOwnPropertyNames(value);
  6475. }
  6476. // IE doesn't make error fields non-enumerable
  6477. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  6478. if (isError(value)
  6479. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  6480. return formatError(value);
  6481. }
  6482. // Some type of object without properties can be shortcutted.
  6483. if (keys.length === 0) {
  6484. if (isFunction(value)) {
  6485. var name = value.name ? ': ' + value.name : '';
  6486. return ctx.stylize('[Function' + name + ']', 'special');
  6487. }
  6488. if (isRegExp(value)) {
  6489. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  6490. }
  6491. if (isDate(value)) {
  6492. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  6493. }
  6494. if (isError(value)) {
  6495. return formatError(value);
  6496. }
  6497. }
  6498. var base = '', array = false, braces = ['{', '}'];
  6499. // Make Array say that they are Array
  6500. if (isArray(value)) {
  6501. array = true;
  6502. braces = ['[', ']'];
  6503. }
  6504. // Make functions say that they are functions
  6505. if (isFunction(value)) {
  6506. var n = value.name ? ': ' + value.name : '';
  6507. base = ' [Function' + n + ']';
  6508. }
  6509. // Make RegExps say that they are RegExps
  6510. if (isRegExp(value)) {
  6511. base = ' ' + RegExp.prototype.toString.call(value);
  6512. }
  6513. // Make dates with properties first say the date
  6514. if (isDate(value)) {
  6515. base = ' ' + Date.prototype.toUTCString.call(value);
  6516. }
  6517. // Make error with message first say the error
  6518. if (isError(value)) {
  6519. base = ' ' + formatError(value);
  6520. }
  6521. if (keys.length === 0 && (!array || value.length == 0)) {
  6522. return braces[0] + base + braces[1];
  6523. }
  6524. if (recurseTimes < 0) {
  6525. if (isRegExp(value)) {
  6526. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  6527. } else {
  6528. return ctx.stylize('[Object]', 'special');
  6529. }
  6530. }
  6531. ctx.seen.push(value);
  6532. var output;
  6533. if (array) {
  6534. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  6535. } else {
  6536. output = keys.map(function(key) {
  6537. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  6538. });
  6539. }
  6540. ctx.seen.pop();
  6541. return reduceToSingleString(output, base, braces);
  6542. }
  6543. function formatPrimitive(ctx, value) {
  6544. if (isUndefined(value))
  6545. return ctx.stylize('undefined', 'undefined');
  6546. if (isString(value)) {
  6547. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  6548. .replace(/'/g, "\\'")
  6549. .replace(/\\"/g, '"') + '\'';
  6550. return ctx.stylize(simple, 'string');
  6551. }
  6552. if (isNumber(value))
  6553. return ctx.stylize('' + value, 'number');
  6554. if (isBoolean(value))
  6555. return ctx.stylize('' + value, 'boolean');
  6556. // For some reason typeof null is "object", so special case here.
  6557. if (isNull(value))
  6558. return ctx.stylize('null', 'null');
  6559. }
  6560. function formatError(value) {
  6561. return '[' + Error.prototype.toString.call(value) + ']';
  6562. }
  6563. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  6564. var output = [];
  6565. for (var i = 0, l = value.length; i < l; ++i) {
  6566. if (hasOwnProperty(value, String(i))) {
  6567. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  6568. String(i), true));
  6569. } else {
  6570. output.push('');
  6571. }
  6572. }
  6573. keys.forEach(function(key) {
  6574. if (!key.match(/^\d+$/)) {
  6575. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  6576. key, true));
  6577. }
  6578. });
  6579. return output;
  6580. }
  6581. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  6582. var name, str, desc;
  6583. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  6584. if (desc.get) {
  6585. if (desc.set) {
  6586. str = ctx.stylize('[Getter/Setter]', 'special');
  6587. } else {
  6588. str = ctx.stylize('[Getter]', 'special');
  6589. }
  6590. } else {
  6591. if (desc.set) {
  6592. str = ctx.stylize('[Setter]', 'special');
  6593. }
  6594. }
  6595. if (!hasOwnProperty(visibleKeys, key)) {
  6596. name = '[' + key + ']';
  6597. }
  6598. if (!str) {
  6599. if (ctx.seen.indexOf(desc.value) < 0) {
  6600. if (isNull(recurseTimes)) {
  6601. str = formatValue(ctx, desc.value, null);
  6602. } else {
  6603. str = formatValue(ctx, desc.value, recurseTimes - 1);
  6604. }
  6605. if (str.indexOf('\n') > -1) {
  6606. if (array) {
  6607. str = str.split('\n').map(function(line) {
  6608. return ' ' + line;
  6609. }).join('\n').substr(2);
  6610. } else {
  6611. str = '\n' + str.split('\n').map(function(line) {
  6612. return ' ' + line;
  6613. }).join('\n');
  6614. }
  6615. }
  6616. } else {
  6617. str = ctx.stylize('[Circular]', 'special');
  6618. }
  6619. }
  6620. if (isUndefined(name)) {
  6621. if (array && key.match(/^\d+$/)) {
  6622. return str;
  6623. }
  6624. name = JSON.stringify('' + key);
  6625. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  6626. name = name.substr(1, name.length - 2);
  6627. name = ctx.stylize(name, 'name');
  6628. } else {
  6629. name = name.replace(/'/g, "\\'")
  6630. .replace(/\\"/g, '"')
  6631. .replace(/(^"|"$)/g, "'");
  6632. name = ctx.stylize(name, 'string');
  6633. }
  6634. }
  6635. return name + ': ' + str;
  6636. }
  6637. function reduceToSingleString(output, base, braces) {
  6638. var numLinesEst = 0;
  6639. var length = output.reduce(function(prev, cur) {
  6640. numLinesEst++;
  6641. if (cur.indexOf('\n') >= 0) numLinesEst++;
  6642. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  6643. }, 0);
  6644. if (length > 60) {
  6645. return braces[0] +
  6646. (base === '' ? '' : base + '\n ') +
  6647. ' ' +
  6648. output.join(',\n ') +
  6649. ' ' +
  6650. braces[1];
  6651. }
  6652. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  6653. }
  6654. // NOTE: These type checking functions intentionally don't use `instanceof`
  6655. // because it is fragile and can be easily faked with `Object.create()`.
  6656. function isArray(ar) {
  6657. return Array.isArray(ar);
  6658. }
  6659. exports.isArray = isArray;
  6660. function isBoolean(arg) {
  6661. return typeof arg === 'boolean';
  6662. }
  6663. exports.isBoolean = isBoolean;
  6664. function isNull(arg) {
  6665. return arg === null;
  6666. }
  6667. exports.isNull = isNull;
  6668. function isNullOrUndefined(arg) {
  6669. return arg == null;
  6670. }
  6671. exports.isNullOrUndefined = isNullOrUndefined;
  6672. function isNumber(arg) {
  6673. return typeof arg === 'number';
  6674. }
  6675. exports.isNumber = isNumber;
  6676. function isString(arg) {
  6677. return typeof arg === 'string';
  6678. }
  6679. exports.isString = isString;
  6680. function isSymbol(arg) {
  6681. return typeof arg === 'symbol';
  6682. }
  6683. exports.isSymbol = isSymbol;
  6684. function isUndefined(arg) {
  6685. return arg === void 0;
  6686. }
  6687. exports.isUndefined = isUndefined;
  6688. function isRegExp(re) {
  6689. return isObject(re) && objectToString(re) === '[object RegExp]';
  6690. }
  6691. exports.isRegExp = isRegExp;
  6692. function isObject(arg) {
  6693. return typeof arg === 'object' && arg !== null;
  6694. }
  6695. exports.isObject = isObject;
  6696. function isDate(d) {
  6697. return isObject(d) && objectToString(d) === '[object Date]';
  6698. }
  6699. exports.isDate = isDate;
  6700. function isError(e) {
  6701. return isObject(e) &&
  6702. (objectToString(e) === '[object Error]' || e instanceof Error);
  6703. }
  6704. exports.isError = isError;
  6705. function isFunction(arg) {
  6706. return typeof arg === 'function';
  6707. }
  6708. exports.isFunction = isFunction;
  6709. function isPrimitive(arg) {
  6710. return arg === null ||
  6711. typeof arg === 'boolean' ||
  6712. typeof arg === 'number' ||
  6713. typeof arg === 'string' ||
  6714. typeof arg === 'symbol' || // ES6 symbol
  6715. typeof arg === 'undefined';
  6716. }
  6717. exports.isPrimitive = isPrimitive;
  6718. exports.isBuffer = require('./support/isBuffer');
  6719. function objectToString(o) {
  6720. return Object.prototype.toString.call(o);
  6721. }
  6722. function pad(n) {
  6723. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  6724. }
  6725. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  6726. 'Oct', 'Nov', 'Dec'];
  6727. // 26 Feb 16:19:34
  6728. function timestamp() {
  6729. var d = new Date();
  6730. var time = [pad(d.getHours()),
  6731. pad(d.getMinutes()),
  6732. pad(d.getSeconds())].join(':');
  6733. return [d.getDate(), months[d.getMonth()], time].join(' ');
  6734. }
  6735. // log is just a thin wrapper to console.log that prepends a timestamp
  6736. exports.log = function() {
  6737. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  6738. };
  6739. /**
  6740. * Inherit the prototype methods from one constructor into another.
  6741. *
  6742. * The Function.prototype.inherits from lang.js rewritten as a standalone
  6743. * function (not on Function.prototype). NOTE: If this file is to be loaded
  6744. * during bootstrapping this function needs to be rewritten using some native
  6745. * functions as prototype setup using normal JavaScript does not work as
  6746. * expected during bootstrapping (see mirror.js in r114903).
  6747. *
  6748. * @param {function} ctor Constructor function which needs to inherit the
  6749. * prototype.
  6750. * @param {function} superCtor Constructor function to inherit prototype from.
  6751. */
  6752. exports.inherits = require('inherits');
  6753. exports._extend = function(origin, add) {
  6754. // Don't do anything if add isn't an object
  6755. if (!add || !isObject(add)) return origin;
  6756. var keys = Object.keys(add);
  6757. var i = keys.length;
  6758. while (i--) {
  6759. origin[keys[i]] = add[keys[i]];
  6760. }
  6761. return origin;
  6762. };
  6763. function hasOwnProperty(obj, prop) {
  6764. return Object.prototype.hasOwnProperty.call(obj, prop);
  6765. }
  6766. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  6767. },{"./support/isBuffer":26,"_process":28,"inherits":25}],28:[function(require,module,exports){
  6768. // shim for using process in browser
  6769. var process = module.exports = {};
  6770. // cached from whatever global is present so that test runners that stub it
  6771. // don't break things. But we need to wrap it in a try catch in case it is
  6772. // wrapped in strict mode code which doesn't define any globals. It's inside a
  6773. // function because try/catches deoptimize in certain engines.
  6774. var cachedSetTimeout;
  6775. var cachedClearTimeout;
  6776. function defaultSetTimout() {
  6777. throw new Error('setTimeout has not been defined');
  6778. }
  6779. function defaultClearTimeout () {
  6780. throw new Error('clearTimeout has not been defined');
  6781. }
  6782. (function () {
  6783. try {
  6784. if (typeof setTimeout === 'function') {
  6785. cachedSetTimeout = setTimeout;
  6786. } else {
  6787. cachedSetTimeout = defaultSetTimout;
  6788. }
  6789. } catch (e) {
  6790. cachedSetTimeout = defaultSetTimout;
  6791. }
  6792. try {
  6793. if (typeof clearTimeout === 'function') {
  6794. cachedClearTimeout = clearTimeout;
  6795. } else {
  6796. cachedClearTimeout = defaultClearTimeout;
  6797. }
  6798. } catch (e) {
  6799. cachedClearTimeout = defaultClearTimeout;
  6800. }
  6801. } ())
  6802. function runTimeout(fun) {
  6803. if (cachedSetTimeout === setTimeout) {
  6804. //normal enviroments in sane situations
  6805. return setTimeout(fun, 0);
  6806. }
  6807. // if setTimeout wasn't available but was latter defined
  6808. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  6809. cachedSetTimeout = setTimeout;
  6810. return setTimeout(fun, 0);
  6811. }
  6812. try {
  6813. // when when somebody has screwed with setTimeout but no I.E. maddness
  6814. return cachedSetTimeout(fun, 0);
  6815. } catch(e){
  6816. try {
  6817. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  6818. return cachedSetTimeout.call(null, fun, 0);
  6819. } catch(e){
  6820. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
  6821. return cachedSetTimeout.call(this, fun, 0);
  6822. }
  6823. }
  6824. }
  6825. function runClearTimeout(marker) {
  6826. if (cachedClearTimeout === clearTimeout) {
  6827. //normal enviroments in sane situations
  6828. return clearTimeout(marker);
  6829. }
  6830. // if clearTimeout wasn't available but was latter defined
  6831. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  6832. cachedClearTimeout = clearTimeout;
  6833. return clearTimeout(marker);
  6834. }
  6835. try {
  6836. // when when somebody has screwed with setTimeout but no I.E. maddness
  6837. return cachedClearTimeout(marker);
  6838. } catch (e){
  6839. try {
  6840. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  6841. return cachedClearTimeout.call(null, marker);
  6842. } catch (e){
  6843. // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
  6844. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  6845. return cachedClearTimeout.call(this, marker);
  6846. }
  6847. }
  6848. }
  6849. var queue = [];
  6850. var draining = false;
  6851. var currentQueue;
  6852. var queueIndex = -1;
  6853. function cleanUpNextTick() {
  6854. if (!draining || !currentQueue) {
  6855. return;
  6856. }
  6857. draining = false;
  6858. if (currentQueue.length) {
  6859. queue = currentQueue.concat(queue);
  6860. } else {
  6861. queueIndex = -1;
  6862. }
  6863. if (queue.length) {
  6864. drainQueue();
  6865. }
  6866. }
  6867. function drainQueue() {
  6868. if (draining) {
  6869. return;
  6870. }
  6871. var timeout = runTimeout(cleanUpNextTick);
  6872. draining = true;
  6873. var len = queue.length;
  6874. while(len) {
  6875. currentQueue = queue;
  6876. queue = [];
  6877. while (++queueIndex < len) {
  6878. if (currentQueue) {
  6879. currentQueue[queueIndex].run();
  6880. }
  6881. }
  6882. queueIndex = -1;
  6883. len = queue.length;
  6884. }
  6885. currentQueue = null;
  6886. draining = false;
  6887. runClearTimeout(timeout);
  6888. }
  6889. process.nextTick = function (fun) {
  6890. var args = new Array(arguments.length - 1);
  6891. if (arguments.length > 1) {
  6892. for (var i = 1; i < arguments.length; i++) {
  6893. args[i - 1] = arguments[i];
  6894. }
  6895. }
  6896. queue.push(new Item(fun, args));
  6897. if (queue.length === 1 && !draining) {
  6898. runTimeout(drainQueue);
  6899. }
  6900. };
  6901. // v8 likes predictible objects
  6902. function Item(fun, array) {
  6903. this.fun = fun;
  6904. this.array = array;
  6905. }
  6906. Item.prototype.run = function () {
  6907. this.fun.apply(null, this.array);
  6908. };
  6909. process.title = 'browser';
  6910. process.browser = true;
  6911. process.env = {};
  6912. process.argv = [];
  6913. process.version = ''; // empty string to avoid regexp issues
  6914. process.versions = {};
  6915. function noop() {}
  6916. process.on = noop;
  6917. process.addListener = noop;
  6918. process.once = noop;
  6919. process.off = noop;
  6920. process.removeListener = noop;
  6921. process.removeAllListeners = noop;
  6922. process.emit = noop;
  6923. process.prependListener = noop;
  6924. process.prependOnceListener = noop;
  6925. process.listeners = function (name) { return [] }
  6926. process.binding = function (name) {
  6927. throw new Error('process.binding is not supported');
  6928. };
  6929. process.cwd = function () { return '/' };
  6930. process.chdir = function (dir) {
  6931. throw new Error('process.chdir is not supported');
  6932. };
  6933. process.umask = function() { return 0; };
  6934. },{}]},{},[23]);