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.

13317 lines
389 KiB

  1. (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.snarkjs = f()}})(function(){var define,module,exports;return (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. (function (global){
  3. 'use strict';
  4. var objectAssign = require('object-assign');
  5. // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
  6. // original notice:
  7. /*!
  8. * The buffer module from node.js, for the browser.
  9. *
  10. * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
  11. * @license MIT
  12. */
  13. function compare(a, b) {
  14. if (a === b) {
  15. return 0;
  16. }
  17. var x = a.length;
  18. var y = b.length;
  19. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  20. if (a[i] !== b[i]) {
  21. x = a[i];
  22. y = b[i];
  23. break;
  24. }
  25. }
  26. if (x < y) {
  27. return -1;
  28. }
  29. if (y < x) {
  30. return 1;
  31. }
  32. return 0;
  33. }
  34. function isBuffer(b) {
  35. if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
  36. return global.Buffer.isBuffer(b);
  37. }
  38. return !!(b != null && b._isBuffer);
  39. }
  40. // based on node assert, original notice:
  41. // NB: The URL to the CommonJS spec is kept just for tradition.
  42. // node-assert has evolved a lot since then, both in API and behavior.
  43. // http://wiki.commonjs.org/wiki/Unit_Testing/1.0
  44. //
  45. // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
  46. //
  47. // Originally from narwhal.js (http://narwhaljs.org)
  48. // Copyright (c) 2009 Thomas Robinson <280north.com>
  49. //
  50. // Permission is hereby granted, free of charge, to any person obtaining a copy
  51. // of this software and associated documentation files (the 'Software'), to
  52. // deal in the Software without restriction, including without limitation the
  53. // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
  54. // sell copies of the Software, and to permit persons to whom the Software is
  55. // furnished to do so, subject to the following conditions:
  56. //
  57. // The above copyright notice and this permission notice shall be included in
  58. // all copies or substantial portions of the Software.
  59. //
  60. // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  61. // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  62. // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  63. // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  64. // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  65. // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  66. var util = require('util/');
  67. var hasOwn = Object.prototype.hasOwnProperty;
  68. var pSlice = Array.prototype.slice;
  69. var functionsHaveNames = (function () {
  70. return function foo() {}.name === 'foo';
  71. }());
  72. function pToString (obj) {
  73. return Object.prototype.toString.call(obj);
  74. }
  75. function isView(arrbuf) {
  76. if (isBuffer(arrbuf)) {
  77. return false;
  78. }
  79. if (typeof global.ArrayBuffer !== 'function') {
  80. return false;
  81. }
  82. if (typeof ArrayBuffer.isView === 'function') {
  83. return ArrayBuffer.isView(arrbuf);
  84. }
  85. if (!arrbuf) {
  86. return false;
  87. }
  88. if (arrbuf instanceof DataView) {
  89. return true;
  90. }
  91. if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  92. return true;
  93. }
  94. return false;
  95. }
  96. // 1. The assert module provides functions that throw
  97. // AssertionError's when particular conditions are not met. The
  98. // assert module must conform to the following interface.
  99. var assert = module.exports = ok;
  100. // 2. The AssertionError is defined in assert.
  101. // new assert.AssertionError({ message: message,
  102. // actual: actual,
  103. // expected: expected })
  104. var regex = /\s*function\s+([^\(\s]*)\s*/;
  105. // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  106. function getName(func) {
  107. if (!util.isFunction(func)) {
  108. return;
  109. }
  110. if (functionsHaveNames) {
  111. return func.name;
  112. }
  113. var str = func.toString();
  114. var match = str.match(regex);
  115. return match && match[1];
  116. }
  117. assert.AssertionError = function AssertionError(options) {
  118. this.name = 'AssertionError';
  119. this.actual = options.actual;
  120. this.expected = options.expected;
  121. this.operator = options.operator;
  122. if (options.message) {
  123. this.message = options.message;
  124. this.generatedMessage = false;
  125. } else {
  126. this.message = getMessage(this);
  127. this.generatedMessage = true;
  128. }
  129. var stackStartFunction = options.stackStartFunction || fail;
  130. if (Error.captureStackTrace) {
  131. Error.captureStackTrace(this, stackStartFunction);
  132. } else {
  133. // non v8 browsers so we can have a stacktrace
  134. var err = new Error();
  135. if (err.stack) {
  136. var out = err.stack;
  137. // try to strip useless frames
  138. var fn_name = getName(stackStartFunction);
  139. var idx = out.indexOf('\n' + fn_name);
  140. if (idx >= 0) {
  141. // once we have located the function frame
  142. // we need to strip out everything before it (and its line)
  143. var next_line = out.indexOf('\n', idx + 1);
  144. out = out.substring(next_line + 1);
  145. }
  146. this.stack = out;
  147. }
  148. }
  149. };
  150. // assert.AssertionError instanceof Error
  151. util.inherits(assert.AssertionError, Error);
  152. function truncate(s, n) {
  153. if (typeof s === 'string') {
  154. return s.length < n ? s : s.slice(0, n);
  155. } else {
  156. return s;
  157. }
  158. }
  159. function inspect(something) {
  160. if (functionsHaveNames || !util.isFunction(something)) {
  161. return util.inspect(something);
  162. }
  163. var rawname = getName(something);
  164. var name = rawname ? ': ' + rawname : '';
  165. return '[Function' + name + ']';
  166. }
  167. function getMessage(self) {
  168. return truncate(inspect(self.actual), 128) + ' ' +
  169. self.operator + ' ' +
  170. truncate(inspect(self.expected), 128);
  171. }
  172. // At present only the three keys mentioned above are used and
  173. // understood by the spec. Implementations or sub modules can pass
  174. // other keys to the AssertionError's constructor - they will be
  175. // ignored.
  176. // 3. All of the following functions must throw an AssertionError
  177. // when a corresponding condition is not met, with a message that
  178. // may be undefined if not provided. All assertion methods provide
  179. // both the actual and expected values to the assertion error for
  180. // display purposes.
  181. function fail(actual, expected, message, operator, stackStartFunction) {
  182. throw new assert.AssertionError({
  183. message: message,
  184. actual: actual,
  185. expected: expected,
  186. operator: operator,
  187. stackStartFunction: stackStartFunction
  188. });
  189. }
  190. // EXTENSION! allows for well behaved errors defined elsewhere.
  191. assert.fail = fail;
  192. // 4. Pure assertion tests whether a value is truthy, as determined
  193. // by !!guard.
  194. // assert.ok(guard, message_opt);
  195. // This statement is equivalent to assert.equal(true, !!guard,
  196. // message_opt);. To test strictly for the value true, use
  197. // assert.strictEqual(true, guard, message_opt);.
  198. function ok(value, message) {
  199. if (!value) fail(value, true, message, '==', assert.ok);
  200. }
  201. assert.ok = ok;
  202. // 5. The equality assertion tests shallow, coercive equality with
  203. // ==.
  204. // assert.equal(actual, expected, message_opt);
  205. assert.equal = function equal(actual, expected, message) {
  206. if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  207. };
  208. // 6. The non-equality assertion tests for whether two objects are not equal
  209. // with != assert.notEqual(actual, expected, message_opt);
  210. assert.notEqual = function notEqual(actual, expected, message) {
  211. if (actual == expected) {
  212. fail(actual, expected, message, '!=', assert.notEqual);
  213. }
  214. };
  215. // 7. The equivalence assertion tests a deep equality relation.
  216. // assert.deepEqual(actual, expected, message_opt);
  217. assert.deepEqual = function deepEqual(actual, expected, message) {
  218. if (!_deepEqual(actual, expected, false)) {
  219. fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  220. }
  221. };
  222. assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  223. if (!_deepEqual(actual, expected, true)) {
  224. fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  225. }
  226. };
  227. function _deepEqual(actual, expected, strict, memos) {
  228. // 7.1. All identical values are equivalent, as determined by ===.
  229. if (actual === expected) {
  230. return true;
  231. } else if (isBuffer(actual) && isBuffer(expected)) {
  232. return compare(actual, expected) === 0;
  233. // 7.2. If the expected value is a Date object, the actual value is
  234. // equivalent if it is also a Date object that refers to the same time.
  235. } else if (util.isDate(actual) && util.isDate(expected)) {
  236. return actual.getTime() === expected.getTime();
  237. // 7.3 If the expected value is a RegExp object, the actual value is
  238. // equivalent if it is also a RegExp object with the same source and
  239. // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  240. } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  241. return actual.source === expected.source &&
  242. actual.global === expected.global &&
  243. actual.multiline === expected.multiline &&
  244. actual.lastIndex === expected.lastIndex &&
  245. actual.ignoreCase === expected.ignoreCase;
  246. // 7.4. Other pairs that do not both pass typeof value == 'object',
  247. // equivalence is determined by ==.
  248. } else if ((actual === null || typeof actual !== 'object') &&
  249. (expected === null || typeof expected !== 'object')) {
  250. return strict ? actual === expected : actual == expected;
  251. // If both values are instances of typed arrays, wrap their underlying
  252. // ArrayBuffers in a Buffer each to increase performance
  253. // This optimization requires the arrays to have the same type as checked by
  254. // Object.prototype.toString (aka pToString). Never perform binary
  255. // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  256. // bit patterns are not identical.
  257. } else if (isView(actual) && isView(expected) &&
  258. pToString(actual) === pToString(expected) &&
  259. !(actual instanceof Float32Array ||
  260. actual instanceof Float64Array)) {
  261. return compare(new Uint8Array(actual.buffer),
  262. new Uint8Array(expected.buffer)) === 0;
  263. // 7.5 For all other Object pairs, including Array objects, equivalence is
  264. // determined by having the same number of owned properties (as verified
  265. // with Object.prototype.hasOwnProperty.call), the same set of keys
  266. // (although not necessarily the same order), equivalent values for every
  267. // corresponding key, and an identical 'prototype' property. Note: this
  268. // accounts for both named and indexed properties on Arrays.
  269. } else if (isBuffer(actual) !== isBuffer(expected)) {
  270. return false;
  271. } else {
  272. memos = memos || {actual: [], expected: []};
  273. var actualIndex = memos.actual.indexOf(actual);
  274. if (actualIndex !== -1) {
  275. if (actualIndex === memos.expected.indexOf(expected)) {
  276. return true;
  277. }
  278. }
  279. memos.actual.push(actual);
  280. memos.expected.push(expected);
  281. return objEquiv(actual, expected, strict, memos);
  282. }
  283. }
  284. function isArguments(object) {
  285. return Object.prototype.toString.call(object) == '[object Arguments]';
  286. }
  287. function objEquiv(a, b, strict, actualVisitedObjects) {
  288. if (a === null || a === undefined || b === null || b === undefined)
  289. return false;
  290. // if one is a primitive, the other must be same
  291. if (util.isPrimitive(a) || util.isPrimitive(b))
  292. return a === b;
  293. if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  294. return false;
  295. var aIsArgs = isArguments(a);
  296. var bIsArgs = isArguments(b);
  297. if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  298. return false;
  299. if (aIsArgs) {
  300. a = pSlice.call(a);
  301. b = pSlice.call(b);
  302. return _deepEqual(a, b, strict);
  303. }
  304. var ka = objectKeys(a);
  305. var kb = objectKeys(b);
  306. var key, i;
  307. // having the same number of owned properties (keys incorporates
  308. // hasOwnProperty)
  309. if (ka.length !== kb.length)
  310. return false;
  311. //the same set of keys (although not necessarily the same order),
  312. ka.sort();
  313. kb.sort();
  314. //~~~cheap key test
  315. for (i = ka.length - 1; i >= 0; i--) {
  316. if (ka[i] !== kb[i])
  317. return false;
  318. }
  319. //equivalent values for every corresponding key, and
  320. //~~~possibly expensive deep test
  321. for (i = ka.length - 1; i >= 0; i--) {
  322. key = ka[i];
  323. if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  324. return false;
  325. }
  326. return true;
  327. }
  328. // 8. The non-equivalence assertion tests for any deep inequality.
  329. // assert.notDeepEqual(actual, expected, message_opt);
  330. assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  331. if (_deepEqual(actual, expected, false)) {
  332. fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  333. }
  334. };
  335. assert.notDeepStrictEqual = notDeepStrictEqual;
  336. function notDeepStrictEqual(actual, expected, message) {
  337. if (_deepEqual(actual, expected, true)) {
  338. fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  339. }
  340. }
  341. // 9. The strict equality assertion tests strict equality, as determined by ===.
  342. // assert.strictEqual(actual, expected, message_opt);
  343. assert.strictEqual = function strictEqual(actual, expected, message) {
  344. if (actual !== expected) {
  345. fail(actual, expected, message, '===', assert.strictEqual);
  346. }
  347. };
  348. // 10. The strict non-equality assertion tests for strict inequality, as
  349. // determined by !==. assert.notStrictEqual(actual, expected, message_opt);
  350. assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  351. if (actual === expected) {
  352. fail(actual, expected, message, '!==', assert.notStrictEqual);
  353. }
  354. };
  355. function expectedException(actual, expected) {
  356. if (!actual || !expected) {
  357. return false;
  358. }
  359. if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  360. return expected.test(actual);
  361. }
  362. try {
  363. if (actual instanceof expected) {
  364. return true;
  365. }
  366. } catch (e) {
  367. // Ignore. The instanceof check doesn't work for arrow functions.
  368. }
  369. if (Error.isPrototypeOf(expected)) {
  370. return false;
  371. }
  372. return expected.call({}, actual) === true;
  373. }
  374. function _tryBlock(block) {
  375. var error;
  376. try {
  377. block();
  378. } catch (e) {
  379. error = e;
  380. }
  381. return error;
  382. }
  383. function _throws(shouldThrow, block, expected, message) {
  384. var actual;
  385. if (typeof block !== 'function') {
  386. throw new TypeError('"block" argument must be a function');
  387. }
  388. if (typeof expected === 'string') {
  389. message = expected;
  390. expected = null;
  391. }
  392. actual = _tryBlock(block);
  393. message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  394. (message ? ' ' + message : '.');
  395. if (shouldThrow && !actual) {
  396. fail(actual, expected, 'Missing expected exception' + message);
  397. }
  398. var userProvidedMessage = typeof message === 'string';
  399. var isUnwantedException = !shouldThrow && util.isError(actual);
  400. var isUnexpectedException = !shouldThrow && actual && !expected;
  401. if ((isUnwantedException &&
  402. userProvidedMessage &&
  403. expectedException(actual, expected)) ||
  404. isUnexpectedException) {
  405. fail(actual, expected, 'Got unwanted exception' + message);
  406. }
  407. if ((shouldThrow && actual && expected &&
  408. !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  409. throw actual;
  410. }
  411. }
  412. // 11. Expected to throw an error:
  413. // assert.throws(block, Error_opt, message_opt);
  414. assert.throws = function(block, /*optional*/error, /*optional*/message) {
  415. _throws(true, block, error, message);
  416. };
  417. // EXTENSION! This is annoying to write outside this module.
  418. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  419. _throws(false, block, error, message);
  420. };
  421. assert.ifError = function(err) { if (err) throw err; };
  422. // Expose a strict only variant of assert
  423. function strict(value, message) {
  424. if (!value) fail(value, true, message, '==', strict);
  425. }
  426. assert.strict = objectAssign(strict, assert, {
  427. equal: assert.strictEqual,
  428. deepEqual: assert.deepStrictEqual,
  429. notEqual: assert.notStrictEqual,
  430. notDeepEqual: assert.notDeepStrictEqual
  431. });
  432. assert.strict.strict = assert.strict;
  433. var objectKeys = Object.keys || function (obj) {
  434. var keys = [];
  435. for (var key in obj) {
  436. if (hasOwn.call(obj, key)) keys.push(key);
  437. }
  438. return keys;
  439. };
  440. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  441. },{"object-assign":38,"util/":4}],2:[function(require,module,exports){
  442. if (typeof Object.create === 'function') {
  443. // implementation from standard node.js 'util' module
  444. module.exports = function inherits(ctor, superCtor) {
  445. ctor.super_ = superCtor
  446. ctor.prototype = Object.create(superCtor.prototype, {
  447. constructor: {
  448. value: ctor,
  449. enumerable: false,
  450. writable: true,
  451. configurable: true
  452. }
  453. });
  454. };
  455. } else {
  456. // old school shim for old browsers
  457. module.exports = function inherits(ctor, superCtor) {
  458. ctor.super_ = superCtor
  459. var TempCtor = function () {}
  460. TempCtor.prototype = superCtor.prototype
  461. ctor.prototype = new TempCtor()
  462. ctor.prototype.constructor = ctor
  463. }
  464. }
  465. },{}],3:[function(require,module,exports){
  466. module.exports = function isBuffer(arg) {
  467. return arg && typeof arg === 'object'
  468. && typeof arg.copy === 'function'
  469. && typeof arg.fill === 'function'
  470. && typeof arg.readUInt8 === 'function';
  471. }
  472. },{}],4:[function(require,module,exports){
  473. (function (process,global){
  474. // Copyright Joyent, Inc. and other Node contributors.
  475. //
  476. // Permission is hereby granted, free of charge, to any person obtaining a
  477. // copy of this software and associated documentation files (the
  478. // "Software"), to deal in the Software without restriction, including
  479. // without limitation the rights to use, copy, modify, merge, publish,
  480. // distribute, sublicense, and/or sell copies of the Software, and to permit
  481. // persons to whom the Software is furnished to do so, subject to the
  482. // following conditions:
  483. //
  484. // The above copyright notice and this permission notice shall be included
  485. // in all copies or substantial portions of the Software.
  486. //
  487. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  488. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  489. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  490. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  491. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  492. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  493. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  494. var formatRegExp = /%[sdj%]/g;
  495. exports.format = function(f) {
  496. if (!isString(f)) {
  497. var objects = [];
  498. for (var i = 0; i < arguments.length; i++) {
  499. objects.push(inspect(arguments[i]));
  500. }
  501. return objects.join(' ');
  502. }
  503. var i = 1;
  504. var args = arguments;
  505. var len = args.length;
  506. var str = String(f).replace(formatRegExp, function(x) {
  507. if (x === '%%') return '%';
  508. if (i >= len) return x;
  509. switch (x) {
  510. case '%s': return String(args[i++]);
  511. case '%d': return Number(args[i++]);
  512. case '%j':
  513. try {
  514. return JSON.stringify(args[i++]);
  515. } catch (_) {
  516. return '[Circular]';
  517. }
  518. default:
  519. return x;
  520. }
  521. });
  522. for (var x = args[i]; i < len; x = args[++i]) {
  523. if (isNull(x) || !isObject(x)) {
  524. str += ' ' + x;
  525. } else {
  526. str += ' ' + inspect(x);
  527. }
  528. }
  529. return str;
  530. };
  531. // Mark that a method should not be used.
  532. // Returns a modified function which warns once by default.
  533. // If --no-deprecation is set, then it is a no-op.
  534. exports.deprecate = function(fn, msg) {
  535. // Allow for deprecating things in the process of starting up.
  536. if (isUndefined(global.process)) {
  537. return function() {
  538. return exports.deprecate(fn, msg).apply(this, arguments);
  539. };
  540. }
  541. if (process.noDeprecation === true) {
  542. return fn;
  543. }
  544. var warned = false;
  545. function deprecated() {
  546. if (!warned) {
  547. if (process.throwDeprecation) {
  548. throw new Error(msg);
  549. } else if (process.traceDeprecation) {
  550. console.trace(msg);
  551. } else {
  552. console.error(msg);
  553. }
  554. warned = true;
  555. }
  556. return fn.apply(this, arguments);
  557. }
  558. return deprecated;
  559. };
  560. var debugs = {};
  561. var debugEnviron;
  562. exports.debuglog = function(set) {
  563. if (isUndefined(debugEnviron))
  564. debugEnviron = process.env.NODE_DEBUG || '';
  565. set = set.toUpperCase();
  566. if (!debugs[set]) {
  567. if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  568. var pid = process.pid;
  569. debugs[set] = function() {
  570. var msg = exports.format.apply(exports, arguments);
  571. console.error('%s %d: %s', set, pid, msg);
  572. };
  573. } else {
  574. debugs[set] = function() {};
  575. }
  576. }
  577. return debugs[set];
  578. };
  579. /**
  580. * Echos the value of a value. Trys to print the value out
  581. * in the best way possible given the different types.
  582. *
  583. * @param {Object} obj The object to print out.
  584. * @param {Object} opts Optional options object that alters the output.
  585. */
  586. /* legacy: obj, showHidden, depth, colors*/
  587. function inspect(obj, opts) {
  588. // default options
  589. var ctx = {
  590. seen: [],
  591. stylize: stylizeNoColor
  592. };
  593. // legacy...
  594. if (arguments.length >= 3) ctx.depth = arguments[2];
  595. if (arguments.length >= 4) ctx.colors = arguments[3];
  596. if (isBoolean(opts)) {
  597. // legacy...
  598. ctx.showHidden = opts;
  599. } else if (opts) {
  600. // got an "options" object
  601. exports._extend(ctx, opts);
  602. }
  603. // set default options
  604. if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  605. if (isUndefined(ctx.depth)) ctx.depth = 2;
  606. if (isUndefined(ctx.colors)) ctx.colors = false;
  607. if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  608. if (ctx.colors) ctx.stylize = stylizeWithColor;
  609. return formatValue(ctx, obj, ctx.depth);
  610. }
  611. exports.inspect = inspect;
  612. // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  613. inspect.colors = {
  614. 'bold' : [1, 22],
  615. 'italic' : [3, 23],
  616. 'underline' : [4, 24],
  617. 'inverse' : [7, 27],
  618. 'white' : [37, 39],
  619. 'grey' : [90, 39],
  620. 'black' : [30, 39],
  621. 'blue' : [34, 39],
  622. 'cyan' : [36, 39],
  623. 'green' : [32, 39],
  624. 'magenta' : [35, 39],
  625. 'red' : [31, 39],
  626. 'yellow' : [33, 39]
  627. };
  628. // Don't use 'blue' not visible on cmd.exe
  629. inspect.styles = {
  630. 'special': 'cyan',
  631. 'number': 'yellow',
  632. 'boolean': 'yellow',
  633. 'undefined': 'grey',
  634. 'null': 'bold',
  635. 'string': 'green',
  636. 'date': 'magenta',
  637. // "name": intentionally not styling
  638. 'regexp': 'red'
  639. };
  640. function stylizeWithColor(str, styleType) {
  641. var style = inspect.styles[styleType];
  642. if (style) {
  643. return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  644. '\u001b[' + inspect.colors[style][1] + 'm';
  645. } else {
  646. return str;
  647. }
  648. }
  649. function stylizeNoColor(str, styleType) {
  650. return str;
  651. }
  652. function arrayToHash(array) {
  653. var hash = {};
  654. array.forEach(function(val, idx) {
  655. hash[val] = true;
  656. });
  657. return hash;
  658. }
  659. function formatValue(ctx, value, recurseTimes) {
  660. // Provide a hook for user-specified inspect functions.
  661. // Check that value is an object with an inspect function on it
  662. if (ctx.customInspect &&
  663. value &&
  664. isFunction(value.inspect) &&
  665. // Filter out the util module, it's inspect function is special
  666. value.inspect !== exports.inspect &&
  667. // Also filter out any prototype objects using the circular check.
  668. !(value.constructor && value.constructor.prototype === value)) {
  669. var ret = value.inspect(recurseTimes, ctx);
  670. if (!isString(ret)) {
  671. ret = formatValue(ctx, ret, recurseTimes);
  672. }
  673. return ret;
  674. }
  675. // Primitive types cannot have properties
  676. var primitive = formatPrimitive(ctx, value);
  677. if (primitive) {
  678. return primitive;
  679. }
  680. // Look up the keys of the object.
  681. var keys = Object.keys(value);
  682. var visibleKeys = arrayToHash(keys);
  683. if (ctx.showHidden) {
  684. keys = Object.getOwnPropertyNames(value);
  685. }
  686. // IE doesn't make error fields non-enumerable
  687. // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  688. if (isError(value)
  689. && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  690. return formatError(value);
  691. }
  692. // Some type of object without properties can be shortcutted.
  693. if (keys.length === 0) {
  694. if (isFunction(value)) {
  695. var name = value.name ? ': ' + value.name : '';
  696. return ctx.stylize('[Function' + name + ']', 'special');
  697. }
  698. if (isRegExp(value)) {
  699. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  700. }
  701. if (isDate(value)) {
  702. return ctx.stylize(Date.prototype.toString.call(value), 'date');
  703. }
  704. if (isError(value)) {
  705. return formatError(value);
  706. }
  707. }
  708. var base = '', array = false, braces = ['{', '}'];
  709. // Make Array say that they are Array
  710. if (isArray(value)) {
  711. array = true;
  712. braces = ['[', ']'];
  713. }
  714. // Make functions say that they are functions
  715. if (isFunction(value)) {
  716. var n = value.name ? ': ' + value.name : '';
  717. base = ' [Function' + n + ']';
  718. }
  719. // Make RegExps say that they are RegExps
  720. if (isRegExp(value)) {
  721. base = ' ' + RegExp.prototype.toString.call(value);
  722. }
  723. // Make dates with properties first say the date
  724. if (isDate(value)) {
  725. base = ' ' + Date.prototype.toUTCString.call(value);
  726. }
  727. // Make error with message first say the error
  728. if (isError(value)) {
  729. base = ' ' + formatError(value);
  730. }
  731. if (keys.length === 0 && (!array || value.length == 0)) {
  732. return braces[0] + base + braces[1];
  733. }
  734. if (recurseTimes < 0) {
  735. if (isRegExp(value)) {
  736. return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  737. } else {
  738. return ctx.stylize('[Object]', 'special');
  739. }
  740. }
  741. ctx.seen.push(value);
  742. var output;
  743. if (array) {
  744. output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  745. } else {
  746. output = keys.map(function(key) {
  747. return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  748. });
  749. }
  750. ctx.seen.pop();
  751. return reduceToSingleString(output, base, braces);
  752. }
  753. function formatPrimitive(ctx, value) {
  754. if (isUndefined(value))
  755. return ctx.stylize('undefined', 'undefined');
  756. if (isString(value)) {
  757. var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  758. .replace(/'/g, "\\'")
  759. .replace(/\\"/g, '"') + '\'';
  760. return ctx.stylize(simple, 'string');
  761. }
  762. if (isNumber(value))
  763. return ctx.stylize('' + value, 'number');
  764. if (isBoolean(value))
  765. return ctx.stylize('' + value, 'boolean');
  766. // For some reason typeof null is "object", so special case here.
  767. if (isNull(value))
  768. return ctx.stylize('null', 'null');
  769. }
  770. function formatError(value) {
  771. return '[' + Error.prototype.toString.call(value) + ']';
  772. }
  773. function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  774. var output = [];
  775. for (var i = 0, l = value.length; i < l; ++i) {
  776. if (hasOwnProperty(value, String(i))) {
  777. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  778. String(i), true));
  779. } else {
  780. output.push('');
  781. }
  782. }
  783. keys.forEach(function(key) {
  784. if (!key.match(/^\d+$/)) {
  785. output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  786. key, true));
  787. }
  788. });
  789. return output;
  790. }
  791. function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  792. var name, str, desc;
  793. desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  794. if (desc.get) {
  795. if (desc.set) {
  796. str = ctx.stylize('[Getter/Setter]', 'special');
  797. } else {
  798. str = ctx.stylize('[Getter]', 'special');
  799. }
  800. } else {
  801. if (desc.set) {
  802. str = ctx.stylize('[Setter]', 'special');
  803. }
  804. }
  805. if (!hasOwnProperty(visibleKeys, key)) {
  806. name = '[' + key + ']';
  807. }
  808. if (!str) {
  809. if (ctx.seen.indexOf(desc.value) < 0) {
  810. if (isNull(recurseTimes)) {
  811. str = formatValue(ctx, desc.value, null);
  812. } else {
  813. str = formatValue(ctx, desc.value, recurseTimes - 1);
  814. }
  815. if (str.indexOf('\n') > -1) {
  816. if (array) {
  817. str = str.split('\n').map(function(line) {
  818. return ' ' + line;
  819. }).join('\n').substr(2);
  820. } else {
  821. str = '\n' + str.split('\n').map(function(line) {
  822. return ' ' + line;
  823. }).join('\n');
  824. }
  825. }
  826. } else {
  827. str = ctx.stylize('[Circular]', 'special');
  828. }
  829. }
  830. if (isUndefined(name)) {
  831. if (array && key.match(/^\d+$/)) {
  832. return str;
  833. }
  834. name = JSON.stringify('' + key);
  835. if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  836. name = name.substr(1, name.length - 2);
  837. name = ctx.stylize(name, 'name');
  838. } else {
  839. name = name.replace(/'/g, "\\'")
  840. .replace(/\\"/g, '"')
  841. .replace(/(^"|"$)/g, "'");
  842. name = ctx.stylize(name, 'string');
  843. }
  844. }
  845. return name + ': ' + str;
  846. }
  847. function reduceToSingleString(output, base, braces) {
  848. var numLinesEst = 0;
  849. var length = output.reduce(function(prev, cur) {
  850. numLinesEst++;
  851. if (cur.indexOf('\n') >= 0) numLinesEst++;
  852. return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  853. }, 0);
  854. if (length > 60) {
  855. return braces[0] +
  856. (base === '' ? '' : base + '\n ') +
  857. ' ' +
  858. output.join(',\n ') +
  859. ' ' +
  860. braces[1];
  861. }
  862. return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  863. }
  864. // NOTE: These type checking functions intentionally don't use `instanceof`
  865. // because it is fragile and can be easily faked with `Object.create()`.
  866. function isArray(ar) {
  867. return Array.isArray(ar);
  868. }
  869. exports.isArray = isArray;
  870. function isBoolean(arg) {
  871. return typeof arg === 'boolean';
  872. }
  873. exports.isBoolean = isBoolean;
  874. function isNull(arg) {
  875. return arg === null;
  876. }
  877. exports.isNull = isNull;
  878. function isNullOrUndefined(arg) {
  879. return arg == null;
  880. }
  881. exports.isNullOrUndefined = isNullOrUndefined;
  882. function isNumber(arg) {
  883. return typeof arg === 'number';
  884. }
  885. exports.isNumber = isNumber;
  886. function isString(arg) {
  887. return typeof arg === 'string';
  888. }
  889. exports.isString = isString;
  890. function isSymbol(arg) {
  891. return typeof arg === 'symbol';
  892. }
  893. exports.isSymbol = isSymbol;
  894. function isUndefined(arg) {
  895. return arg === void 0;
  896. }
  897. exports.isUndefined = isUndefined;
  898. function isRegExp(re) {
  899. return isObject(re) && objectToString(re) === '[object RegExp]';
  900. }
  901. exports.isRegExp = isRegExp;
  902. function isObject(arg) {
  903. return typeof arg === 'object' && arg !== null;
  904. }
  905. exports.isObject = isObject;
  906. function isDate(d) {
  907. return isObject(d) && objectToString(d) === '[object Date]';
  908. }
  909. exports.isDate = isDate;
  910. function isError(e) {
  911. return isObject(e) &&
  912. (objectToString(e) === '[object Error]' || e instanceof Error);
  913. }
  914. exports.isError = isError;
  915. function isFunction(arg) {
  916. return typeof arg === 'function';
  917. }
  918. exports.isFunction = isFunction;
  919. function isPrimitive(arg) {
  920. return arg === null ||
  921. typeof arg === 'boolean' ||
  922. typeof arg === 'number' ||
  923. typeof arg === 'string' ||
  924. typeof arg === 'symbol' || // ES6 symbol
  925. typeof arg === 'undefined';
  926. }
  927. exports.isPrimitive = isPrimitive;
  928. exports.isBuffer = require('./support/isBuffer');
  929. function objectToString(o) {
  930. return Object.prototype.toString.call(o);
  931. }
  932. function pad(n) {
  933. return n < 10 ? '0' + n.toString(10) : n.toString(10);
  934. }
  935. var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
  936. 'Oct', 'Nov', 'Dec'];
  937. // 26 Feb 16:19:34
  938. function timestamp() {
  939. var d = new Date();
  940. var time = [pad(d.getHours()),
  941. pad(d.getMinutes()),
  942. pad(d.getSeconds())].join(':');
  943. return [d.getDate(), months[d.getMonth()], time].join(' ');
  944. }
  945. // log is just a thin wrapper to console.log that prepends a timestamp
  946. exports.log = function() {
  947. console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
  948. };
  949. /**
  950. * Inherit the prototype methods from one constructor into another.
  951. *
  952. * The Function.prototype.inherits from lang.js rewritten as a standalone
  953. * function (not on Function.prototype). NOTE: If this file is to be loaded
  954. * during bootstrapping this function needs to be rewritten using some native
  955. * functions as prototype setup using normal JavaScript does not work as
  956. * expected during bootstrapping (see mirror.js in r114903).
  957. *
  958. * @param {function} ctor Constructor function which needs to inherit the
  959. * prototype.
  960. * @param {function} superCtor Constructor function to inherit prototype from.
  961. */
  962. exports.inherits = require('inherits');
  963. exports._extend = function(origin, add) {
  964. // Don't do anything if add isn't an object
  965. if (!add || !isObject(add)) return origin;
  966. var keys = Object.keys(add);
  967. var i = keys.length;
  968. while (i--) {
  969. origin[keys[i]] = add[keys[i]];
  970. }
  971. return origin;
  972. };
  973. function hasOwnProperty(obj, prop) {
  974. return Object.prototype.hasOwnProperty.call(obj, prop);
  975. }
  976. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  977. },{"./support/isBuffer":3,"_process":9,"inherits":2}],5:[function(require,module,exports){
  978. 'use strict'
  979. exports.byteLength = byteLength
  980. exports.toByteArray = toByteArray
  981. exports.fromByteArray = fromByteArray
  982. var lookup = []
  983. var revLookup = []
  984. var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
  985. var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
  986. for (var i = 0, len = code.length; i < len; ++i) {
  987. lookup[i] = code[i]
  988. revLookup[code.charCodeAt(i)] = i
  989. }
  990. // Support decoding URL-safe base64 strings, as Node.js does.
  991. // See: https://en.wikipedia.org/wiki/Base64#URL_applications
  992. revLookup['-'.charCodeAt(0)] = 62
  993. revLookup['_'.charCodeAt(0)] = 63
  994. function getLens (b64) {
  995. var len = b64.length
  996. if (len % 4 > 0) {
  997. throw new Error('Invalid string. Length must be a multiple of 4')
  998. }
  999. // Trim off extra bytes after placeholder bytes are found
  1000. // See: https://github.com/beatgammit/base64-js/issues/42
  1001. var validLen = b64.indexOf('=')
  1002. if (validLen === -1) validLen = len
  1003. var placeHoldersLen = validLen === len
  1004. ? 0
  1005. : 4 - (validLen % 4)
  1006. return [validLen, placeHoldersLen]
  1007. }
  1008. // base64 is 4/3 + up to two characters of the original data
  1009. function byteLength (b64) {
  1010. var lens = getLens(b64)
  1011. var validLen = lens[0]
  1012. var placeHoldersLen = lens[1]
  1013. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1014. }
  1015. function _byteLength (b64, validLen, placeHoldersLen) {
  1016. return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
  1017. }
  1018. function toByteArray (b64) {
  1019. var tmp
  1020. var lens = getLens(b64)
  1021. var validLen = lens[0]
  1022. var placeHoldersLen = lens[1]
  1023. var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
  1024. var curByte = 0
  1025. // if there are placeholders, only get up to the last complete 4 chars
  1026. var len = placeHoldersLen > 0
  1027. ? validLen - 4
  1028. : validLen
  1029. var i
  1030. for (i = 0; i < len; i += 4) {
  1031. tmp =
  1032. (revLookup[b64.charCodeAt(i)] << 18) |
  1033. (revLookup[b64.charCodeAt(i + 1)] << 12) |
  1034. (revLookup[b64.charCodeAt(i + 2)] << 6) |
  1035. revLookup[b64.charCodeAt(i + 3)]
  1036. arr[curByte++] = (tmp >> 16) & 0xFF
  1037. arr[curByte++] = (tmp >> 8) & 0xFF
  1038. arr[curByte++] = tmp & 0xFF
  1039. }
  1040. if (placeHoldersLen === 2) {
  1041. tmp =
  1042. (revLookup[b64.charCodeAt(i)] << 2) |
  1043. (revLookup[b64.charCodeAt(i + 1)] >> 4)
  1044. arr[curByte++] = tmp & 0xFF
  1045. }
  1046. if (placeHoldersLen === 1) {
  1047. tmp =
  1048. (revLookup[b64.charCodeAt(i)] << 10) |
  1049. (revLookup[b64.charCodeAt(i + 1)] << 4) |
  1050. (revLookup[b64.charCodeAt(i + 2)] >> 2)
  1051. arr[curByte++] = (tmp >> 8) & 0xFF
  1052. arr[curByte++] = tmp & 0xFF
  1053. }
  1054. return arr
  1055. }
  1056. function tripletToBase64 (num) {
  1057. return lookup[num >> 18 & 0x3F] +
  1058. lookup[num >> 12 & 0x3F] +
  1059. lookup[num >> 6 & 0x3F] +
  1060. lookup[num & 0x3F]
  1061. }
  1062. function encodeChunk (uint8, start, end) {
  1063. var tmp
  1064. var output = []
  1065. for (var i = start; i < end; i += 3) {
  1066. tmp =
  1067. ((uint8[i] << 16) & 0xFF0000) +
  1068. ((uint8[i + 1] << 8) & 0xFF00) +
  1069. (uint8[i + 2] & 0xFF)
  1070. output.push(tripletToBase64(tmp))
  1071. }
  1072. return output.join('')
  1073. }
  1074. function fromByteArray (uint8) {
  1075. var tmp
  1076. var len = uint8.length
  1077. var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
  1078. var parts = []
  1079. var maxChunkLength = 16383 // must be multiple of 3
  1080. // go through the array every three bytes, we'll deal with trailing stuff later
  1081. for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
  1082. parts.push(encodeChunk(
  1083. uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
  1084. ))
  1085. }
  1086. // pad the end with zeros, but make sure to not forget the extra bytes
  1087. if (extraBytes === 1) {
  1088. tmp = uint8[len - 1]
  1089. parts.push(
  1090. lookup[tmp >> 2] +
  1091. lookup[(tmp << 4) & 0x3F] +
  1092. '=='
  1093. )
  1094. } else if (extraBytes === 2) {
  1095. tmp = (uint8[len - 2] << 8) + uint8[len - 1]
  1096. parts.push(
  1097. lookup[tmp >> 10] +
  1098. lookup[(tmp >> 4) & 0x3F] +
  1099. lookup[(tmp << 2) & 0x3F] +
  1100. '='
  1101. )
  1102. }
  1103. return parts.join('')
  1104. }
  1105. },{}],6:[function(require,module,exports){
  1106. var bigInt = (function (undefined) {
  1107. "use strict";
  1108. var BASE = 1e7,
  1109. LOG_BASE = 7,
  1110. MAX_INT = 9007199254740992,
  1111. MAX_INT_ARR = smallToArray(MAX_INT),
  1112. DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
  1113. var supportsNativeBigInt = typeof BigInt === "function";
  1114. function Integer(v, radix, alphabet, caseSensitive) {
  1115. if (typeof v === "undefined") return Integer[0];
  1116. if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);
  1117. return parseValue(v);
  1118. }
  1119. function BigInteger(value, sign) {
  1120. this.value = value;
  1121. this.sign = sign;
  1122. this.isSmall = false;
  1123. }
  1124. BigInteger.prototype = Object.create(Integer.prototype);
  1125. function SmallInteger(value) {
  1126. this.value = value;
  1127. this.sign = value < 0;
  1128. this.isSmall = true;
  1129. }
  1130. SmallInteger.prototype = Object.create(Integer.prototype);
  1131. function NativeBigInt(value) {
  1132. this.value = value;
  1133. }
  1134. NativeBigInt.prototype = Object.create(Integer.prototype);
  1135. function isPrecise(n) {
  1136. return -MAX_INT < n && n < MAX_INT;
  1137. }
  1138. function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
  1139. if (n < 1e7)
  1140. return [n];
  1141. if (n < 1e14)
  1142. return [n % 1e7, Math.floor(n / 1e7)];
  1143. return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
  1144. }
  1145. function arrayToSmall(arr) { // If BASE changes this function may need to change
  1146. trim(arr);
  1147. var length = arr.length;
  1148. if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
  1149. switch (length) {
  1150. case 0: return 0;
  1151. case 1: return arr[0];
  1152. case 2: return arr[0] + arr[1] * BASE;
  1153. default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
  1154. }
  1155. }
  1156. return arr;
  1157. }
  1158. function trim(v) {
  1159. var i = v.length;
  1160. while (v[--i] === 0);
  1161. v.length = i + 1;
  1162. }
  1163. function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
  1164. var x = new Array(length);
  1165. var i = -1;
  1166. while (++i < length) {
  1167. x[i] = 0;
  1168. }
  1169. return x;
  1170. }
  1171. function truncate(n) {
  1172. if (n > 0) return Math.floor(n);
  1173. return Math.ceil(n);
  1174. }
  1175. function add(a, b) { // assumes a and b are arrays with a.length >= b.length
  1176. var l_a = a.length,
  1177. l_b = b.length,
  1178. r = new Array(l_a),
  1179. carry = 0,
  1180. base = BASE,
  1181. sum, i;
  1182. for (i = 0; i < l_b; i++) {
  1183. sum = a[i] + b[i] + carry;
  1184. carry = sum >= base ? 1 : 0;
  1185. r[i] = sum - carry * base;
  1186. }
  1187. while (i < l_a) {
  1188. sum = a[i] + carry;
  1189. carry = sum === base ? 1 : 0;
  1190. r[i++] = sum - carry * base;
  1191. }
  1192. if (carry > 0) r.push(carry);
  1193. return r;
  1194. }
  1195. function addAny(a, b) {
  1196. if (a.length >= b.length) return add(a, b);
  1197. return add(b, a);
  1198. }
  1199. function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
  1200. var l = a.length,
  1201. r = new Array(l),
  1202. base = BASE,
  1203. sum, i;
  1204. for (i = 0; i < l; i++) {
  1205. sum = a[i] - base + carry;
  1206. carry = Math.floor(sum / base);
  1207. r[i] = sum - carry * base;
  1208. carry += 1;
  1209. }
  1210. while (carry > 0) {
  1211. r[i++] = carry % base;
  1212. carry = Math.floor(carry / base);
  1213. }
  1214. return r;
  1215. }
  1216. BigInteger.prototype.add = function (v) {
  1217. var n = parseValue(v);
  1218. if (this.sign !== n.sign) {
  1219. return this.subtract(n.negate());
  1220. }
  1221. var a = this.value, b = n.value;
  1222. if (n.isSmall) {
  1223. return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
  1224. }
  1225. return new BigInteger(addAny(a, b), this.sign);
  1226. };
  1227. BigInteger.prototype.plus = BigInteger.prototype.add;
  1228. SmallInteger.prototype.add = function (v) {
  1229. var n = parseValue(v);
  1230. var a = this.value;
  1231. if (a < 0 !== n.sign) {
  1232. return this.subtract(n.negate());
  1233. }
  1234. var b = n.value;
  1235. if (n.isSmall) {
  1236. if (isPrecise(a + b)) return new SmallInteger(a + b);
  1237. b = smallToArray(Math.abs(b));
  1238. }
  1239. return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
  1240. };
  1241. SmallInteger.prototype.plus = SmallInteger.prototype.add;
  1242. NativeBigInt.prototype.add = function (v) {
  1243. return new NativeBigInt(this.value + parseValue(v).value);
  1244. }
  1245. NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
  1246. function subtract(a, b) { // assumes a and b are arrays with a >= b
  1247. var a_l = a.length,
  1248. b_l = b.length,
  1249. r = new Array(a_l),
  1250. borrow = 0,
  1251. base = BASE,
  1252. i, difference;
  1253. for (i = 0; i < b_l; i++) {
  1254. difference = a[i] - borrow - b[i];
  1255. if (difference < 0) {
  1256. difference += base;
  1257. borrow = 1;
  1258. } else borrow = 0;
  1259. r[i] = difference;
  1260. }
  1261. for (i = b_l; i < a_l; i++) {
  1262. difference = a[i] - borrow;
  1263. if (difference < 0) difference += base;
  1264. else {
  1265. r[i++] = difference;
  1266. break;
  1267. }
  1268. r[i] = difference;
  1269. }
  1270. for (; i < a_l; i++) {
  1271. r[i] = a[i];
  1272. }
  1273. trim(r);
  1274. return r;
  1275. }
  1276. function subtractAny(a, b, sign) {
  1277. var value;
  1278. if (compareAbs(a, b) >= 0) {
  1279. value = subtract(a, b);
  1280. } else {
  1281. value = subtract(b, a);
  1282. sign = !sign;
  1283. }
  1284. value = arrayToSmall(value);
  1285. if (typeof value === "number") {
  1286. if (sign) value = -value;
  1287. return new SmallInteger(value);
  1288. }
  1289. return new BigInteger(value, sign);
  1290. }
  1291. function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
  1292. var l = a.length,
  1293. r = new Array(l),
  1294. carry = -b,
  1295. base = BASE,
  1296. i, difference;
  1297. for (i = 0; i < l; i++) {
  1298. difference = a[i] + carry;
  1299. carry = Math.floor(difference / base);
  1300. difference %= base;
  1301. r[i] = difference < 0 ? difference + base : difference;
  1302. }
  1303. r = arrayToSmall(r);
  1304. if (typeof r === "number") {
  1305. if (sign) r = -r;
  1306. return new SmallInteger(r);
  1307. } return new BigInteger(r, sign);
  1308. }
  1309. BigInteger.prototype.subtract = function (v) {
  1310. var n = parseValue(v);
  1311. if (this.sign !== n.sign) {
  1312. return this.add(n.negate());
  1313. }
  1314. var a = this.value, b = n.value;
  1315. if (n.isSmall)
  1316. return subtractSmall(a, Math.abs(b), this.sign);
  1317. return subtractAny(a, b, this.sign);
  1318. };
  1319. BigInteger.prototype.minus = BigInteger.prototype.subtract;
  1320. SmallInteger.prototype.subtract = function (v) {
  1321. var n = parseValue(v);
  1322. var a = this.value;
  1323. if (a < 0 !== n.sign) {
  1324. return this.add(n.negate());
  1325. }
  1326. var b = n.value;
  1327. if (n.isSmall) {
  1328. return new SmallInteger(a - b);
  1329. }
  1330. return subtractSmall(b, Math.abs(a), a >= 0);
  1331. };
  1332. SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
  1333. NativeBigInt.prototype.subtract = function (v) {
  1334. return new NativeBigInt(this.value - parseValue(v).value);
  1335. }
  1336. NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
  1337. BigInteger.prototype.negate = function () {
  1338. return new BigInteger(this.value, !this.sign);
  1339. };
  1340. SmallInteger.prototype.negate = function () {
  1341. var sign = this.sign;
  1342. var small = new SmallInteger(-this.value);
  1343. small.sign = !sign;
  1344. return small;
  1345. };
  1346. NativeBigInt.prototype.negate = function () {
  1347. return new NativeBigInt(-this.value);
  1348. }
  1349. BigInteger.prototype.abs = function () {
  1350. return new BigInteger(this.value, false);
  1351. };
  1352. SmallInteger.prototype.abs = function () {
  1353. return new SmallInteger(Math.abs(this.value));
  1354. };
  1355. NativeBigInt.prototype.abs = function () {
  1356. return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
  1357. }
  1358. function multiplyLong(a, b) {
  1359. var a_l = a.length,
  1360. b_l = b.length,
  1361. l = a_l + b_l,
  1362. r = createArray(l),
  1363. base = BASE,
  1364. product, carry, i, a_i, b_j;
  1365. for (i = 0; i < a_l; ++i) {
  1366. a_i = a[i];
  1367. for (var j = 0; j < b_l; ++j) {
  1368. b_j = b[j];
  1369. product = a_i * b_j + r[i + j];
  1370. carry = Math.floor(product / base);
  1371. r[i + j] = product - carry * base;
  1372. r[i + j + 1] += carry;
  1373. }
  1374. }
  1375. trim(r);
  1376. return r;
  1377. }
  1378. function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
  1379. var l = a.length,
  1380. r = new Array(l),
  1381. base = BASE,
  1382. carry = 0,
  1383. product, i;
  1384. for (i = 0; i < l; i++) {
  1385. product = a[i] * b + carry;
  1386. carry = Math.floor(product / base);
  1387. r[i] = product - carry * base;
  1388. }
  1389. while (carry > 0) {
  1390. r[i++] = carry % base;
  1391. carry = Math.floor(carry / base);
  1392. }
  1393. return r;
  1394. }
  1395. function shiftLeft(x, n) {
  1396. var r = [];
  1397. while (n-- > 0) r.push(0);
  1398. return r.concat(x);
  1399. }
  1400. function multiplyKaratsuba(x, y) {
  1401. var n = Math.max(x.length, y.length);
  1402. if (n <= 30) return multiplyLong(x, y);
  1403. n = Math.ceil(n / 2);
  1404. var b = x.slice(n),
  1405. a = x.slice(0, n),
  1406. d = y.slice(n),
  1407. c = y.slice(0, n);
  1408. var ac = multiplyKaratsuba(a, c),
  1409. bd = multiplyKaratsuba(b, d),
  1410. abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
  1411. var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
  1412. trim(product);
  1413. return product;
  1414. }
  1415. // The following function is derived from a surface fit of a graph plotting the performance difference
  1416. // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
  1417. function useKaratsuba(l1, l2) {
  1418. return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
  1419. }
  1420. BigInteger.prototype.multiply = function (v) {
  1421. var n = parseValue(v),
  1422. a = this.value, b = n.value,
  1423. sign = this.sign !== n.sign,
  1424. abs;
  1425. if (n.isSmall) {
  1426. if (b === 0) return Integer[0];
  1427. if (b === 1) return this;
  1428. if (b === -1) return this.negate();
  1429. abs = Math.abs(b);
  1430. if (abs < BASE) {
  1431. return new BigInteger(multiplySmall(a, abs), sign);
  1432. }
  1433. b = smallToArray(abs);
  1434. }
  1435. if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
  1436. return new BigInteger(multiplyKaratsuba(a, b), sign);
  1437. return new BigInteger(multiplyLong(a, b), sign);
  1438. };
  1439. BigInteger.prototype.times = BigInteger.prototype.multiply;
  1440. function multiplySmallAndArray(a, b, sign) { // a >= 0
  1441. if (a < BASE) {
  1442. return new BigInteger(multiplySmall(b, a), sign);
  1443. }
  1444. return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
  1445. }
  1446. SmallInteger.prototype._multiplyBySmall = function (a) {
  1447. if (isPrecise(a.value * this.value)) {
  1448. return new SmallInteger(a.value * this.value);
  1449. }
  1450. return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
  1451. };
  1452. BigInteger.prototype._multiplyBySmall = function (a) {
  1453. if (a.value === 0) return Integer[0];
  1454. if (a.value === 1) return this;
  1455. if (a.value === -1) return this.negate();
  1456. return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
  1457. };
  1458. SmallInteger.prototype.multiply = function (v) {
  1459. return parseValue(v)._multiplyBySmall(this);
  1460. };
  1461. SmallInteger.prototype.times = SmallInteger.prototype.multiply;
  1462. NativeBigInt.prototype.multiply = function (v) {
  1463. return new NativeBigInt(this.value * parseValue(v).value);
  1464. }
  1465. NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
  1466. function square(a) {
  1467. //console.assert(2 * BASE * BASE < MAX_INT);
  1468. var l = a.length,
  1469. r = createArray(l + l),
  1470. base = BASE,
  1471. product, carry, i, a_i, a_j;
  1472. for (i = 0; i < l; i++) {
  1473. a_i = a[i];
  1474. carry = 0 - a_i * a_i;
  1475. for (var j = i; j < l; j++) {
  1476. a_j = a[j];
  1477. product = 2 * (a_i * a_j) + r[i + j] + carry;
  1478. carry = Math.floor(product / base);
  1479. r[i + j] = product - carry * base;
  1480. }
  1481. r[i + l] = carry;
  1482. }
  1483. trim(r);
  1484. return r;
  1485. }
  1486. BigInteger.prototype.square = function () {
  1487. return new BigInteger(square(this.value), false);
  1488. };
  1489. SmallInteger.prototype.square = function () {
  1490. var value = this.value * this.value;
  1491. if (isPrecise(value)) return new SmallInteger(value);
  1492. return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
  1493. };
  1494. NativeBigInt.prototype.square = function (v) {
  1495. return new NativeBigInt(this.value * this.value);
  1496. }
  1497. function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
  1498. var a_l = a.length,
  1499. b_l = b.length,
  1500. base = BASE,
  1501. result = createArray(b.length),
  1502. divisorMostSignificantDigit = b[b_l - 1],
  1503. // normalization
  1504. lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
  1505. remainder = multiplySmall(a, lambda),
  1506. divisor = multiplySmall(b, lambda),
  1507. quotientDigit, shift, carry, borrow, i, l, q;
  1508. if (remainder.length <= a_l) remainder.push(0);
  1509. divisor.push(0);
  1510. divisorMostSignificantDigit = divisor[b_l - 1];
  1511. for (shift = a_l - b_l; shift >= 0; shift--) {
  1512. quotientDigit = base - 1;
  1513. if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
  1514. quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
  1515. }
  1516. // quotientDigit <= base - 1
  1517. carry = 0;
  1518. borrow = 0;
  1519. l = divisor.length;
  1520. for (i = 0; i < l; i++) {
  1521. carry += quotientDigit * divisor[i];
  1522. q = Math.floor(carry / base);
  1523. borrow += remainder[shift + i] - (carry - q * base);
  1524. carry = q;
  1525. if (borrow < 0) {
  1526. remainder[shift + i] = borrow + base;
  1527. borrow = -1;
  1528. } else {
  1529. remainder[shift + i] = borrow;
  1530. borrow = 0;
  1531. }
  1532. }
  1533. while (borrow !== 0) {
  1534. quotientDigit -= 1;
  1535. carry = 0;
  1536. for (i = 0; i < l; i++) {
  1537. carry += remainder[shift + i] - base + divisor[i];
  1538. if (carry < 0) {
  1539. remainder[shift + i] = carry + base;
  1540. carry = 0;
  1541. } else {
  1542. remainder[shift + i] = carry;
  1543. carry = 1;
  1544. }
  1545. }
  1546. borrow += carry;
  1547. }
  1548. result[shift] = quotientDigit;
  1549. }
  1550. // denormalization
  1551. remainder = divModSmall(remainder, lambda)[0];
  1552. return [arrayToSmall(result), arrayToSmall(remainder)];
  1553. }
  1554. function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
  1555. // Performs faster than divMod1 on larger input sizes.
  1556. var a_l = a.length,
  1557. b_l = b.length,
  1558. result = [],
  1559. part = [],
  1560. base = BASE,
  1561. guess, xlen, highx, highy, check;
  1562. while (a_l) {
  1563. part.unshift(a[--a_l]);
  1564. trim(part);
  1565. if (compareAbs(part, b) < 0) {
  1566. result.push(0);
  1567. continue;
  1568. }
  1569. xlen = part.length;
  1570. highx = part[xlen - 1] * base + part[xlen - 2];
  1571. highy = b[b_l - 1] * base + b[b_l - 2];
  1572. if (xlen > b_l) {
  1573. highx = (highx + 1) * base;
  1574. }
  1575. guess = Math.ceil(highx / highy);
  1576. do {
  1577. check = multiplySmall(b, guess);
  1578. if (compareAbs(check, part) <= 0) break;
  1579. guess--;
  1580. } while (guess);
  1581. result.push(guess);
  1582. part = subtract(part, check);
  1583. }
  1584. result.reverse();
  1585. return [arrayToSmall(result), arrayToSmall(part)];
  1586. }
  1587. function divModSmall(value, lambda) {
  1588. var length = value.length,
  1589. quotient = createArray(length),
  1590. base = BASE,
  1591. i, q, remainder, divisor;
  1592. remainder = 0;
  1593. for (i = length - 1; i >= 0; --i) {
  1594. divisor = remainder * base + value[i];
  1595. q = truncate(divisor / lambda);
  1596. remainder = divisor - q * lambda;
  1597. quotient[i] = q | 0;
  1598. }
  1599. return [quotient, remainder | 0];
  1600. }
  1601. function divModAny(self, v) {
  1602. var value, n = parseValue(v);
  1603. if (supportsNativeBigInt) {
  1604. return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];
  1605. }
  1606. var a = self.value, b = n.value;
  1607. var quotient;
  1608. if (b === 0) throw new Error("Cannot divide by zero");
  1609. if (self.isSmall) {
  1610. if (n.isSmall) {
  1611. return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
  1612. }
  1613. return [Integer[0], self];
  1614. }
  1615. if (n.isSmall) {
  1616. if (b === 1) return [self, Integer[0]];
  1617. if (b == -1) return [self.negate(), Integer[0]];
  1618. var abs = Math.abs(b);
  1619. if (abs < BASE) {
  1620. value = divModSmall(a, abs);
  1621. quotient = arrayToSmall(value[0]);
  1622. var remainder = value[1];
  1623. if (self.sign) remainder = -remainder;
  1624. if (typeof quotient === "number") {
  1625. if (self.sign !== n.sign) quotient = -quotient;
  1626. return [new SmallInteger(quotient), new SmallInteger(remainder)];
  1627. }
  1628. return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
  1629. }
  1630. b = smallToArray(abs);
  1631. }
  1632. var comparison = compareAbs(a, b);
  1633. if (comparison === -1) return [Integer[0], self];
  1634. if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
  1635. // divMod1 is faster on smaller input sizes
  1636. if (a.length + b.length <= 200)
  1637. value = divMod1(a, b);
  1638. else value = divMod2(a, b);
  1639. quotient = value[0];
  1640. var qSign = self.sign !== n.sign,
  1641. mod = value[1],
  1642. mSign = self.sign;
  1643. if (typeof quotient === "number") {
  1644. if (qSign) quotient = -quotient;
  1645. quotient = new SmallInteger(quotient);
  1646. } else quotient = new BigInteger(quotient, qSign);
  1647. if (typeof mod === "number") {
  1648. if (mSign) mod = -mod;
  1649. mod = new SmallInteger(mod);
  1650. } else mod = new BigInteger(mod, mSign);
  1651. return [quotient, mod];
  1652. }
  1653. BigInteger.prototype.divmod = function (v) {
  1654. var result = divModAny(this, v);
  1655. return {
  1656. quotient: result[0],
  1657. remainder: result[1]
  1658. };
  1659. };
  1660. NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
  1661. BigInteger.prototype.divide = function (v) {
  1662. return divModAny(this, v)[0];
  1663. };
  1664. NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {
  1665. return new NativeBigInt(this.value / parseValue(v).value);
  1666. };
  1667. SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
  1668. BigInteger.prototype.mod = function (v) {
  1669. return divModAny(this, v)[1];
  1670. };
  1671. NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {
  1672. return new NativeBigInt(this.value % parseValue(v).value);
  1673. };
  1674. SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
  1675. BigInteger.prototype.pow = function (v) {
  1676. var n = parseValue(v),
  1677. a = this.value,
  1678. b = n.value,
  1679. value, x, y;
  1680. if (b === 0) return Integer[1];
  1681. if (a === 0) return Integer[0];
  1682. if (a === 1) return Integer[1];
  1683. if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
  1684. if (n.sign) {
  1685. return Integer[0];
  1686. }
  1687. if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
  1688. if (this.isSmall) {
  1689. if (isPrecise(value = Math.pow(a, b)))
  1690. return new SmallInteger(truncate(value));
  1691. }
  1692. x = this;
  1693. y = Integer[1];
  1694. while (true) {
  1695. if (b & 1 === 1) {
  1696. y = y.times(x);
  1697. --b;
  1698. }
  1699. if (b === 0) break;
  1700. b /= 2;
  1701. x = x.square();
  1702. }
  1703. return y;
  1704. };
  1705. SmallInteger.prototype.pow = BigInteger.prototype.pow;
  1706. NativeBigInt.prototype.pow = function (v) {
  1707. var n = parseValue(v);
  1708. var a = this.value, b = n.value;
  1709. var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
  1710. if (b === _0) return Integer[1];
  1711. if (a === _0) return Integer[0];
  1712. if (a === _1) return Integer[1];
  1713. if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];
  1714. if (n.isNegative()) return new NativeBigInt(_0);
  1715. var x = this;
  1716. var y = Integer[1];
  1717. while (true) {
  1718. if ((b & _1) === _1) {
  1719. y = y.times(x);
  1720. --b;
  1721. }
  1722. if (b === _0) break;
  1723. b /= _2;
  1724. x = x.square();
  1725. }
  1726. return y;
  1727. }
  1728. BigInteger.prototype.modPow = function (exp, mod) {
  1729. exp = parseValue(exp);
  1730. mod = parseValue(mod);
  1731. if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
  1732. var r = Integer[1],
  1733. base = this.mod(mod);
  1734. if (exp.isNegative()) {
  1735. exp = exp.multiply(Integer[-1]);
  1736. base = base.modInv(mod);
  1737. }
  1738. while (exp.isPositive()) {
  1739. if (base.isZero()) return Integer[0];
  1740. if (exp.isOdd()) r = r.multiply(base).mod(mod);
  1741. exp = exp.divide(2);
  1742. base = base.square().mod(mod);
  1743. }
  1744. return r;
  1745. };
  1746. NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
  1747. function compareAbs(a, b) {
  1748. if (a.length !== b.length) {
  1749. return a.length > b.length ? 1 : -1;
  1750. }
  1751. for (var i = a.length - 1; i >= 0; i--) {
  1752. if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
  1753. }
  1754. return 0;
  1755. }
  1756. BigInteger.prototype.compareAbs = function (v) {
  1757. var n = parseValue(v),
  1758. a = this.value,
  1759. b = n.value;
  1760. if (n.isSmall) return 1;
  1761. return compareAbs(a, b);
  1762. };
  1763. SmallInteger.prototype.compareAbs = function (v) {
  1764. var n = parseValue(v),
  1765. a = Math.abs(this.value),
  1766. b = n.value;
  1767. if (n.isSmall) {
  1768. b = Math.abs(b);
  1769. return a === b ? 0 : a > b ? 1 : -1;
  1770. }
  1771. return -1;
  1772. };
  1773. NativeBigInt.prototype.compareAbs = function (v) {
  1774. var a = this.value;
  1775. var b = parseValue(v).value;
  1776. a = a >= 0 ? a : -a;
  1777. b = b >= 0 ? b : -b;
  1778. return a === b ? 0 : a > b ? 1 : -1;
  1779. }
  1780. BigInteger.prototype.compare = function (v) {
  1781. // See discussion about comparison with Infinity:
  1782. // https://github.com/peterolson/BigInteger.js/issues/61
  1783. if (v === Infinity) {
  1784. return -1;
  1785. }
  1786. if (v === -Infinity) {
  1787. return 1;
  1788. }
  1789. var n = parseValue(v),
  1790. a = this.value,
  1791. b = n.value;
  1792. if (this.sign !== n.sign) {
  1793. return n.sign ? 1 : -1;
  1794. }
  1795. if (n.isSmall) {
  1796. return this.sign ? -1 : 1;
  1797. }
  1798. return compareAbs(a, b) * (this.sign ? -1 : 1);
  1799. };
  1800. BigInteger.prototype.compareTo = BigInteger.prototype.compare;
  1801. SmallInteger.prototype.compare = function (v) {
  1802. if (v === Infinity) {
  1803. return -1;
  1804. }
  1805. if (v === -Infinity) {
  1806. return 1;
  1807. }
  1808. var n = parseValue(v),
  1809. a = this.value,
  1810. b = n.value;
  1811. if (n.isSmall) {
  1812. return a == b ? 0 : a > b ? 1 : -1;
  1813. }
  1814. if (a < 0 !== n.sign) {
  1815. return a < 0 ? -1 : 1;
  1816. }
  1817. return a < 0 ? 1 : -1;
  1818. };
  1819. SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
  1820. NativeBigInt.prototype.compare = function (v) {
  1821. if (v === Infinity) {
  1822. return -1;
  1823. }
  1824. if (v === -Infinity) {
  1825. return 1;
  1826. }
  1827. var a = this.value;
  1828. var b = parseValue(v).value;
  1829. return a === b ? 0 : a > b ? 1 : -1;
  1830. }
  1831. NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
  1832. BigInteger.prototype.equals = function (v) {
  1833. return this.compare(v) === 0;
  1834. };
  1835. NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
  1836. BigInteger.prototype.notEquals = function (v) {
  1837. return this.compare(v) !== 0;
  1838. };
  1839. NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
  1840. BigInteger.prototype.greater = function (v) {
  1841. return this.compare(v) > 0;
  1842. };
  1843. NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
  1844. BigInteger.prototype.lesser = function (v) {
  1845. return this.compare(v) < 0;
  1846. };
  1847. NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
  1848. BigInteger.prototype.greaterOrEquals = function (v) {
  1849. return this.compare(v) >= 0;
  1850. };
  1851. NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
  1852. BigInteger.prototype.lesserOrEquals = function (v) {
  1853. return this.compare(v) <= 0;
  1854. };
  1855. NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
  1856. BigInteger.prototype.isEven = function () {
  1857. return (this.value[0] & 1) === 0;
  1858. };
  1859. SmallInteger.prototype.isEven = function () {
  1860. return (this.value & 1) === 0;
  1861. };
  1862. NativeBigInt.prototype.isEven = function () {
  1863. return (this.value & BigInt(1)) === BigInt(0);
  1864. }
  1865. BigInteger.prototype.isOdd = function () {
  1866. return (this.value[0] & 1) === 1;
  1867. };
  1868. SmallInteger.prototype.isOdd = function () {
  1869. return (this.value & 1) === 1;
  1870. };
  1871. NativeBigInt.prototype.isOdd = function () {
  1872. return (this.value & BigInt(1)) === BigInt(1);
  1873. }
  1874. BigInteger.prototype.isPositive = function () {
  1875. return !this.sign;
  1876. };
  1877. SmallInteger.prototype.isPositive = function () {
  1878. return this.value > 0;
  1879. };
  1880. NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
  1881. BigInteger.prototype.isNegative = function () {
  1882. return this.sign;
  1883. };
  1884. SmallInteger.prototype.isNegative = function () {
  1885. return this.value < 0;
  1886. };
  1887. NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
  1888. BigInteger.prototype.isUnit = function () {
  1889. return false;
  1890. };
  1891. SmallInteger.prototype.isUnit = function () {
  1892. return Math.abs(this.value) === 1;
  1893. };
  1894. NativeBigInt.prototype.isUnit = function () {
  1895. return this.abs().value === BigInt(1);
  1896. }
  1897. BigInteger.prototype.isZero = function () {
  1898. return false;
  1899. };
  1900. SmallInteger.prototype.isZero = function () {
  1901. return this.value === 0;
  1902. };
  1903. NativeBigInt.prototype.isZero = function () {
  1904. return this.value === BigInt(0);
  1905. }
  1906. BigInteger.prototype.isDivisibleBy = function (v) {
  1907. var n = parseValue(v);
  1908. if (n.isZero()) return false;
  1909. if (n.isUnit()) return true;
  1910. if (n.compareAbs(2) === 0) return this.isEven();
  1911. return this.mod(n).isZero();
  1912. };
  1913. NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
  1914. function isBasicPrime(v) {
  1915. var n = v.abs();
  1916. if (n.isUnit()) return false;
  1917. if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
  1918. if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
  1919. if (n.lesser(49)) return true;
  1920. // we don't know if it's prime: let the other functions figure it out
  1921. }
  1922. function millerRabinTest(n, a) {
  1923. var nPrev = n.prev(),
  1924. b = nPrev,
  1925. r = 0,
  1926. d, t, i, x;
  1927. while (b.isEven()) b = b.divide(2), r++;
  1928. next: for (i = 0; i < a.length; i++) {
  1929. if (n.lesser(a[i])) continue;
  1930. x = bigInt(a[i]).modPow(b, n);
  1931. if (x.isUnit() || x.equals(nPrev)) continue;
  1932. for (d = r - 1; d != 0; d--) {
  1933. x = x.square().mod(n);
  1934. if (x.isUnit()) return false;
  1935. if (x.equals(nPrev)) continue next;
  1936. }
  1937. return false;
  1938. }
  1939. return true;
  1940. }
  1941. // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
  1942. BigInteger.prototype.isPrime = function (strict) {
  1943. var isPrime = isBasicPrime(this);
  1944. if (isPrime !== undefined) return isPrime;
  1945. var n = this.abs();
  1946. var bits = n.bitLength();
  1947. if (bits <= 64)
  1948. return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
  1949. var logN = Math.log(2) * bits.toJSNumber();
  1950. var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
  1951. for (var a = [], i = 0; i < t; i++) {
  1952. a.push(bigInt(i + 2));
  1953. }
  1954. return millerRabinTest(n, a);
  1955. };
  1956. NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
  1957. BigInteger.prototype.isProbablePrime = function (iterations, rng) {
  1958. var isPrime = isBasicPrime(this);
  1959. if (isPrime !== undefined) return isPrime;
  1960. var n = this.abs();
  1961. var t = iterations === undefined ? 5 : iterations;
  1962. for (var a = [], i = 0; i < t; i++) {
  1963. a.push(bigInt.randBetween(2, n.minus(2), rng));
  1964. }
  1965. return millerRabinTest(n, a);
  1966. };
  1967. NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
  1968. BigInteger.prototype.modInv = function (n) {
  1969. var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
  1970. while (!newR.isZero()) {
  1971. q = r.divide(newR);
  1972. lastT = t;
  1973. lastR = r;
  1974. t = newT;
  1975. r = newR;
  1976. newT = lastT.subtract(q.multiply(newT));
  1977. newR = lastR.subtract(q.multiply(newR));
  1978. }
  1979. if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
  1980. if (t.compare(0) === -1) {
  1981. t = t.add(n);
  1982. }
  1983. if (this.isNegative()) {
  1984. return t.negate();
  1985. }
  1986. return t;
  1987. };
  1988. NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
  1989. BigInteger.prototype.next = function () {
  1990. var value = this.value;
  1991. if (this.sign) {
  1992. return subtractSmall(value, 1, this.sign);
  1993. }
  1994. return new BigInteger(addSmall(value, 1), this.sign);
  1995. };
  1996. SmallInteger.prototype.next = function () {
  1997. var value = this.value;
  1998. if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
  1999. return new BigInteger(MAX_INT_ARR, false);
  2000. };
  2001. NativeBigInt.prototype.next = function () {
  2002. return new NativeBigInt(this.value + BigInt(1));
  2003. }
  2004. BigInteger.prototype.prev = function () {
  2005. var value = this.value;
  2006. if (this.sign) {
  2007. return new BigInteger(addSmall(value, 1), true);
  2008. }
  2009. return subtractSmall(value, 1, this.sign);
  2010. };
  2011. SmallInteger.prototype.prev = function () {
  2012. var value = this.value;
  2013. if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
  2014. return new BigInteger(MAX_INT_ARR, true);
  2015. };
  2016. NativeBigInt.prototype.prev = function () {
  2017. return new NativeBigInt(this.value - BigInt(1));
  2018. }
  2019. var powersOfTwo = [1];
  2020. while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
  2021. var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
  2022. function shift_isSmall(n) {
  2023. return Math.abs(n) <= BASE;
  2024. }
  2025. BigInteger.prototype.shiftLeft = function (v) {
  2026. var n = parseValue(v).toJSNumber();
  2027. if (!shift_isSmall(n)) {
  2028. throw new Error(String(n) + " is too large for shifting.");
  2029. }
  2030. if (n < 0) return this.shiftRight(-n);
  2031. var result = this;
  2032. if (result.isZero()) return result;
  2033. while (n >= powers2Length) {
  2034. result = result.multiply(highestPower2);
  2035. n -= powers2Length - 1;
  2036. }
  2037. return result.multiply(powersOfTwo[n]);
  2038. };
  2039. NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
  2040. BigInteger.prototype.shiftRight = function (v) {
  2041. var remQuo;
  2042. var n = parseValue(v).toJSNumber();
  2043. if (!shift_isSmall(n)) {
  2044. throw new Error(String(n) + " is too large for shifting.");
  2045. }
  2046. if (n < 0) return this.shiftLeft(-n);
  2047. var result = this;
  2048. while (n >= powers2Length) {
  2049. if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
  2050. remQuo = divModAny(result, highestPower2);
  2051. result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
  2052. n -= powers2Length - 1;
  2053. }
  2054. remQuo = divModAny(result, powersOfTwo[n]);
  2055. return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
  2056. };
  2057. NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
  2058. function bitwise(x, y, fn) {
  2059. y = parseValue(y);
  2060. var xSign = x.isNegative(), ySign = y.isNegative();
  2061. var xRem = xSign ? x.not() : x,
  2062. yRem = ySign ? y.not() : y;
  2063. var xDigit = 0, yDigit = 0;
  2064. var xDivMod = null, yDivMod = null;
  2065. var result = [];
  2066. while (!xRem.isZero() || !yRem.isZero()) {
  2067. xDivMod = divModAny(xRem, highestPower2);
  2068. xDigit = xDivMod[1].toJSNumber();
  2069. if (xSign) {
  2070. xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
  2071. }
  2072. yDivMod = divModAny(yRem, highestPower2);
  2073. yDigit = yDivMod[1].toJSNumber();
  2074. if (ySign) {
  2075. yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
  2076. }
  2077. xRem = xDivMod[0];
  2078. yRem = yDivMod[0];
  2079. result.push(fn(xDigit, yDigit));
  2080. }
  2081. var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
  2082. for (var i = result.length - 1; i >= 0; i -= 1) {
  2083. sum = sum.multiply(highestPower2).add(bigInt(result[i]));
  2084. }
  2085. return sum;
  2086. }
  2087. BigInteger.prototype.not = function () {
  2088. return this.negate().prev();
  2089. };
  2090. NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
  2091. BigInteger.prototype.and = function (n) {
  2092. return bitwise(this, n, function (a, b) { return a & b; });
  2093. };
  2094. NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
  2095. BigInteger.prototype.or = function (n) {
  2096. return bitwise(this, n, function (a, b) { return a | b; });
  2097. };
  2098. NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
  2099. BigInteger.prototype.xor = function (n) {
  2100. return bitwise(this, n, function (a, b) { return a ^ b; });
  2101. };
  2102. NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
  2103. var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
  2104. function roughLOB(n) { // get lowestOneBit (rough)
  2105. // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
  2106. // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
  2107. var v = n.value,
  2108. x = typeof v === "number" ? v | LOBMASK_I :
  2109. typeof v === "bigint" ? v | BigInt(LOBMASK_I) :
  2110. v[0] + v[1] * BASE | LOBMASK_BI;
  2111. return x & -x;
  2112. }
  2113. function integerLogarithm(value, base) {
  2114. if (base.compareTo(value) <= 0) {
  2115. var tmp = integerLogarithm(value, base.square(base));
  2116. var p = tmp.p;
  2117. var e = tmp.e;
  2118. var t = p.multiply(base);
  2119. return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
  2120. }
  2121. return { p: bigInt(1), e: 0 };
  2122. }
  2123. BigInteger.prototype.bitLength = function () {
  2124. var n = this;
  2125. if (n.compareTo(bigInt(0)) < 0) {
  2126. n = n.negate().subtract(bigInt(1));
  2127. }
  2128. if (n.compareTo(bigInt(0)) === 0) {
  2129. return bigInt(0);
  2130. }
  2131. return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
  2132. }
  2133. NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
  2134. function max(a, b) {
  2135. a = parseValue(a);
  2136. b = parseValue(b);
  2137. return a.greater(b) ? a : b;
  2138. }
  2139. function min(a, b) {
  2140. a = parseValue(a);
  2141. b = parseValue(b);
  2142. return a.lesser(b) ? a : b;
  2143. }
  2144. function gcd(a, b) {
  2145. a = parseValue(a).abs();
  2146. b = parseValue(b).abs();
  2147. if (a.equals(b)) return a;
  2148. if (a.isZero()) return b;
  2149. if (b.isZero()) return a;
  2150. var c = Integer[1], d, t;
  2151. while (a.isEven() && b.isEven()) {
  2152. d = min(roughLOB(a), roughLOB(b));
  2153. a = a.divide(d);
  2154. b = b.divide(d);
  2155. c = c.multiply(d);
  2156. }
  2157. while (a.isEven()) {
  2158. a = a.divide(roughLOB(a));
  2159. }
  2160. do {
  2161. while (b.isEven()) {
  2162. b = b.divide(roughLOB(b));
  2163. }
  2164. if (a.greater(b)) {
  2165. t = b; b = a; a = t;
  2166. }
  2167. b = b.subtract(a);
  2168. } while (!b.isZero());
  2169. return c.isUnit() ? a : a.multiply(c);
  2170. }
  2171. function lcm(a, b) {
  2172. a = parseValue(a).abs();
  2173. b = parseValue(b).abs();
  2174. return a.divide(gcd(a, b)).multiply(b);
  2175. }
  2176. function randBetween(a, b, rng) {
  2177. a = parseValue(a);
  2178. b = parseValue(b);
  2179. var usedRNG = rng || Math.random;
  2180. var low = min(a, b), high = max(a, b);
  2181. var range = high.subtract(low).add(1);
  2182. if (range.isSmall) return low.add(Math.floor(usedRNG() * range));
  2183. var digits = toBase(range, BASE).value;
  2184. var result = [], restricted = true;
  2185. for (var i = 0; i < digits.length; i++) {
  2186. var top = restricted ? digits[i] : BASE;
  2187. var digit = truncate(usedRNG() * top);
  2188. result.push(digit);
  2189. if (digit < top) restricted = false;
  2190. }
  2191. return low.add(Integer.fromArray(result, BASE, false));
  2192. }
  2193. var parseBase = function (text, base, alphabet, caseSensitive) {
  2194. alphabet = alphabet || DEFAULT_ALPHABET;
  2195. text = String(text);
  2196. if (!caseSensitive) {
  2197. text = text.toLowerCase();
  2198. alphabet = alphabet.toLowerCase();
  2199. }
  2200. var length = text.length;
  2201. var i;
  2202. var absBase = Math.abs(base);
  2203. var alphabetValues = {};
  2204. for (i = 0; i < alphabet.length; i++) {
  2205. alphabetValues[alphabet[i]] = i;
  2206. }
  2207. for (i = 0; i < length; i++) {
  2208. var c = text[i];
  2209. if (c === "-") continue;
  2210. if (c in alphabetValues) {
  2211. if (alphabetValues[c] >= absBase) {
  2212. if (c === "1" && absBase === 1) continue;
  2213. throw new Error(c + " is not a valid digit in base " + base + ".");
  2214. }
  2215. }
  2216. }
  2217. base = parseValue(base);
  2218. var digits = [];
  2219. var isNegative = text[0] === "-";
  2220. for (i = isNegative ? 1 : 0; i < text.length; i++) {
  2221. var c = text[i];
  2222. if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));
  2223. else if (c === "<") {
  2224. var start = i;
  2225. do { i++; } while (text[i] !== ">" && i < text.length);
  2226. digits.push(parseValue(text.slice(start + 1, i)));
  2227. }
  2228. else throw new Error(c + " is not a valid character");
  2229. }
  2230. return parseBaseFromArray(digits, base, isNegative);
  2231. };
  2232. function parseBaseFromArray(digits, base, isNegative) {
  2233. var val = Integer[0], pow = Integer[1], i;
  2234. for (i = digits.length - 1; i >= 0; i--) {
  2235. val = val.add(digits[i].times(pow));
  2236. pow = pow.times(base);
  2237. }
  2238. return isNegative ? val.negate() : val;
  2239. }
  2240. function stringify(digit, alphabet) {
  2241. alphabet = alphabet || DEFAULT_ALPHABET;
  2242. if (digit < alphabet.length) {
  2243. return alphabet[digit];
  2244. }
  2245. return "<" + digit + ">";
  2246. }
  2247. function toBase(n, base) {
  2248. base = bigInt(base);
  2249. if (base.isZero()) {
  2250. if (n.isZero()) return { value: [0], isNegative: false };
  2251. throw new Error("Cannot convert nonzero numbers to base 0.");
  2252. }
  2253. if (base.equals(-1)) {
  2254. if (n.isZero()) return { value: [0], isNegative: false };
  2255. if (n.isNegative())
  2256. return {
  2257. value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))
  2258. .map(Array.prototype.valueOf, [1, 0])
  2259. ),
  2260. isNegative: false
  2261. };
  2262. var arr = Array.apply(null, Array(n.toJSNumber() - 1))
  2263. .map(Array.prototype.valueOf, [0, 1]);
  2264. arr.unshift([1]);
  2265. return {
  2266. value: [].concat.apply([], arr),
  2267. isNegative: false
  2268. };
  2269. }
  2270. var neg = false;
  2271. if (n.isNegative() && base.isPositive()) {
  2272. neg = true;
  2273. n = n.abs();
  2274. }
  2275. if (base.isUnit()) {
  2276. if (n.isZero()) return { value: [0], isNegative: false };
  2277. return {
  2278. value: Array.apply(null, Array(n.toJSNumber()))
  2279. .map(Number.prototype.valueOf, 1),
  2280. isNegative: neg
  2281. };
  2282. }
  2283. var out = [];
  2284. var left = n, divmod;
  2285. while (left.isNegative() || left.compareAbs(base) >= 0) {
  2286. divmod = left.divmod(base);
  2287. left = divmod.quotient;
  2288. var digit = divmod.remainder;
  2289. if (digit.isNegative()) {
  2290. digit = base.minus(digit).abs();
  2291. left = left.next();
  2292. }
  2293. out.push(digit.toJSNumber());
  2294. }
  2295. out.push(left.toJSNumber());
  2296. return { value: out.reverse(), isNegative: neg };
  2297. }
  2298. function toBaseString(n, base, alphabet) {
  2299. var arr = toBase(n, base);
  2300. return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {
  2301. return stringify(x, alphabet);
  2302. }).join('');
  2303. }
  2304. BigInteger.prototype.toArray = function (radix) {
  2305. return toBase(this, radix);
  2306. };
  2307. SmallInteger.prototype.toArray = function (radix) {
  2308. return toBase(this, radix);
  2309. };
  2310. NativeBigInt.prototype.toArray = function (radix) {
  2311. return toBase(this, radix);
  2312. };
  2313. BigInteger.prototype.toString = function (radix, alphabet) {
  2314. if (radix === undefined) radix = 10;
  2315. if (radix !== 10) return toBaseString(this, radix, alphabet);
  2316. var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
  2317. while (--l >= 0) {
  2318. digit = String(v[l]);
  2319. str += zeros.slice(digit.length) + digit;
  2320. }
  2321. var sign = this.sign ? "-" : "";
  2322. return sign + str;
  2323. };
  2324. SmallInteger.prototype.toString = function (radix, alphabet) {
  2325. if (radix === undefined) radix = 10;
  2326. if (radix != 10) return toBaseString(this, radix, alphabet);
  2327. return String(this.value);
  2328. };
  2329. NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
  2330. NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }
  2331. BigInteger.prototype.valueOf = function () {
  2332. return parseInt(this.toString(), 10);
  2333. };
  2334. BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
  2335. SmallInteger.prototype.valueOf = function () {
  2336. return this.value;
  2337. };
  2338. SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
  2339. NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {
  2340. return parseInt(this.toString(), 10);
  2341. }
  2342. function parseStringValue(v) {
  2343. if (isPrecise(+v)) {
  2344. var x = +v;
  2345. if (x === truncate(x))
  2346. return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
  2347. throw new Error("Invalid integer: " + v);
  2348. }
  2349. var sign = v[0] === "-";
  2350. if (sign) v = v.slice(1);
  2351. var split = v.split(/e/i);
  2352. if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
  2353. if (split.length === 2) {
  2354. var exp = split[1];
  2355. if (exp[0] === "+") exp = exp.slice(1);
  2356. exp = +exp;
  2357. if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
  2358. var text = split[0];
  2359. var decimalPlace = text.indexOf(".");
  2360. if (decimalPlace >= 0) {
  2361. exp -= text.length - decimalPlace - 1;
  2362. text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
  2363. }
  2364. if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
  2365. text += (new Array(exp + 1)).join("0");
  2366. v = text;
  2367. }
  2368. var isValid = /^([0-9][0-9]*)$/.test(v);
  2369. if (!isValid) throw new Error("Invalid integer: " + v);
  2370. if (supportsNativeBigInt) {
  2371. return new NativeBigInt(BigInt(sign ? "-" + v : v));
  2372. }
  2373. var r = [], max = v.length, l = LOG_BASE, min = max - l;
  2374. while (max > 0) {
  2375. r.push(+v.slice(min, max));
  2376. min -= l;
  2377. if (min < 0) min = 0;
  2378. max -= l;
  2379. }
  2380. trim(r);
  2381. return new BigInteger(r, sign);
  2382. }
  2383. function parseNumberValue(v) {
  2384. if (supportsNativeBigInt) {
  2385. return new NativeBigInt(BigInt(v));
  2386. }
  2387. if (isPrecise(v)) {
  2388. if (v !== truncate(v)) throw new Error(v + " is not an integer.");
  2389. return new SmallInteger(v);
  2390. }
  2391. return parseStringValue(v.toString());
  2392. }
  2393. function parseValue(v) {
  2394. if (typeof v === "number") {
  2395. return parseNumberValue(v);
  2396. }
  2397. if (typeof v === "string") {
  2398. return parseStringValue(v);
  2399. }
  2400. if (typeof v === "bigint") {
  2401. return new NativeBigInt(v);
  2402. }
  2403. return v;
  2404. }
  2405. // Pre-define numbers in range [-999,999]
  2406. for (var i = 0; i < 1000; i++) {
  2407. Integer[i] = parseValue(i);
  2408. if (i > 0) Integer[-i] = parseValue(-i);
  2409. }
  2410. // Backwards compatibility
  2411. Integer.one = Integer[1];
  2412. Integer.zero = Integer[0];
  2413. Integer.minusOne = Integer[-1];
  2414. Integer.max = max;
  2415. Integer.min = min;
  2416. Integer.gcd = gcd;
  2417. Integer.lcm = lcm;
  2418. Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };
  2419. Integer.randBetween = randBetween;
  2420. Integer.fromArray = function (digits, base, isNegative) {
  2421. return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
  2422. };
  2423. return Integer;
  2424. })();
  2425. // Node.js check
  2426. if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
  2427. module.exports = bigInt;
  2428. }
  2429. //amd check
  2430. if (typeof define === "function" && define.amd) {
  2431. define( function () {
  2432. return bigInt;
  2433. });
  2434. }
  2435. },{}],7:[function(require,module,exports){
  2436. },{}],8:[function(require,module,exports){
  2437. (function (Buffer){
  2438. /*!
  2439. * The buffer module from node.js, for the browser.
  2440. *
  2441. * @author Feross Aboukhadijeh <https://feross.org>
  2442. * @license MIT
  2443. */
  2444. /* eslint-disable no-proto */
  2445. 'use strict'
  2446. var base64 = require('base64-js')
  2447. var ieee754 = require('ieee754')
  2448. exports.Buffer = Buffer
  2449. exports.SlowBuffer = SlowBuffer
  2450. exports.INSPECT_MAX_BYTES = 50
  2451. var K_MAX_LENGTH = 0x7fffffff
  2452. exports.kMaxLength = K_MAX_LENGTH
  2453. /**
  2454. * If `Buffer.TYPED_ARRAY_SUPPORT`:
  2455. * === true Use Uint8Array implementation (fastest)
  2456. * === false Print warning and recommend using `buffer` v4.x which has an Object
  2457. * implementation (most compatible, even IE6)
  2458. *
  2459. * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
  2460. * Opera 11.6+, iOS 4.2+.
  2461. *
  2462. * We report that the browser does not support typed arrays if the are not subclassable
  2463. * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
  2464. * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
  2465. * for __proto__ and has a buggy typed array implementation.
  2466. */
  2467. Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
  2468. if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
  2469. typeof console.error === 'function') {
  2470. console.error(
  2471. 'This browser lacks typed array (Uint8Array) support which is required by ' +
  2472. '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
  2473. )
  2474. }
  2475. function typedArraySupport () {
  2476. // Can typed array instances can be augmented?
  2477. try {
  2478. var arr = new Uint8Array(1)
  2479. arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
  2480. return arr.foo() === 42
  2481. } catch (e) {
  2482. return false
  2483. }
  2484. }
  2485. Object.defineProperty(Buffer.prototype, 'parent', {
  2486. enumerable: true,
  2487. get: function () {
  2488. if (!Buffer.isBuffer(this)) return undefined
  2489. return this.buffer
  2490. }
  2491. })
  2492. Object.defineProperty(Buffer.prototype, 'offset', {
  2493. enumerable: true,
  2494. get: function () {
  2495. if (!Buffer.isBuffer(this)) return undefined
  2496. return this.byteOffset
  2497. }
  2498. })
  2499. function createBuffer (length) {
  2500. if (length > K_MAX_LENGTH) {
  2501. throw new RangeError('The value "' + length + '" is invalid for option "size"')
  2502. }
  2503. // Return an augmented `Uint8Array` instance
  2504. var buf = new Uint8Array(length)
  2505. buf.__proto__ = Buffer.prototype
  2506. return buf
  2507. }
  2508. /**
  2509. * The Buffer constructor returns instances of `Uint8Array` that have their
  2510. * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
  2511. * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
  2512. * and the `Uint8Array` methods. Square bracket notation works as expected -- it
  2513. * returns a single octet.
  2514. *
  2515. * The `Uint8Array` prototype remains unmodified.
  2516. */
  2517. function Buffer (arg, encodingOrOffset, length) {
  2518. // Common case.
  2519. if (typeof arg === 'number') {
  2520. if (typeof encodingOrOffset === 'string') {
  2521. throw new TypeError(
  2522. 'The "string" argument must be of type string. Received type number'
  2523. )
  2524. }
  2525. return allocUnsafe(arg)
  2526. }
  2527. return from(arg, encodingOrOffset, length)
  2528. }
  2529. // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
  2530. if (typeof Symbol !== 'undefined' && Symbol.species != null &&
  2531. Buffer[Symbol.species] === Buffer) {
  2532. Object.defineProperty(Buffer, Symbol.species, {
  2533. value: null,
  2534. configurable: true,
  2535. enumerable: false,
  2536. writable: false
  2537. })
  2538. }
  2539. Buffer.poolSize = 8192 // not used by this implementation
  2540. function from (value, encodingOrOffset, length) {
  2541. if (typeof value === 'string') {
  2542. return fromString(value, encodingOrOffset)
  2543. }
  2544. if (ArrayBuffer.isView(value)) {
  2545. return fromArrayLike(value)
  2546. }
  2547. if (value == null) {
  2548. throw TypeError(
  2549. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2550. 'or Array-like Object. Received type ' + (typeof value)
  2551. )
  2552. }
  2553. if (isInstance(value, ArrayBuffer) ||
  2554. (value && isInstance(value.buffer, ArrayBuffer))) {
  2555. return fromArrayBuffer(value, encodingOrOffset, length)
  2556. }
  2557. if (typeof value === 'number') {
  2558. throw new TypeError(
  2559. 'The "value" argument must not be of type number. Received type number'
  2560. )
  2561. }
  2562. var valueOf = value.valueOf && value.valueOf()
  2563. if (valueOf != null && valueOf !== value) {
  2564. return Buffer.from(valueOf, encodingOrOffset, length)
  2565. }
  2566. var b = fromObject(value)
  2567. if (b) return b
  2568. if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
  2569. typeof value[Symbol.toPrimitive] === 'function') {
  2570. return Buffer.from(
  2571. value[Symbol.toPrimitive]('string'), encodingOrOffset, length
  2572. )
  2573. }
  2574. throw new TypeError(
  2575. 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
  2576. 'or Array-like Object. Received type ' + (typeof value)
  2577. )
  2578. }
  2579. /**
  2580. * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
  2581. * if value is a number.
  2582. * Buffer.from(str[, encoding])
  2583. * Buffer.from(array)
  2584. * Buffer.from(buffer)
  2585. * Buffer.from(arrayBuffer[, byteOffset[, length]])
  2586. **/
  2587. Buffer.from = function (value, encodingOrOffset, length) {
  2588. return from(value, encodingOrOffset, length)
  2589. }
  2590. // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
  2591. // https://github.com/feross/buffer/pull/148
  2592. Buffer.prototype.__proto__ = Uint8Array.prototype
  2593. Buffer.__proto__ = Uint8Array
  2594. function assertSize (size) {
  2595. if (typeof size !== 'number') {
  2596. throw new TypeError('"size" argument must be of type number')
  2597. } else if (size < 0) {
  2598. throw new RangeError('The value "' + size + '" is invalid for option "size"')
  2599. }
  2600. }
  2601. function alloc (size, fill, encoding) {
  2602. assertSize(size)
  2603. if (size <= 0) {
  2604. return createBuffer(size)
  2605. }
  2606. if (fill !== undefined) {
  2607. // Only pay attention to encoding if it's a string. This
  2608. // prevents accidentally sending in a number that would
  2609. // be interpretted as a start offset.
  2610. return typeof encoding === 'string'
  2611. ? createBuffer(size).fill(fill, encoding)
  2612. : createBuffer(size).fill(fill)
  2613. }
  2614. return createBuffer(size)
  2615. }
  2616. /**
  2617. * Creates a new filled Buffer instance.
  2618. * alloc(size[, fill[, encoding]])
  2619. **/
  2620. Buffer.alloc = function (size, fill, encoding) {
  2621. return alloc(size, fill, encoding)
  2622. }
  2623. function allocUnsafe (size) {
  2624. assertSize(size)
  2625. return createBuffer(size < 0 ? 0 : checked(size) | 0)
  2626. }
  2627. /**
  2628. * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
  2629. * */
  2630. Buffer.allocUnsafe = function (size) {
  2631. return allocUnsafe(size)
  2632. }
  2633. /**
  2634. * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
  2635. */
  2636. Buffer.allocUnsafeSlow = function (size) {
  2637. return allocUnsafe(size)
  2638. }
  2639. function fromString (string, encoding) {
  2640. if (typeof encoding !== 'string' || encoding === '') {
  2641. encoding = 'utf8'
  2642. }
  2643. if (!Buffer.isEncoding(encoding)) {
  2644. throw new TypeError('Unknown encoding: ' + encoding)
  2645. }
  2646. var length = byteLength(string, encoding) | 0
  2647. var buf = createBuffer(length)
  2648. var actual = buf.write(string, encoding)
  2649. if (actual !== length) {
  2650. // Writing a hex string, for example, that contains invalid characters will
  2651. // cause everything after the first invalid character to be ignored. (e.g.
  2652. // 'abxxcd' will be treated as 'ab')
  2653. buf = buf.slice(0, actual)
  2654. }
  2655. return buf
  2656. }
  2657. function fromArrayLike (array) {
  2658. var length = array.length < 0 ? 0 : checked(array.length) | 0
  2659. var buf = createBuffer(length)
  2660. for (var i = 0; i < length; i += 1) {
  2661. buf[i] = array[i] & 255
  2662. }
  2663. return buf
  2664. }
  2665. function fromArrayBuffer (array, byteOffset, length) {
  2666. if (byteOffset < 0 || array.byteLength < byteOffset) {
  2667. throw new RangeError('"offset" is outside of buffer bounds')
  2668. }
  2669. if (array.byteLength < byteOffset + (length || 0)) {
  2670. throw new RangeError('"length" is outside of buffer bounds')
  2671. }
  2672. var buf
  2673. if (byteOffset === undefined && length === undefined) {
  2674. buf = new Uint8Array(array)
  2675. } else if (length === undefined) {
  2676. buf = new Uint8Array(array, byteOffset)
  2677. } else {
  2678. buf = new Uint8Array(array, byteOffset, length)
  2679. }
  2680. // Return an augmented `Uint8Array` instance
  2681. buf.__proto__ = Buffer.prototype
  2682. return buf
  2683. }
  2684. function fromObject (obj) {
  2685. if (Buffer.isBuffer(obj)) {
  2686. var len = checked(obj.length) | 0
  2687. var buf = createBuffer(len)
  2688. if (buf.length === 0) {
  2689. return buf
  2690. }
  2691. obj.copy(buf, 0, 0, len)
  2692. return buf
  2693. }
  2694. if (obj.length !== undefined) {
  2695. if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
  2696. return createBuffer(0)
  2697. }
  2698. return fromArrayLike(obj)
  2699. }
  2700. if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
  2701. return fromArrayLike(obj.data)
  2702. }
  2703. }
  2704. function checked (length) {
  2705. // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
  2706. // length is NaN (which is otherwise coerced to zero.)
  2707. if (length >= K_MAX_LENGTH) {
  2708. throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
  2709. 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
  2710. }
  2711. return length | 0
  2712. }
  2713. function SlowBuffer (length) {
  2714. if (+length != length) { // eslint-disable-line eqeqeq
  2715. length = 0
  2716. }
  2717. return Buffer.alloc(+length)
  2718. }
  2719. Buffer.isBuffer = function isBuffer (b) {
  2720. return b != null && b._isBuffer === true &&
  2721. b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
  2722. }
  2723. Buffer.compare = function compare (a, b) {
  2724. if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
  2725. if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
  2726. if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
  2727. throw new TypeError(
  2728. 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
  2729. )
  2730. }
  2731. if (a === b) return 0
  2732. var x = a.length
  2733. var y = b.length
  2734. for (var i = 0, len = Math.min(x, y); i < len; ++i) {
  2735. if (a[i] !== b[i]) {
  2736. x = a[i]
  2737. y = b[i]
  2738. break
  2739. }
  2740. }
  2741. if (x < y) return -1
  2742. if (y < x) return 1
  2743. return 0
  2744. }
  2745. Buffer.isEncoding = function isEncoding (encoding) {
  2746. switch (String(encoding).toLowerCase()) {
  2747. case 'hex':
  2748. case 'utf8':
  2749. case 'utf-8':
  2750. case 'ascii':
  2751. case 'latin1':
  2752. case 'binary':
  2753. case 'base64':
  2754. case 'ucs2':
  2755. case 'ucs-2':
  2756. case 'utf16le':
  2757. case 'utf-16le':
  2758. return true
  2759. default:
  2760. return false
  2761. }
  2762. }
  2763. Buffer.concat = function concat (list, length) {
  2764. if (!Array.isArray(list)) {
  2765. throw new TypeError('"list" argument must be an Array of Buffers')
  2766. }
  2767. if (list.length === 0) {
  2768. return Buffer.alloc(0)
  2769. }
  2770. var i
  2771. if (length === undefined) {
  2772. length = 0
  2773. for (i = 0; i < list.length; ++i) {
  2774. length += list[i].length
  2775. }
  2776. }
  2777. var buffer = Buffer.allocUnsafe(length)
  2778. var pos = 0
  2779. for (i = 0; i < list.length; ++i) {
  2780. var buf = list[i]
  2781. if (isInstance(buf, Uint8Array)) {
  2782. buf = Buffer.from(buf)
  2783. }
  2784. if (!Buffer.isBuffer(buf)) {
  2785. throw new TypeError('"list" argument must be an Array of Buffers')
  2786. }
  2787. buf.copy(buffer, pos)
  2788. pos += buf.length
  2789. }
  2790. return buffer
  2791. }
  2792. function byteLength (string, encoding) {
  2793. if (Buffer.isBuffer(string)) {
  2794. return string.length
  2795. }
  2796. if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
  2797. return string.byteLength
  2798. }
  2799. if (typeof string !== 'string') {
  2800. throw new TypeError(
  2801. 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
  2802. 'Received type ' + typeof string
  2803. )
  2804. }
  2805. var len = string.length
  2806. var mustMatch = (arguments.length > 2 && arguments[2] === true)
  2807. if (!mustMatch && len === 0) return 0
  2808. // Use a for loop to avoid recursion
  2809. var loweredCase = false
  2810. for (;;) {
  2811. switch (encoding) {
  2812. case 'ascii':
  2813. case 'latin1':
  2814. case 'binary':
  2815. return len
  2816. case 'utf8':
  2817. case 'utf-8':
  2818. return utf8ToBytes(string).length
  2819. case 'ucs2':
  2820. case 'ucs-2':
  2821. case 'utf16le':
  2822. case 'utf-16le':
  2823. return len * 2
  2824. case 'hex':
  2825. return len >>> 1
  2826. case 'base64':
  2827. return base64ToBytes(string).length
  2828. default:
  2829. if (loweredCase) {
  2830. return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
  2831. }
  2832. encoding = ('' + encoding).toLowerCase()
  2833. loweredCase = true
  2834. }
  2835. }
  2836. }
  2837. Buffer.byteLength = byteLength
  2838. function slowToString (encoding, start, end) {
  2839. var loweredCase = false
  2840. // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
  2841. // property of a typed array.
  2842. // This behaves neither like String nor Uint8Array in that we set start/end
  2843. // to their upper/lower bounds if the value passed is out of range.
  2844. // undefined is handled specially as per ECMA-262 6th Edition,
  2845. // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
  2846. if (start === undefined || start < 0) {
  2847. start = 0
  2848. }
  2849. // Return early if start > this.length. Done here to prevent potential uint32
  2850. // coercion fail below.
  2851. if (start > this.length) {
  2852. return ''
  2853. }
  2854. if (end === undefined || end > this.length) {
  2855. end = this.length
  2856. }
  2857. if (end <= 0) {
  2858. return ''
  2859. }
  2860. // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
  2861. end >>>= 0
  2862. start >>>= 0
  2863. if (end <= start) {
  2864. return ''
  2865. }
  2866. if (!encoding) encoding = 'utf8'
  2867. while (true) {
  2868. switch (encoding) {
  2869. case 'hex':
  2870. return hexSlice(this, start, end)
  2871. case 'utf8':
  2872. case 'utf-8':
  2873. return utf8Slice(this, start, end)
  2874. case 'ascii':
  2875. return asciiSlice(this, start, end)
  2876. case 'latin1':
  2877. case 'binary':
  2878. return latin1Slice(this, start, end)
  2879. case 'base64':
  2880. return base64Slice(this, start, end)
  2881. case 'ucs2':
  2882. case 'ucs-2':
  2883. case 'utf16le':
  2884. case 'utf-16le':
  2885. return utf16leSlice(this, start, end)
  2886. default:
  2887. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  2888. encoding = (encoding + '').toLowerCase()
  2889. loweredCase = true
  2890. }
  2891. }
  2892. }
  2893. // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
  2894. // to detect a Buffer instance. It's not possible to use `instanceof Buffer`
  2895. // reliably in a browserify context because there could be multiple different
  2896. // copies of the 'buffer' package in use. This method works even for Buffer
  2897. // instances that were created from another copy of the `buffer` package.
  2898. // See: https://github.com/feross/buffer/issues/154
  2899. Buffer.prototype._isBuffer = true
  2900. function swap (b, n, m) {
  2901. var i = b[n]
  2902. b[n] = b[m]
  2903. b[m] = i
  2904. }
  2905. Buffer.prototype.swap16 = function swap16 () {
  2906. var len = this.length
  2907. if (len % 2 !== 0) {
  2908. throw new RangeError('Buffer size must be a multiple of 16-bits')
  2909. }
  2910. for (var i = 0; i < len; i += 2) {
  2911. swap(this, i, i + 1)
  2912. }
  2913. return this
  2914. }
  2915. Buffer.prototype.swap32 = function swap32 () {
  2916. var len = this.length
  2917. if (len % 4 !== 0) {
  2918. throw new RangeError('Buffer size must be a multiple of 32-bits')
  2919. }
  2920. for (var i = 0; i < len; i += 4) {
  2921. swap(this, i, i + 3)
  2922. swap(this, i + 1, i + 2)
  2923. }
  2924. return this
  2925. }
  2926. Buffer.prototype.swap64 = function swap64 () {
  2927. var len = this.length
  2928. if (len % 8 !== 0) {
  2929. throw new RangeError('Buffer size must be a multiple of 64-bits')
  2930. }
  2931. for (var i = 0; i < len; i += 8) {
  2932. swap(this, i, i + 7)
  2933. swap(this, i + 1, i + 6)
  2934. swap(this, i + 2, i + 5)
  2935. swap(this, i + 3, i + 4)
  2936. }
  2937. return this
  2938. }
  2939. Buffer.prototype.toString = function toString () {
  2940. var length = this.length
  2941. if (length === 0) return ''
  2942. if (arguments.length === 0) return utf8Slice(this, 0, length)
  2943. return slowToString.apply(this, arguments)
  2944. }
  2945. Buffer.prototype.toLocaleString = Buffer.prototype.toString
  2946. Buffer.prototype.equals = function equals (b) {
  2947. if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
  2948. if (this === b) return true
  2949. return Buffer.compare(this, b) === 0
  2950. }
  2951. Buffer.prototype.inspect = function inspect () {
  2952. var str = ''
  2953. var max = exports.INSPECT_MAX_BYTES
  2954. str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
  2955. if (this.length > max) str += ' ... '
  2956. return '<Buffer ' + str + '>'
  2957. }
  2958. Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
  2959. if (isInstance(target, Uint8Array)) {
  2960. target = Buffer.from(target, target.offset, target.byteLength)
  2961. }
  2962. if (!Buffer.isBuffer(target)) {
  2963. throw new TypeError(
  2964. 'The "target" argument must be one of type Buffer or Uint8Array. ' +
  2965. 'Received type ' + (typeof target)
  2966. )
  2967. }
  2968. if (start === undefined) {
  2969. start = 0
  2970. }
  2971. if (end === undefined) {
  2972. end = target ? target.length : 0
  2973. }
  2974. if (thisStart === undefined) {
  2975. thisStart = 0
  2976. }
  2977. if (thisEnd === undefined) {
  2978. thisEnd = this.length
  2979. }
  2980. if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
  2981. throw new RangeError('out of range index')
  2982. }
  2983. if (thisStart >= thisEnd && start >= end) {
  2984. return 0
  2985. }
  2986. if (thisStart >= thisEnd) {
  2987. return -1
  2988. }
  2989. if (start >= end) {
  2990. return 1
  2991. }
  2992. start >>>= 0
  2993. end >>>= 0
  2994. thisStart >>>= 0
  2995. thisEnd >>>= 0
  2996. if (this === target) return 0
  2997. var x = thisEnd - thisStart
  2998. var y = end - start
  2999. var len = Math.min(x, y)
  3000. var thisCopy = this.slice(thisStart, thisEnd)
  3001. var targetCopy = target.slice(start, end)
  3002. for (var i = 0; i < len; ++i) {
  3003. if (thisCopy[i] !== targetCopy[i]) {
  3004. x = thisCopy[i]
  3005. y = targetCopy[i]
  3006. break
  3007. }
  3008. }
  3009. if (x < y) return -1
  3010. if (y < x) return 1
  3011. return 0
  3012. }
  3013. // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
  3014. // OR the last index of `val` in `buffer` at offset <= `byteOffset`.
  3015. //
  3016. // Arguments:
  3017. // - buffer - a Buffer to search
  3018. // - val - a string, Buffer, or number
  3019. // - byteOffset - an index into `buffer`; will be clamped to an int32
  3020. // - encoding - an optional encoding, relevant is val is a string
  3021. // - dir - true for indexOf, false for lastIndexOf
  3022. function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
  3023. // Empty buffer means no match
  3024. if (buffer.length === 0) return -1
  3025. // Normalize byteOffset
  3026. if (typeof byteOffset === 'string') {
  3027. encoding = byteOffset
  3028. byteOffset = 0
  3029. } else if (byteOffset > 0x7fffffff) {
  3030. byteOffset = 0x7fffffff
  3031. } else if (byteOffset < -0x80000000) {
  3032. byteOffset = -0x80000000
  3033. }
  3034. byteOffset = +byteOffset // Coerce to Number.
  3035. if (numberIsNaN(byteOffset)) {
  3036. // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
  3037. byteOffset = dir ? 0 : (buffer.length - 1)
  3038. }
  3039. // Normalize byteOffset: negative offsets start from the end of the buffer
  3040. if (byteOffset < 0) byteOffset = buffer.length + byteOffset
  3041. if (byteOffset >= buffer.length) {
  3042. if (dir) return -1
  3043. else byteOffset = buffer.length - 1
  3044. } else if (byteOffset < 0) {
  3045. if (dir) byteOffset = 0
  3046. else return -1
  3047. }
  3048. // Normalize val
  3049. if (typeof val === 'string') {
  3050. val = Buffer.from(val, encoding)
  3051. }
  3052. // Finally, search either indexOf (if dir is true) or lastIndexOf
  3053. if (Buffer.isBuffer(val)) {
  3054. // Special case: looking for empty string/buffer always fails
  3055. if (val.length === 0) {
  3056. return -1
  3057. }
  3058. return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
  3059. } else if (typeof val === 'number') {
  3060. val = val & 0xFF // Search for a byte value [0-255]
  3061. if (typeof Uint8Array.prototype.indexOf === 'function') {
  3062. if (dir) {
  3063. return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
  3064. } else {
  3065. return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
  3066. }
  3067. }
  3068. return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
  3069. }
  3070. throw new TypeError('val must be string, number or Buffer')
  3071. }
  3072. function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
  3073. var indexSize = 1
  3074. var arrLength = arr.length
  3075. var valLength = val.length
  3076. if (encoding !== undefined) {
  3077. encoding = String(encoding).toLowerCase()
  3078. if (encoding === 'ucs2' || encoding === 'ucs-2' ||
  3079. encoding === 'utf16le' || encoding === 'utf-16le') {
  3080. if (arr.length < 2 || val.length < 2) {
  3081. return -1
  3082. }
  3083. indexSize = 2
  3084. arrLength /= 2
  3085. valLength /= 2
  3086. byteOffset /= 2
  3087. }
  3088. }
  3089. function read (buf, i) {
  3090. if (indexSize === 1) {
  3091. return buf[i]
  3092. } else {
  3093. return buf.readUInt16BE(i * indexSize)
  3094. }
  3095. }
  3096. var i
  3097. if (dir) {
  3098. var foundIndex = -1
  3099. for (i = byteOffset; i < arrLength; i++) {
  3100. if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
  3101. if (foundIndex === -1) foundIndex = i
  3102. if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
  3103. } else {
  3104. if (foundIndex !== -1) i -= i - foundIndex
  3105. foundIndex = -1
  3106. }
  3107. }
  3108. } else {
  3109. if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
  3110. for (i = byteOffset; i >= 0; i--) {
  3111. var found = true
  3112. for (var j = 0; j < valLength; j++) {
  3113. if (read(arr, i + j) !== read(val, j)) {
  3114. found = false
  3115. break
  3116. }
  3117. }
  3118. if (found) return i
  3119. }
  3120. }
  3121. return -1
  3122. }
  3123. Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
  3124. return this.indexOf(val, byteOffset, encoding) !== -1
  3125. }
  3126. Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
  3127. return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
  3128. }
  3129. Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
  3130. return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
  3131. }
  3132. function hexWrite (buf, string, offset, length) {
  3133. offset = Number(offset) || 0
  3134. var remaining = buf.length - offset
  3135. if (!length) {
  3136. length = remaining
  3137. } else {
  3138. length = Number(length)
  3139. if (length > remaining) {
  3140. length = remaining
  3141. }
  3142. }
  3143. var strLen = string.length
  3144. if (length > strLen / 2) {
  3145. length = strLen / 2
  3146. }
  3147. for (var i = 0; i < length; ++i) {
  3148. var parsed = parseInt(string.substr(i * 2, 2), 16)
  3149. if (numberIsNaN(parsed)) return i
  3150. buf[offset + i] = parsed
  3151. }
  3152. return i
  3153. }
  3154. function utf8Write (buf, string, offset, length) {
  3155. return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
  3156. }
  3157. function asciiWrite (buf, string, offset, length) {
  3158. return blitBuffer(asciiToBytes(string), buf, offset, length)
  3159. }
  3160. function latin1Write (buf, string, offset, length) {
  3161. return asciiWrite(buf, string, offset, length)
  3162. }
  3163. function base64Write (buf, string, offset, length) {
  3164. return blitBuffer(base64ToBytes(string), buf, offset, length)
  3165. }
  3166. function ucs2Write (buf, string, offset, length) {
  3167. return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
  3168. }
  3169. Buffer.prototype.write = function write (string, offset, length, encoding) {
  3170. // Buffer#write(string)
  3171. if (offset === undefined) {
  3172. encoding = 'utf8'
  3173. length = this.length
  3174. offset = 0
  3175. // Buffer#write(string, encoding)
  3176. } else if (length === undefined && typeof offset === 'string') {
  3177. encoding = offset
  3178. length = this.length
  3179. offset = 0
  3180. // Buffer#write(string, offset[, length][, encoding])
  3181. } else if (isFinite(offset)) {
  3182. offset = offset >>> 0
  3183. if (isFinite(length)) {
  3184. length = length >>> 0
  3185. if (encoding === undefined) encoding = 'utf8'
  3186. } else {
  3187. encoding = length
  3188. length = undefined
  3189. }
  3190. } else {
  3191. throw new Error(
  3192. 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
  3193. )
  3194. }
  3195. var remaining = this.length - offset
  3196. if (length === undefined || length > remaining) length = remaining
  3197. if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
  3198. throw new RangeError('Attempt to write outside buffer bounds')
  3199. }
  3200. if (!encoding) encoding = 'utf8'
  3201. var loweredCase = false
  3202. for (;;) {
  3203. switch (encoding) {
  3204. case 'hex':
  3205. return hexWrite(this, string, offset, length)
  3206. case 'utf8':
  3207. case 'utf-8':
  3208. return utf8Write(this, string, offset, length)
  3209. case 'ascii':
  3210. return asciiWrite(this, string, offset, length)
  3211. case 'latin1':
  3212. case 'binary':
  3213. return latin1Write(this, string, offset, length)
  3214. case 'base64':
  3215. // Warning: maxLength not taken into account in base64Write
  3216. return base64Write(this, string, offset, length)
  3217. case 'ucs2':
  3218. case 'ucs-2':
  3219. case 'utf16le':
  3220. case 'utf-16le':
  3221. return ucs2Write(this, string, offset, length)
  3222. default:
  3223. if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
  3224. encoding = ('' + encoding).toLowerCase()
  3225. loweredCase = true
  3226. }
  3227. }
  3228. }
  3229. Buffer.prototype.toJSON = function toJSON () {
  3230. return {
  3231. type: 'Buffer',
  3232. data: Array.prototype.slice.call(this._arr || this, 0)
  3233. }
  3234. }
  3235. function base64Slice (buf, start, end) {
  3236. if (start === 0 && end === buf.length) {
  3237. return base64.fromByteArray(buf)
  3238. } else {
  3239. return base64.fromByteArray(buf.slice(start, end))
  3240. }
  3241. }
  3242. function utf8Slice (buf, start, end) {
  3243. end = Math.min(buf.length, end)
  3244. var res = []
  3245. var i = start
  3246. while (i < end) {
  3247. var firstByte = buf[i]
  3248. var codePoint = null
  3249. var bytesPerSequence = (firstByte > 0xEF) ? 4
  3250. : (firstByte > 0xDF) ? 3
  3251. : (firstByte > 0xBF) ? 2
  3252. : 1
  3253. if (i + bytesPerSequence <= end) {
  3254. var secondByte, thirdByte, fourthByte, tempCodePoint
  3255. switch (bytesPerSequence) {
  3256. case 1:
  3257. if (firstByte < 0x80) {
  3258. codePoint = firstByte
  3259. }
  3260. break
  3261. case 2:
  3262. secondByte = buf[i + 1]
  3263. if ((secondByte & 0xC0) === 0x80) {
  3264. tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
  3265. if (tempCodePoint > 0x7F) {
  3266. codePoint = tempCodePoint
  3267. }
  3268. }
  3269. break
  3270. case 3:
  3271. secondByte = buf[i + 1]
  3272. thirdByte = buf[i + 2]
  3273. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
  3274. tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
  3275. if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
  3276. codePoint = tempCodePoint
  3277. }
  3278. }
  3279. break
  3280. case 4:
  3281. secondByte = buf[i + 1]
  3282. thirdByte = buf[i + 2]
  3283. fourthByte = buf[i + 3]
  3284. if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
  3285. tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
  3286. if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
  3287. codePoint = tempCodePoint
  3288. }
  3289. }
  3290. }
  3291. }
  3292. if (codePoint === null) {
  3293. // we did not generate a valid codePoint so insert a
  3294. // replacement char (U+FFFD) and advance only 1 byte
  3295. codePoint = 0xFFFD
  3296. bytesPerSequence = 1
  3297. } else if (codePoint > 0xFFFF) {
  3298. // encode to utf16 (surrogate pair dance)
  3299. codePoint -= 0x10000
  3300. res.push(codePoint >>> 10 & 0x3FF | 0xD800)
  3301. codePoint = 0xDC00 | codePoint & 0x3FF
  3302. }
  3303. res.push(codePoint)
  3304. i += bytesPerSequence
  3305. }
  3306. return decodeCodePointsArray(res)
  3307. }
  3308. // Based on http://stackoverflow.com/a/22747272/680742, the browser with
  3309. // the lowest limit is Chrome, with 0x10000 args.
  3310. // We go 1 magnitude less, for safety
  3311. var MAX_ARGUMENTS_LENGTH = 0x1000
  3312. function decodeCodePointsArray (codePoints) {
  3313. var len = codePoints.length
  3314. if (len <= MAX_ARGUMENTS_LENGTH) {
  3315. return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
  3316. }
  3317. // Decode in chunks to avoid "call stack size exceeded".
  3318. var res = ''
  3319. var i = 0
  3320. while (i < len) {
  3321. res += String.fromCharCode.apply(
  3322. String,
  3323. codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
  3324. )
  3325. }
  3326. return res
  3327. }
  3328. function asciiSlice (buf, start, end) {
  3329. var ret = ''
  3330. end = Math.min(buf.length, end)
  3331. for (var i = start; i < end; ++i) {
  3332. ret += String.fromCharCode(buf[i] & 0x7F)
  3333. }
  3334. return ret
  3335. }
  3336. function latin1Slice (buf, start, end) {
  3337. var ret = ''
  3338. end = Math.min(buf.length, end)
  3339. for (var i = start; i < end; ++i) {
  3340. ret += String.fromCharCode(buf[i])
  3341. }
  3342. return ret
  3343. }
  3344. function hexSlice (buf, start, end) {
  3345. var len = buf.length
  3346. if (!start || start < 0) start = 0
  3347. if (!end || end < 0 || end > len) end = len
  3348. var out = ''
  3349. for (var i = start; i < end; ++i) {
  3350. out += toHex(buf[i])
  3351. }
  3352. return out
  3353. }
  3354. function utf16leSlice (buf, start, end) {
  3355. var bytes = buf.slice(start, end)
  3356. var res = ''
  3357. for (var i = 0; i < bytes.length; i += 2) {
  3358. res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
  3359. }
  3360. return res
  3361. }
  3362. Buffer.prototype.slice = function slice (start, end) {
  3363. var len = this.length
  3364. start = ~~start
  3365. end = end === undefined ? len : ~~end
  3366. if (start < 0) {
  3367. start += len
  3368. if (start < 0) start = 0
  3369. } else if (start > len) {
  3370. start = len
  3371. }
  3372. if (end < 0) {
  3373. end += len
  3374. if (end < 0) end = 0
  3375. } else if (end > len) {
  3376. end = len
  3377. }
  3378. if (end < start) end = start
  3379. var newBuf = this.subarray(start, end)
  3380. // Return an augmented `Uint8Array` instance
  3381. newBuf.__proto__ = Buffer.prototype
  3382. return newBuf
  3383. }
  3384. /*
  3385. * Need to make sure that buffer isn't trying to write out of bounds.
  3386. */
  3387. function checkOffset (offset, ext, length) {
  3388. if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
  3389. if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
  3390. }
  3391. Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
  3392. offset = offset >>> 0
  3393. byteLength = byteLength >>> 0
  3394. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3395. var val = this[offset]
  3396. var mul = 1
  3397. var i = 0
  3398. while (++i < byteLength && (mul *= 0x100)) {
  3399. val += this[offset + i] * mul
  3400. }
  3401. return val
  3402. }
  3403. Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
  3404. offset = offset >>> 0
  3405. byteLength = byteLength >>> 0
  3406. if (!noAssert) {
  3407. checkOffset(offset, byteLength, this.length)
  3408. }
  3409. var val = this[offset + --byteLength]
  3410. var mul = 1
  3411. while (byteLength > 0 && (mul *= 0x100)) {
  3412. val += this[offset + --byteLength] * mul
  3413. }
  3414. return val
  3415. }
  3416. Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
  3417. offset = offset >>> 0
  3418. if (!noAssert) checkOffset(offset, 1, this.length)
  3419. return this[offset]
  3420. }
  3421. Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
  3422. offset = offset >>> 0
  3423. if (!noAssert) checkOffset(offset, 2, this.length)
  3424. return this[offset] | (this[offset + 1] << 8)
  3425. }
  3426. Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
  3427. offset = offset >>> 0
  3428. if (!noAssert) checkOffset(offset, 2, this.length)
  3429. return (this[offset] << 8) | this[offset + 1]
  3430. }
  3431. Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
  3432. offset = offset >>> 0
  3433. if (!noAssert) checkOffset(offset, 4, this.length)
  3434. return ((this[offset]) |
  3435. (this[offset + 1] << 8) |
  3436. (this[offset + 2] << 16)) +
  3437. (this[offset + 3] * 0x1000000)
  3438. }
  3439. Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
  3440. offset = offset >>> 0
  3441. if (!noAssert) checkOffset(offset, 4, this.length)
  3442. return (this[offset] * 0x1000000) +
  3443. ((this[offset + 1] << 16) |
  3444. (this[offset + 2] << 8) |
  3445. this[offset + 3])
  3446. }
  3447. Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
  3448. offset = offset >>> 0
  3449. byteLength = byteLength >>> 0
  3450. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3451. var val = this[offset]
  3452. var mul = 1
  3453. var i = 0
  3454. while (++i < byteLength && (mul *= 0x100)) {
  3455. val += this[offset + i] * mul
  3456. }
  3457. mul *= 0x80
  3458. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3459. return val
  3460. }
  3461. Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
  3462. offset = offset >>> 0
  3463. byteLength = byteLength >>> 0
  3464. if (!noAssert) checkOffset(offset, byteLength, this.length)
  3465. var i = byteLength
  3466. var mul = 1
  3467. var val = this[offset + --i]
  3468. while (i > 0 && (mul *= 0x100)) {
  3469. val += this[offset + --i] * mul
  3470. }
  3471. mul *= 0x80
  3472. if (val >= mul) val -= Math.pow(2, 8 * byteLength)
  3473. return val
  3474. }
  3475. Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
  3476. offset = offset >>> 0
  3477. if (!noAssert) checkOffset(offset, 1, this.length)
  3478. if (!(this[offset] & 0x80)) return (this[offset])
  3479. return ((0xff - this[offset] + 1) * -1)
  3480. }
  3481. Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
  3482. offset = offset >>> 0
  3483. if (!noAssert) checkOffset(offset, 2, this.length)
  3484. var val = this[offset] | (this[offset + 1] << 8)
  3485. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3486. }
  3487. Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
  3488. offset = offset >>> 0
  3489. if (!noAssert) checkOffset(offset, 2, this.length)
  3490. var val = this[offset + 1] | (this[offset] << 8)
  3491. return (val & 0x8000) ? val | 0xFFFF0000 : val
  3492. }
  3493. Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
  3494. offset = offset >>> 0
  3495. if (!noAssert) checkOffset(offset, 4, this.length)
  3496. return (this[offset]) |
  3497. (this[offset + 1] << 8) |
  3498. (this[offset + 2] << 16) |
  3499. (this[offset + 3] << 24)
  3500. }
  3501. Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
  3502. offset = offset >>> 0
  3503. if (!noAssert) checkOffset(offset, 4, this.length)
  3504. return (this[offset] << 24) |
  3505. (this[offset + 1] << 16) |
  3506. (this[offset + 2] << 8) |
  3507. (this[offset + 3])
  3508. }
  3509. Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
  3510. offset = offset >>> 0
  3511. if (!noAssert) checkOffset(offset, 4, this.length)
  3512. return ieee754.read(this, offset, true, 23, 4)
  3513. }
  3514. Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
  3515. offset = offset >>> 0
  3516. if (!noAssert) checkOffset(offset, 4, this.length)
  3517. return ieee754.read(this, offset, false, 23, 4)
  3518. }
  3519. Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
  3520. offset = offset >>> 0
  3521. if (!noAssert) checkOffset(offset, 8, this.length)
  3522. return ieee754.read(this, offset, true, 52, 8)
  3523. }
  3524. Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
  3525. offset = offset >>> 0
  3526. if (!noAssert) checkOffset(offset, 8, this.length)
  3527. return ieee754.read(this, offset, false, 52, 8)
  3528. }
  3529. function checkInt (buf, value, offset, ext, max, min) {
  3530. if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
  3531. if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
  3532. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3533. }
  3534. Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
  3535. value = +value
  3536. offset = offset >>> 0
  3537. byteLength = byteLength >>> 0
  3538. if (!noAssert) {
  3539. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3540. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3541. }
  3542. var mul = 1
  3543. var i = 0
  3544. this[offset] = value & 0xFF
  3545. while (++i < byteLength && (mul *= 0x100)) {
  3546. this[offset + i] = (value / mul) & 0xFF
  3547. }
  3548. return offset + byteLength
  3549. }
  3550. Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
  3551. value = +value
  3552. offset = offset >>> 0
  3553. byteLength = byteLength >>> 0
  3554. if (!noAssert) {
  3555. var maxBytes = Math.pow(2, 8 * byteLength) - 1
  3556. checkInt(this, value, offset, byteLength, maxBytes, 0)
  3557. }
  3558. var i = byteLength - 1
  3559. var mul = 1
  3560. this[offset + i] = value & 0xFF
  3561. while (--i >= 0 && (mul *= 0x100)) {
  3562. this[offset + i] = (value / mul) & 0xFF
  3563. }
  3564. return offset + byteLength
  3565. }
  3566. Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
  3567. value = +value
  3568. offset = offset >>> 0
  3569. if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
  3570. this[offset] = (value & 0xff)
  3571. return offset + 1
  3572. }
  3573. Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
  3574. value = +value
  3575. offset = offset >>> 0
  3576. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3577. this[offset] = (value & 0xff)
  3578. this[offset + 1] = (value >>> 8)
  3579. return offset + 2
  3580. }
  3581. Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
  3582. value = +value
  3583. offset = offset >>> 0
  3584. if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
  3585. this[offset] = (value >>> 8)
  3586. this[offset + 1] = (value & 0xff)
  3587. return offset + 2
  3588. }
  3589. Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
  3590. value = +value
  3591. offset = offset >>> 0
  3592. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3593. this[offset + 3] = (value >>> 24)
  3594. this[offset + 2] = (value >>> 16)
  3595. this[offset + 1] = (value >>> 8)
  3596. this[offset] = (value & 0xff)
  3597. return offset + 4
  3598. }
  3599. Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
  3600. value = +value
  3601. offset = offset >>> 0
  3602. if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
  3603. this[offset] = (value >>> 24)
  3604. this[offset + 1] = (value >>> 16)
  3605. this[offset + 2] = (value >>> 8)
  3606. this[offset + 3] = (value & 0xff)
  3607. return offset + 4
  3608. }
  3609. Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
  3610. value = +value
  3611. offset = offset >>> 0
  3612. if (!noAssert) {
  3613. var limit = Math.pow(2, (8 * byteLength) - 1)
  3614. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3615. }
  3616. var i = 0
  3617. var mul = 1
  3618. var sub = 0
  3619. this[offset] = value & 0xFF
  3620. while (++i < byteLength && (mul *= 0x100)) {
  3621. if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
  3622. sub = 1
  3623. }
  3624. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3625. }
  3626. return offset + byteLength
  3627. }
  3628. Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
  3629. value = +value
  3630. offset = offset >>> 0
  3631. if (!noAssert) {
  3632. var limit = Math.pow(2, (8 * byteLength) - 1)
  3633. checkInt(this, value, offset, byteLength, limit - 1, -limit)
  3634. }
  3635. var i = byteLength - 1
  3636. var mul = 1
  3637. var sub = 0
  3638. this[offset + i] = value & 0xFF
  3639. while (--i >= 0 && (mul *= 0x100)) {
  3640. if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
  3641. sub = 1
  3642. }
  3643. this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
  3644. }
  3645. return offset + byteLength
  3646. }
  3647. Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
  3648. value = +value
  3649. offset = offset >>> 0
  3650. if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
  3651. if (value < 0) value = 0xff + value + 1
  3652. this[offset] = (value & 0xff)
  3653. return offset + 1
  3654. }
  3655. Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
  3656. value = +value
  3657. offset = offset >>> 0
  3658. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3659. this[offset] = (value & 0xff)
  3660. this[offset + 1] = (value >>> 8)
  3661. return offset + 2
  3662. }
  3663. Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
  3664. value = +value
  3665. offset = offset >>> 0
  3666. if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
  3667. this[offset] = (value >>> 8)
  3668. this[offset + 1] = (value & 0xff)
  3669. return offset + 2
  3670. }
  3671. Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
  3672. value = +value
  3673. offset = offset >>> 0
  3674. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3675. this[offset] = (value & 0xff)
  3676. this[offset + 1] = (value >>> 8)
  3677. this[offset + 2] = (value >>> 16)
  3678. this[offset + 3] = (value >>> 24)
  3679. return offset + 4
  3680. }
  3681. Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
  3682. value = +value
  3683. offset = offset >>> 0
  3684. if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
  3685. if (value < 0) value = 0xffffffff + value + 1
  3686. this[offset] = (value >>> 24)
  3687. this[offset + 1] = (value >>> 16)
  3688. this[offset + 2] = (value >>> 8)
  3689. this[offset + 3] = (value & 0xff)
  3690. return offset + 4
  3691. }
  3692. function checkIEEE754 (buf, value, offset, ext, max, min) {
  3693. if (offset + ext > buf.length) throw new RangeError('Index out of range')
  3694. if (offset < 0) throw new RangeError('Index out of range')
  3695. }
  3696. function writeFloat (buf, value, offset, littleEndian, noAssert) {
  3697. value = +value
  3698. offset = offset >>> 0
  3699. if (!noAssert) {
  3700. checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
  3701. }
  3702. ieee754.write(buf, value, offset, littleEndian, 23, 4)
  3703. return offset + 4
  3704. }
  3705. Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
  3706. return writeFloat(this, value, offset, true, noAssert)
  3707. }
  3708. Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
  3709. return writeFloat(this, value, offset, false, noAssert)
  3710. }
  3711. function writeDouble (buf, value, offset, littleEndian, noAssert) {
  3712. value = +value
  3713. offset = offset >>> 0
  3714. if (!noAssert) {
  3715. checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
  3716. }
  3717. ieee754.write(buf, value, offset, littleEndian, 52, 8)
  3718. return offset + 8
  3719. }
  3720. Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
  3721. return writeDouble(this, value, offset, true, noAssert)
  3722. }
  3723. Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
  3724. return writeDouble(this, value, offset, false, noAssert)
  3725. }
  3726. // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
  3727. Buffer.prototype.copy = function copy (target, targetStart, start, end) {
  3728. if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
  3729. if (!start) start = 0
  3730. if (!end && end !== 0) end = this.length
  3731. if (targetStart >= target.length) targetStart = target.length
  3732. if (!targetStart) targetStart = 0
  3733. if (end > 0 && end < start) end = start
  3734. // Copy 0 bytes; we're done
  3735. if (end === start) return 0
  3736. if (target.length === 0 || this.length === 0) return 0
  3737. // Fatal error conditions
  3738. if (targetStart < 0) {
  3739. throw new RangeError('targetStart out of bounds')
  3740. }
  3741. if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
  3742. if (end < 0) throw new RangeError('sourceEnd out of bounds')
  3743. // Are we oob?
  3744. if (end > this.length) end = this.length
  3745. if (target.length - targetStart < end - start) {
  3746. end = target.length - targetStart + start
  3747. }
  3748. var len = end - start
  3749. if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
  3750. // Use built-in when available, missing from IE11
  3751. this.copyWithin(targetStart, start, end)
  3752. } else if (this === target && start < targetStart && targetStart < end) {
  3753. // descending copy from end
  3754. for (var i = len - 1; i >= 0; --i) {
  3755. target[i + targetStart] = this[i + start]
  3756. }
  3757. } else {
  3758. Uint8Array.prototype.set.call(
  3759. target,
  3760. this.subarray(start, end),
  3761. targetStart
  3762. )
  3763. }
  3764. return len
  3765. }
  3766. // Usage:
  3767. // buffer.fill(number[, offset[, end]])
  3768. // buffer.fill(buffer[, offset[, end]])
  3769. // buffer.fill(string[, offset[, end]][, encoding])
  3770. Buffer.prototype.fill = function fill (val, start, end, encoding) {
  3771. // Handle string cases:
  3772. if (typeof val === 'string') {
  3773. if (typeof start === 'string') {
  3774. encoding = start
  3775. start = 0
  3776. end = this.length
  3777. } else if (typeof end === 'string') {
  3778. encoding = end
  3779. end = this.length
  3780. }
  3781. if (encoding !== undefined && typeof encoding !== 'string') {
  3782. throw new TypeError('encoding must be a string')
  3783. }
  3784. if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
  3785. throw new TypeError('Unknown encoding: ' + encoding)
  3786. }
  3787. if (val.length === 1) {
  3788. var code = val.charCodeAt(0)
  3789. if ((encoding === 'utf8' && code < 128) ||
  3790. encoding === 'latin1') {
  3791. // Fast path: If `val` fits into a single byte, use that numeric value.
  3792. val = code
  3793. }
  3794. }
  3795. } else if (typeof val === 'number') {
  3796. val = val & 255
  3797. }
  3798. // Invalid ranges are not set to a default, so can range check early.
  3799. if (start < 0 || this.length < start || this.length < end) {
  3800. throw new RangeError('Out of range index')
  3801. }
  3802. if (end <= start) {
  3803. return this
  3804. }
  3805. start = start >>> 0
  3806. end = end === undefined ? this.length : end >>> 0
  3807. if (!val) val = 0
  3808. var i
  3809. if (typeof val === 'number') {
  3810. for (i = start; i < end; ++i) {
  3811. this[i] = val
  3812. }
  3813. } else {
  3814. var bytes = Buffer.isBuffer(val)
  3815. ? val
  3816. : Buffer.from(val, encoding)
  3817. var len = bytes.length
  3818. if (len === 0) {
  3819. throw new TypeError('The value "' + val +
  3820. '" is invalid for argument "value"')
  3821. }
  3822. for (i = 0; i < end - start; ++i) {
  3823. this[i + start] = bytes[i % len]
  3824. }
  3825. }
  3826. return this
  3827. }
  3828. // HELPER FUNCTIONS
  3829. // ================
  3830. var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
  3831. function base64clean (str) {
  3832. // Node takes equal signs as end of the Base64 encoding
  3833. str = str.split('=')[0]
  3834. // Node strips out invalid characters like \n and \t from the string, base64-js does not
  3835. str = str.trim().replace(INVALID_BASE64_RE, '')
  3836. // Node converts strings with length < 2 to ''
  3837. if (str.length < 2) return ''
  3838. // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
  3839. while (str.length % 4 !== 0) {
  3840. str = str + '='
  3841. }
  3842. return str
  3843. }
  3844. function toHex (n) {
  3845. if (n < 16) return '0' + n.toString(16)
  3846. return n.toString(16)
  3847. }
  3848. function utf8ToBytes (string, units) {
  3849. units = units || Infinity
  3850. var codePoint
  3851. var length = string.length
  3852. var leadSurrogate = null
  3853. var bytes = []
  3854. for (var i = 0; i < length; ++i) {
  3855. codePoint = string.charCodeAt(i)
  3856. // is surrogate component
  3857. if (codePoint > 0xD7FF && codePoint < 0xE000) {
  3858. // last char was a lead
  3859. if (!leadSurrogate) {
  3860. // no lead yet
  3861. if (codePoint > 0xDBFF) {
  3862. // unexpected trail
  3863. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3864. continue
  3865. } else if (i + 1 === length) {
  3866. // unpaired lead
  3867. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3868. continue
  3869. }
  3870. // valid lead
  3871. leadSurrogate = codePoint
  3872. continue
  3873. }
  3874. // 2 leads in a row
  3875. if (codePoint < 0xDC00) {
  3876. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3877. leadSurrogate = codePoint
  3878. continue
  3879. }
  3880. // valid surrogate pair
  3881. codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
  3882. } else if (leadSurrogate) {
  3883. // valid bmp char, but last char was a lead
  3884. if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
  3885. }
  3886. leadSurrogate = null
  3887. // encode utf8
  3888. if (codePoint < 0x80) {
  3889. if ((units -= 1) < 0) break
  3890. bytes.push(codePoint)
  3891. } else if (codePoint < 0x800) {
  3892. if ((units -= 2) < 0) break
  3893. bytes.push(
  3894. codePoint >> 0x6 | 0xC0,
  3895. codePoint & 0x3F | 0x80
  3896. )
  3897. } else if (codePoint < 0x10000) {
  3898. if ((units -= 3) < 0) break
  3899. bytes.push(
  3900. codePoint >> 0xC | 0xE0,
  3901. codePoint >> 0x6 & 0x3F | 0x80,
  3902. codePoint & 0x3F | 0x80
  3903. )
  3904. } else if (codePoint < 0x110000) {
  3905. if ((units -= 4) < 0) break
  3906. bytes.push(
  3907. codePoint >> 0x12 | 0xF0,
  3908. codePoint >> 0xC & 0x3F | 0x80,
  3909. codePoint >> 0x6 & 0x3F | 0x80,
  3910. codePoint & 0x3F | 0x80
  3911. )
  3912. } else {
  3913. throw new Error('Invalid code point')
  3914. }
  3915. }
  3916. return bytes
  3917. }
  3918. function asciiToBytes (str) {
  3919. var byteArray = []
  3920. for (var i = 0; i < str.length; ++i) {
  3921. // Node's code seems to be doing this and not & 0x7F..
  3922. byteArray.push(str.charCodeAt(i) & 0xFF)
  3923. }
  3924. return byteArray
  3925. }
  3926. function utf16leToBytes (str, units) {
  3927. var c, hi, lo
  3928. var byteArray = []
  3929. for (var i = 0; i < str.length; ++i) {
  3930. if ((units -= 2) < 0) break
  3931. c = str.charCodeAt(i)
  3932. hi = c >> 8
  3933. lo = c % 256
  3934. byteArray.push(lo)
  3935. byteArray.push(hi)
  3936. }
  3937. return byteArray
  3938. }
  3939. function base64ToBytes (str) {
  3940. return base64.toByteArray(base64clean(str))
  3941. }
  3942. function blitBuffer (src, dst, offset, length) {
  3943. for (var i = 0; i < length; ++i) {
  3944. if ((i + offset >= dst.length) || (i >= src.length)) break
  3945. dst[i + offset] = src[i]
  3946. }
  3947. return i
  3948. }
  3949. // ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
  3950. // the `instanceof` check but they should be treated as of that type.
  3951. // See: https://github.com/feross/buffer/issues/166
  3952. function isInstance (obj, type) {
  3953. return obj instanceof type ||
  3954. (obj != null && obj.constructor != null && obj.constructor.name != null &&
  3955. obj.constructor.name === type.name)
  3956. }
  3957. function numberIsNaN (obj) {
  3958. // For IE11 support
  3959. return obj !== obj // eslint-disable-line no-self-compare
  3960. }
  3961. }).call(this,require("buffer").Buffer)
  3962. },{"base64-js":5,"buffer":8,"ieee754":28}],9:[function(require,module,exports){
  3963. // shim for using process in browser
  3964. var process = module.exports = {};
  3965. // cached from whatever global is present so that test runners that stub it
  3966. // don't break things. But we need to wrap it in a try catch in case it is
  3967. // wrapped in strict mode code which doesn't define any globals. It's inside a
  3968. // function because try/catches deoptimize in certain engines.
  3969. var cachedSetTimeout;
  3970. var cachedClearTimeout;
  3971. function defaultSetTimout() {
  3972. throw new Error('setTimeout has not been defined');
  3973. }
  3974. function defaultClearTimeout () {
  3975. throw new Error('clearTimeout has not been defined');
  3976. }
  3977. (function () {
  3978. try {
  3979. if (typeof setTimeout === 'function') {
  3980. cachedSetTimeout = setTimeout;
  3981. } else {
  3982. cachedSetTimeout = defaultSetTimout;
  3983. }
  3984. } catch (e) {
  3985. cachedSetTimeout = defaultSetTimout;
  3986. }
  3987. try {
  3988. if (typeof clearTimeout === 'function') {
  3989. cachedClearTimeout = clearTimeout;
  3990. } else {
  3991. cachedClearTimeout = defaultClearTimeout;
  3992. }
  3993. } catch (e) {
  3994. cachedClearTimeout = defaultClearTimeout;
  3995. }
  3996. } ())
  3997. function runTimeout(fun) {
  3998. if (cachedSetTimeout === setTimeout) {
  3999. //normal enviroments in sane situations
  4000. return setTimeout(fun, 0);
  4001. }
  4002. // if setTimeout wasn't available but was latter defined
  4003. if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
  4004. cachedSetTimeout = setTimeout;
  4005. return setTimeout(fun, 0);
  4006. }
  4007. try {
  4008. // when when somebody has screwed with setTimeout but no I.E. maddness
  4009. return cachedSetTimeout(fun, 0);
  4010. } catch(e){
  4011. try {
  4012. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4013. return cachedSetTimeout.call(null, fun, 0);
  4014. } catch(e){
  4015. // 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
  4016. return cachedSetTimeout.call(this, fun, 0);
  4017. }
  4018. }
  4019. }
  4020. function runClearTimeout(marker) {
  4021. if (cachedClearTimeout === clearTimeout) {
  4022. //normal enviroments in sane situations
  4023. return clearTimeout(marker);
  4024. }
  4025. // if clearTimeout wasn't available but was latter defined
  4026. if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
  4027. cachedClearTimeout = clearTimeout;
  4028. return clearTimeout(marker);
  4029. }
  4030. try {
  4031. // when when somebody has screwed with setTimeout but no I.E. maddness
  4032. return cachedClearTimeout(marker);
  4033. } catch (e){
  4034. try {
  4035. // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
  4036. return cachedClearTimeout.call(null, marker);
  4037. } catch (e){
  4038. // 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.
  4039. // Some versions of I.E. have different rules for clearTimeout vs setTimeout
  4040. return cachedClearTimeout.call(this, marker);
  4041. }
  4042. }
  4043. }
  4044. var queue = [];
  4045. var draining = false;
  4046. var currentQueue;
  4047. var queueIndex = -1;
  4048. function cleanUpNextTick() {
  4049. if (!draining || !currentQueue) {
  4050. return;
  4051. }
  4052. draining = false;
  4053. if (currentQueue.length) {
  4054. queue = currentQueue.concat(queue);
  4055. } else {
  4056. queueIndex = -1;
  4057. }
  4058. if (queue.length) {
  4059. drainQueue();
  4060. }
  4061. }
  4062. function drainQueue() {
  4063. if (draining) {
  4064. return;
  4065. }
  4066. var timeout = runTimeout(cleanUpNextTick);
  4067. draining = true;
  4068. var len = queue.length;
  4069. while(len) {
  4070. currentQueue = queue;
  4071. queue = [];
  4072. while (++queueIndex < len) {
  4073. if (currentQueue) {
  4074. currentQueue[queueIndex].run();
  4075. }
  4076. }
  4077. queueIndex = -1;
  4078. len = queue.length;
  4079. }
  4080. currentQueue = null;
  4081. draining = false;
  4082. runClearTimeout(timeout);
  4083. }
  4084. process.nextTick = function (fun) {
  4085. var args = new Array(arguments.length - 1);
  4086. if (arguments.length > 1) {
  4087. for (var i = 1; i < arguments.length; i++) {
  4088. args[i - 1] = arguments[i];
  4089. }
  4090. }
  4091. queue.push(new Item(fun, args));
  4092. if (queue.length === 1 && !draining) {
  4093. runTimeout(drainQueue);
  4094. }
  4095. };
  4096. // v8 likes predictible objects
  4097. function Item(fun, array) {
  4098. this.fun = fun;
  4099. this.array = array;
  4100. }
  4101. Item.prototype.run = function () {
  4102. this.fun.apply(null, this.array);
  4103. };
  4104. process.title = 'browser';
  4105. process.browser = true;
  4106. process.env = {};
  4107. process.argv = [];
  4108. process.version = ''; // empty string to avoid regexp issues
  4109. process.versions = {};
  4110. function noop() {}
  4111. process.on = noop;
  4112. process.addListener = noop;
  4113. process.once = noop;
  4114. process.off = noop;
  4115. process.removeListener = noop;
  4116. process.removeAllListeners = noop;
  4117. process.emit = noop;
  4118. process.prependListener = noop;
  4119. process.prependOnceListener = noop;
  4120. process.listeners = function (name) { return [] }
  4121. process.binding = function (name) {
  4122. throw new Error('process.binding is not supported');
  4123. };
  4124. process.cwd = function () { return '/' };
  4125. process.chdir = function (dir) {
  4126. throw new Error('process.chdir is not supported');
  4127. };
  4128. process.umask = function() { return 0; };
  4129. },{}],10:[function(require,module,exports){
  4130. (function (Buffer){
  4131. // Copyright Joyent, Inc. and other Node contributors.
  4132. //
  4133. // Permission is hereby granted, free of charge, to any person obtaining a
  4134. // copy of this software and associated documentation files (the
  4135. // "Software"), to deal in the Software without restriction, including
  4136. // without limitation the rights to use, copy, modify, merge, publish,
  4137. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4138. // persons to whom the Software is furnished to do so, subject to the
  4139. // following conditions:
  4140. //
  4141. // The above copyright notice and this permission notice shall be included
  4142. // in all copies or substantial portions of the Software.
  4143. //
  4144. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4145. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4146. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4147. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4148. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4149. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4150. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4151. // NOTE: These type checking functions intentionally don't use `instanceof`
  4152. // because it is fragile and can be easily faked with `Object.create()`.
  4153. function isArray(arg) {
  4154. if (Array.isArray) {
  4155. return Array.isArray(arg);
  4156. }
  4157. return objectToString(arg) === '[object Array]';
  4158. }
  4159. exports.isArray = isArray;
  4160. function isBoolean(arg) {
  4161. return typeof arg === 'boolean';
  4162. }
  4163. exports.isBoolean = isBoolean;
  4164. function isNull(arg) {
  4165. return arg === null;
  4166. }
  4167. exports.isNull = isNull;
  4168. function isNullOrUndefined(arg) {
  4169. return arg == null;
  4170. }
  4171. exports.isNullOrUndefined = isNullOrUndefined;
  4172. function isNumber(arg) {
  4173. return typeof arg === 'number';
  4174. }
  4175. exports.isNumber = isNumber;
  4176. function isString(arg) {
  4177. return typeof arg === 'string';
  4178. }
  4179. exports.isString = isString;
  4180. function isSymbol(arg) {
  4181. return typeof arg === 'symbol';
  4182. }
  4183. exports.isSymbol = isSymbol;
  4184. function isUndefined(arg) {
  4185. return arg === void 0;
  4186. }
  4187. exports.isUndefined = isUndefined;
  4188. function isRegExp(re) {
  4189. return objectToString(re) === '[object RegExp]';
  4190. }
  4191. exports.isRegExp = isRegExp;
  4192. function isObject(arg) {
  4193. return typeof arg === 'object' && arg !== null;
  4194. }
  4195. exports.isObject = isObject;
  4196. function isDate(d) {
  4197. return objectToString(d) === '[object Date]';
  4198. }
  4199. exports.isDate = isDate;
  4200. function isError(e) {
  4201. return (objectToString(e) === '[object Error]' || e instanceof Error);
  4202. }
  4203. exports.isError = isError;
  4204. function isFunction(arg) {
  4205. return typeof arg === 'function';
  4206. }
  4207. exports.isFunction = isFunction;
  4208. function isPrimitive(arg) {
  4209. return arg === null ||
  4210. typeof arg === 'boolean' ||
  4211. typeof arg === 'number' ||
  4212. typeof arg === 'string' ||
  4213. typeof arg === 'symbol' || // ES6 symbol
  4214. typeof arg === 'undefined';
  4215. }
  4216. exports.isPrimitive = isPrimitive;
  4217. exports.isBuffer = Buffer.isBuffer;
  4218. function objectToString(o) {
  4219. return Object.prototype.toString.call(o);
  4220. }
  4221. }).call(this,{"isBuffer":require("../../insert-module-globals/node_modules/is-buffer/index.js")})
  4222. },{"../../insert-module-globals/node_modules/is-buffer/index.js":30}],11:[function(require,module,exports){
  4223. // Copyright Joyent, Inc. and other Node contributors.
  4224. //
  4225. // Permission is hereby granted, free of charge, to any person obtaining a
  4226. // copy of this software and associated documentation files (the
  4227. // "Software"), to deal in the Software without restriction, including
  4228. // without limitation the rights to use, copy, modify, merge, publish,
  4229. // distribute, sublicense, and/or sell copies of the Software, and to permit
  4230. // persons to whom the Software is furnished to do so, subject to the
  4231. // following conditions:
  4232. //
  4233. // The above copyright notice and this permission notice shall be included
  4234. // in all copies or substantial portions of the Software.
  4235. //
  4236. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  4237. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  4238. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  4239. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  4240. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  4241. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  4242. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  4243. var objectCreate = Object.create || objectCreatePolyfill
  4244. var objectKeys = Object.keys || objectKeysPolyfill
  4245. var bind = Function.prototype.bind || functionBindPolyfill
  4246. function EventEmitter() {
  4247. if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
  4248. this._events = objectCreate(null);
  4249. this._eventsCount = 0;
  4250. }
  4251. this._maxListeners = this._maxListeners || undefined;
  4252. }
  4253. module.exports = EventEmitter;
  4254. // Backwards-compat with node 0.10.x
  4255. EventEmitter.EventEmitter = EventEmitter;
  4256. EventEmitter.prototype._events = undefined;
  4257. EventEmitter.prototype._maxListeners = undefined;
  4258. // By default EventEmitters will print a warning if more than 10 listeners are
  4259. // added to it. This is a useful default which helps finding memory leaks.
  4260. var defaultMaxListeners = 10;
  4261. var hasDefineProperty;
  4262. try {
  4263. var o = {};
  4264. if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
  4265. hasDefineProperty = o.x === 0;
  4266. } catch (err) { hasDefineProperty = false }
  4267. if (hasDefineProperty) {
  4268. Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
  4269. enumerable: true,
  4270. get: function() {
  4271. return defaultMaxListeners;
  4272. },
  4273. set: function(arg) {
  4274. // check whether the input is a positive number (whose value is zero or
  4275. // greater and not a NaN).
  4276. if (typeof arg !== 'number' || arg < 0 || arg !== arg)
  4277. throw new TypeError('"defaultMaxListeners" must be a positive number');
  4278. defaultMaxListeners = arg;
  4279. }
  4280. });
  4281. } else {
  4282. EventEmitter.defaultMaxListeners = defaultMaxListeners;
  4283. }
  4284. // Obviously not all Emitters should be limited to 10. This function allows
  4285. // that to be increased. Set to zero for unlimited.
  4286. EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
  4287. if (typeof n !== 'number' || n < 0 || isNaN(n))
  4288. throw new TypeError('"n" argument must be a positive number');
  4289. this._maxListeners = n;
  4290. return this;
  4291. };
  4292. function $getMaxListeners(that) {
  4293. if (that._maxListeners === undefined)
  4294. return EventEmitter.defaultMaxListeners;
  4295. return that._maxListeners;
  4296. }
  4297. EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
  4298. return $getMaxListeners(this);
  4299. };
  4300. // These standalone emit* functions are used to optimize calling of event
  4301. // handlers for fast cases because emit() itself often has a variable number of
  4302. // arguments and can be deoptimized because of that. These functions always have
  4303. // the same number of arguments and thus do not get deoptimized, so the code
  4304. // inside them can execute faster.
  4305. function emitNone(handler, isFn, self) {
  4306. if (isFn)
  4307. handler.call(self);
  4308. else {
  4309. var len = handler.length;
  4310. var listeners = arrayClone(handler, len);
  4311. for (var i = 0; i < len; ++i)
  4312. listeners[i].call(self);
  4313. }
  4314. }
  4315. function emitOne(handler, isFn, self, arg1) {
  4316. if (isFn)
  4317. handler.call(self, arg1);
  4318. else {
  4319. var len = handler.length;
  4320. var listeners = arrayClone(handler, len);
  4321. for (var i = 0; i < len; ++i)
  4322. listeners[i].call(self, arg1);
  4323. }
  4324. }
  4325. function emitTwo(handler, isFn, self, arg1, arg2) {
  4326. if (isFn)
  4327. handler.call(self, arg1, arg2);
  4328. else {
  4329. var len = handler.length;
  4330. var listeners = arrayClone(handler, len);
  4331. for (var i = 0; i < len; ++i)
  4332. listeners[i].call(self, arg1, arg2);
  4333. }
  4334. }
  4335. function emitThree(handler, isFn, self, arg1, arg2, arg3) {
  4336. if (isFn)
  4337. handler.call(self, arg1, arg2, arg3);
  4338. else {
  4339. var len = handler.length;
  4340. var listeners = arrayClone(handler, len);
  4341. for (var i = 0; i < len; ++i)
  4342. listeners[i].call(self, arg1, arg2, arg3);
  4343. }
  4344. }
  4345. function emitMany(handler, isFn, self, args) {
  4346. if (isFn)
  4347. handler.apply(self, args);
  4348. else {
  4349. var len = handler.length;
  4350. var listeners = arrayClone(handler, len);
  4351. for (var i = 0; i < len; ++i)
  4352. listeners[i].apply(self, args);
  4353. }
  4354. }
  4355. EventEmitter.prototype.emit = function emit(type) {
  4356. var er, handler, len, args, i, events;
  4357. var doError = (type === 'error');
  4358. events = this._events;
  4359. if (events)
  4360. doError = (doError && events.error == null);
  4361. else if (!doError)
  4362. return false;
  4363. // If there is no 'error' event listener then throw.
  4364. if (doError) {
  4365. if (arguments.length > 1)
  4366. er = arguments[1];
  4367. if (er instanceof Error) {
  4368. throw er; // Unhandled 'error' event
  4369. } else {
  4370. // At least give some kind of context to the user
  4371. var err = new Error('Unhandled "error" event. (' + er + ')');
  4372. err.context = er;
  4373. throw err;
  4374. }
  4375. return false;
  4376. }
  4377. handler = events[type];
  4378. if (!handler)
  4379. return false;
  4380. var isFn = typeof handler === 'function';
  4381. len = arguments.length;
  4382. switch (len) {
  4383. // fast cases
  4384. case 1:
  4385. emitNone(handler, isFn, this);
  4386. break;
  4387. case 2:
  4388. emitOne(handler, isFn, this, arguments[1]);
  4389. break;
  4390. case 3:
  4391. emitTwo(handler, isFn, this, arguments[1], arguments[2]);
  4392. break;
  4393. case 4:
  4394. emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
  4395. break;
  4396. // slower
  4397. default:
  4398. args = new Array(len - 1);
  4399. for (i = 1; i < len; i++)
  4400. args[i - 1] = arguments[i];
  4401. emitMany(handler, isFn, this, args);
  4402. }
  4403. return true;
  4404. };
  4405. function _addListener(target, type, listener, prepend) {
  4406. var m;
  4407. var events;
  4408. var existing;
  4409. if (typeof listener !== 'function')
  4410. throw new TypeError('"listener" argument must be a function');
  4411. events = target._events;
  4412. if (!events) {
  4413. events = target._events = objectCreate(null);
  4414. target._eventsCount = 0;
  4415. } else {
  4416. // To avoid recursion in the case that type === "newListener"! Before
  4417. // adding it to the listeners, first emit "newListener".
  4418. if (events.newListener) {
  4419. target.emit('newListener', type,
  4420. listener.listener ? listener.listener : listener);
  4421. // Re-assign `events` because a newListener handler could have caused the
  4422. // this._events to be assigned to a new object
  4423. events = target._events;
  4424. }
  4425. existing = events[type];
  4426. }
  4427. if (!existing) {
  4428. // Optimize the case of one listener. Don't need the extra array object.
  4429. existing = events[type] = listener;
  4430. ++target._eventsCount;
  4431. } else {
  4432. if (typeof existing === 'function') {
  4433. // Adding the second element, need to change to array.
  4434. existing = events[type] =
  4435. prepend ? [listener, existing] : [existing, listener];
  4436. } else {
  4437. // If we've already got an array, just append.
  4438. if (prepend) {
  4439. existing.unshift(listener);
  4440. } else {
  4441. existing.push(listener);
  4442. }
  4443. }
  4444. // Check for listener leak
  4445. if (!existing.warned) {
  4446. m = $getMaxListeners(target);
  4447. if (m && m > 0 && existing.length > m) {
  4448. existing.warned = true;
  4449. var w = new Error('Possible EventEmitter memory leak detected. ' +
  4450. existing.length + ' "' + String(type) + '" listeners ' +
  4451. 'added. Use emitter.setMaxListeners() to ' +
  4452. 'increase limit.');
  4453. w.name = 'MaxListenersExceededWarning';
  4454. w.emitter = target;
  4455. w.type = type;
  4456. w.count = existing.length;
  4457. if (typeof console === 'object' && console.warn) {
  4458. console.warn('%s: %s', w.name, w.message);
  4459. }
  4460. }
  4461. }
  4462. }
  4463. return target;
  4464. }
  4465. EventEmitter.prototype.addListener = function addListener(type, listener) {
  4466. return _addListener(this, type, listener, false);
  4467. };
  4468. EventEmitter.prototype.on = EventEmitter.prototype.addListener;
  4469. EventEmitter.prototype.prependListener =
  4470. function prependListener(type, listener) {
  4471. return _addListener(this, type, listener, true);
  4472. };
  4473. function onceWrapper() {
  4474. if (!this.fired) {
  4475. this.target.removeListener(this.type, this.wrapFn);
  4476. this.fired = true;
  4477. switch (arguments.length) {
  4478. case 0:
  4479. return this.listener.call(this.target);
  4480. case 1:
  4481. return this.listener.call(this.target, arguments[0]);
  4482. case 2:
  4483. return this.listener.call(this.target, arguments[0], arguments[1]);
  4484. case 3:
  4485. return this.listener.call(this.target, arguments[0], arguments[1],
  4486. arguments[2]);
  4487. default:
  4488. var args = new Array(arguments.length);
  4489. for (var i = 0; i < args.length; ++i)
  4490. args[i] = arguments[i];
  4491. this.listener.apply(this.target, args);
  4492. }
  4493. }
  4494. }
  4495. function _onceWrap(target, type, listener) {
  4496. var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
  4497. var wrapped = bind.call(onceWrapper, state);
  4498. wrapped.listener = listener;
  4499. state.wrapFn = wrapped;
  4500. return wrapped;
  4501. }
  4502. EventEmitter.prototype.once = function once(type, listener) {
  4503. if (typeof listener !== 'function')
  4504. throw new TypeError('"listener" argument must be a function');
  4505. this.on(type, _onceWrap(this, type, listener));
  4506. return this;
  4507. };
  4508. EventEmitter.prototype.prependOnceListener =
  4509. function prependOnceListener(type, listener) {
  4510. if (typeof listener !== 'function')
  4511. throw new TypeError('"listener" argument must be a function');
  4512. this.prependListener(type, _onceWrap(this, type, listener));
  4513. return this;
  4514. };
  4515. // Emits a 'removeListener' event if and only if the listener was removed.
  4516. EventEmitter.prototype.removeListener =
  4517. function removeListener(type, listener) {
  4518. var list, events, position, i, originalListener;
  4519. if (typeof listener !== 'function')
  4520. throw new TypeError('"listener" argument must be a function');
  4521. events = this._events;
  4522. if (!events)
  4523. return this;
  4524. list = events[type];
  4525. if (!list)
  4526. return this;
  4527. if (list === listener || list.listener === listener) {
  4528. if (--this._eventsCount === 0)
  4529. this._events = objectCreate(null);
  4530. else {
  4531. delete events[type];
  4532. if (events.removeListener)
  4533. this.emit('removeListener', type, list.listener || listener);
  4534. }
  4535. } else if (typeof list !== 'function') {
  4536. position = -1;
  4537. for (i = list.length - 1; i >= 0; i--) {
  4538. if (list[i] === listener || list[i].listener === listener) {
  4539. originalListener = list[i].listener;
  4540. position = i;
  4541. break;
  4542. }
  4543. }
  4544. if (position < 0)
  4545. return this;
  4546. if (position === 0)
  4547. list.shift();
  4548. else
  4549. spliceOne(list, position);
  4550. if (list.length === 1)
  4551. events[type] = list[0];
  4552. if (events.removeListener)
  4553. this.emit('removeListener', type, originalListener || listener);
  4554. }
  4555. return this;
  4556. };
  4557. EventEmitter.prototype.removeAllListeners =
  4558. function removeAllListeners(type) {
  4559. var listeners, events, i;
  4560. events = this._events;
  4561. if (!events)
  4562. return this;
  4563. // not listening for removeListener, no need to emit
  4564. if (!events.removeListener) {
  4565. if (arguments.length === 0) {
  4566. this._events = objectCreate(null);
  4567. this._eventsCount = 0;
  4568. } else if (events[type]) {
  4569. if (--this._eventsCount === 0)
  4570. this._events = objectCreate(null);
  4571. else
  4572. delete events[type];
  4573. }
  4574. return this;
  4575. }
  4576. // emit removeListener for all listeners on all events
  4577. if (arguments.length === 0) {
  4578. var keys = objectKeys(events);
  4579. var key;
  4580. for (i = 0; i < keys.length; ++i) {
  4581. key = keys[i];
  4582. if (key === 'removeListener') continue;
  4583. this.removeAllListeners(key);
  4584. }
  4585. this.removeAllListeners('removeListener');
  4586. this._events = objectCreate(null);
  4587. this._eventsCount = 0;
  4588. return this;
  4589. }
  4590. listeners = events[type];
  4591. if (typeof listeners === 'function') {
  4592. this.removeListener(type, listeners);
  4593. } else if (listeners) {
  4594. // LIFO order
  4595. for (i = listeners.length - 1; i >= 0; i--) {
  4596. this.removeListener(type, listeners[i]);
  4597. }
  4598. }
  4599. return this;
  4600. };
  4601. function _listeners(target, type, unwrap) {
  4602. var events = target._events;
  4603. if (!events)
  4604. return [];
  4605. var evlistener = events[type];
  4606. if (!evlistener)
  4607. return [];
  4608. if (typeof evlistener === 'function')
  4609. return unwrap ? [evlistener.listener || evlistener] : [evlistener];
  4610. return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
  4611. }
  4612. EventEmitter.prototype.listeners = function listeners(type) {
  4613. return _listeners(this, type, true);
  4614. };
  4615. EventEmitter.prototype.rawListeners = function rawListeners(type) {
  4616. return _listeners(this, type, false);
  4617. };
  4618. EventEmitter.listenerCount = function(emitter, type) {
  4619. if (typeof emitter.listenerCount === 'function') {
  4620. return emitter.listenerCount(type);
  4621. } else {
  4622. return listenerCount.call(emitter, type);
  4623. }
  4624. };
  4625. EventEmitter.prototype.listenerCount = listenerCount;
  4626. function listenerCount(type) {
  4627. var events = this._events;
  4628. if (events) {
  4629. var evlistener = events[type];
  4630. if (typeof evlistener === 'function') {
  4631. return 1;
  4632. } else if (evlistener) {
  4633. return evlistener.length;
  4634. }
  4635. }
  4636. return 0;
  4637. }
  4638. EventEmitter.prototype.eventNames = function eventNames() {
  4639. return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
  4640. };
  4641. // About 1.5x faster than the two-arg version of Array#splice().
  4642. function spliceOne(list, index) {
  4643. for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
  4644. list[i] = list[k];
  4645. list.pop();
  4646. }
  4647. function arrayClone(arr, n) {
  4648. var copy = new Array(n);
  4649. for (var i = 0; i < n; ++i)
  4650. copy[i] = arr[i];
  4651. return copy;
  4652. }
  4653. function unwrapListeners(arr) {
  4654. var ret = new Array(arr.length);
  4655. for (var i = 0; i < ret.length; ++i) {
  4656. ret[i] = arr[i].listener || arr[i];
  4657. }
  4658. return ret;
  4659. }
  4660. function objectCreatePolyfill(proto) {
  4661. var F = function() {};
  4662. F.prototype = proto;
  4663. return new F;
  4664. }
  4665. function objectKeysPolyfill(obj) {
  4666. var keys = [];
  4667. for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
  4668. keys.push(k);
  4669. }
  4670. return k;
  4671. }
  4672. function functionBindPolyfill(context) {
  4673. var fn = this;
  4674. return function () {
  4675. return fn.apply(context, arguments);
  4676. };
  4677. }
  4678. },{}],12:[function(require,module,exports){
  4679. exports.Scalar = require("./src/scalar");
  4680. exports.PolField = require("./src/polfield.js");
  4681. exports.F1Field = require("./src/f1field");
  4682. exports.F2Field = require("./src/f2field");
  4683. exports.F3Field = require("./src/f3field");
  4684. exports.ZqField = exports.F1Field;
  4685. exports.EC = require("./src/ec");
  4686. exports.bn128 = require("./src/bn128.js");
  4687. exports.utils = require("./src/utils");
  4688. },{"./src/bn128.js":13,"./src/ec":14,"./src/f1field":15,"./src/f2field":18,"./src/f3field":19,"./src/polfield.js":21,"./src/scalar":22,"./src/utils":25}],13:[function(require,module,exports){
  4689. /*
  4690. Copyright 2018 0kims association.
  4691. This file is part of snarkjs.
  4692. snarkjs is a free software: you can redistribute it and/or
  4693. modify it under the terms of the GNU General Public License as published by the
  4694. Free Software Foundation, either version 3 of the License, or (at your option)
  4695. any later version.
  4696. snarkjs is distributed in the hope that it will be useful,
  4697. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  4698. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  4699. more details.
  4700. You should have received a copy of the GNU General Public License along with
  4701. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  4702. */
  4703. const Scalar = require("./scalar");
  4704. const F1Field = require("./f1field");
  4705. const F2Field = require("./f2field");
  4706. const F3Field = require("./f3field");
  4707. const EC = require("./ec.js");
  4708. class BN128 {
  4709. constructor() {
  4710. this.q = Scalar.fromString("21888242871839275222246405745257275088696311157297823662689037894645226208583");
  4711. this.r = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
  4712. this.F1 = new F1Field(this.q);
  4713. this.nonResidueF2 = this.F1.e("21888242871839275222246405745257275088696311157297823662689037894645226208582");
  4714. this.F2 = new F2Field(this.F1, this.nonResidueF2);
  4715. this.g1 = [ this.F1.e(1), this.F1.e(2), this.F1.e(1)];
  4716. this.g2 = [
  4717. [
  4718. this.F1.e("10857046999023057135944570762232829481370756359578518086990519993285655852781"),
  4719. this.F1.e("11559732032986387107991004021392285783925812861821192530917403151452391805634")
  4720. ],
  4721. [
  4722. this.F1.e("8495653923123431417604973247489272438418190587263600148770280649306958101930"),
  4723. this.F1.e("4082367875863433681332203403145435568316851327593401208105741076214120093531")
  4724. ],
  4725. [
  4726. this.F1.e("1"),
  4727. this.F1.e("0")
  4728. ]
  4729. ];
  4730. this.G1 = new EC(this.F1, this.g1);
  4731. this.G2 = new EC(this.F2, this.g2);
  4732. this.nonResidueF6 = [ this.F1.e("9"), this.F1.e("1") ];
  4733. this.F6 = new F3Field(this.F2, this.nonResidueF6);
  4734. this.F12 = new F2Field(this.F6, this.nonResidueF6);
  4735. this.Fr = new F1Field(this.r);
  4736. const self = this;
  4737. this.F12._mulByNonResidue = function(a) {
  4738. return [self.F2.mul(this.nonResidue, a[2]), a[0], a[1]];
  4739. };
  4740. this._preparePairing();
  4741. }
  4742. _preparePairing() {
  4743. this.loopCount = Scalar.fromString("29793968203157093288");// CONSTANT
  4744. // Set loopCountNeg
  4745. if (Scalar.isNegative(this.loopCount)) {
  4746. this.loopCount = this.loopCount.neg();
  4747. this.loopCountNeg = true;
  4748. } else {
  4749. this.loopCountNeg = false;
  4750. }
  4751. // Set loop_count_bits
  4752. let lc = this.loopCount;
  4753. this.loop_count_bits = []; // Constant
  4754. while (!Scalar.isZero(lc)) {
  4755. this.loop_count_bits.push( Scalar.isOdd(lc) );
  4756. lc = Scalar.shiftRight(lc, 1);
  4757. }
  4758. this.two_inv = this.F1.inv(this.F1.e(2));
  4759. this.coef_b = this.F1.e(3);
  4760. this.twist = [this.F1.e(9) , this.F1.e(1)];
  4761. this.twist_coeff_b = this.F2.mulScalar( this.F2.inv(this.twist), this.coef_b );
  4762. this.frobenius_coeffs_c1_1 = this.F1.e("21888242871839275222246405745257275088696311157297823662689037894645226208582");
  4763. this.twist_mul_by_q_X =
  4764. [
  4765. this.F1.e("21575463638280843010398324269430826099269044274347216827212613867836435027261"),
  4766. this.F1.e("10307601595873709700152284273816112264069230130616436755625194854815875713954")
  4767. ];
  4768. this.twist_mul_by_q_Y =
  4769. [
  4770. this.F1.e("2821565182194536844548159561693502659359617185244120367078079554186484126554"),
  4771. this.F1.e("3505843767911556378687030309984248845540243509899259641013678093033130930403")
  4772. ];
  4773. this.final_exponent = Scalar.fromString("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480");
  4774. }
  4775. pairing(p1, p2) {
  4776. const pre1 = this.precomputeG1(p1);
  4777. const pre2 = this.precomputeG2(p2);
  4778. const r1 = this.millerLoop(pre1, pre2);
  4779. const res = this.finalExponentiation(r1);
  4780. return res;
  4781. }
  4782. precomputeG1(p) {
  4783. const Pcopy = this.G1.affine(p);
  4784. const res = {};
  4785. res.PX = Pcopy[0];
  4786. res.PY = Pcopy[1];
  4787. return res;
  4788. }
  4789. precomputeG2(p) {
  4790. const Qcopy = this.G2.affine(p);
  4791. const res = {
  4792. QX: Qcopy[0],
  4793. QY: Qcopy[1],
  4794. coeffs: []
  4795. };
  4796. const R = {
  4797. X: Qcopy[0],
  4798. Y: Qcopy[1],
  4799. Z: this.F2.one
  4800. };
  4801. let c;
  4802. for (let i = this.loop_count_bits.length-2; i >= 0; --i)
  4803. {
  4804. const bit = this.loop_count_bits[i];
  4805. c = this._doubleStep(R);
  4806. res.coeffs.push(c);
  4807. if (bit)
  4808. {
  4809. c = this._addStep(Qcopy, R);
  4810. res.coeffs.push(c);
  4811. }
  4812. }
  4813. const Q1 = this.G2.affine(this._g2MulByQ(Qcopy));
  4814. if (!this.F2.eq(Q1[2], this.F2.one))
  4815. {
  4816. throw new Error("Expected values are not equal");
  4817. }
  4818. const Q2 = this.G2.affine(this._g2MulByQ(Q1));
  4819. if (!this.F2.eq(Q2[2], this.F2.one))
  4820. {
  4821. throw new Error("Expected values are not equal");
  4822. }
  4823. if (this.loopCountNeg)
  4824. {
  4825. R.Y = this.F2.neg(R.Y);
  4826. }
  4827. Q2[1] = this.F2.neg(Q2[1]);
  4828. c = this._addStep(Q1, R);
  4829. res.coeffs.push(c);
  4830. c = this._addStep(Q2, R);
  4831. res.coeffs.push(c);
  4832. return res;
  4833. }
  4834. millerLoop(pre1, pre2) {
  4835. let f = this.F12.one;
  4836. let idx = 0;
  4837. let c;
  4838. for (let i = this.loop_count_bits.length-2; i >= 0; --i)
  4839. {
  4840. const bit = this.loop_count_bits[i];
  4841. /* code below gets executed for all bits (EXCEPT the MSB itself) of
  4842. alt_bn128_param_p (skipping leading zeros) in MSB to LSB
  4843. order */
  4844. c = pre2.coeffs[idx++];
  4845. f = this.F12.square(f);
  4846. f = this._mul_by_024(
  4847. f,
  4848. c.ell_0,
  4849. this.F2.mulScalar(c.ell_VW , pre1.PY),
  4850. this.F2.mulScalar(c.ell_VV , pre1.PX));
  4851. if (bit)
  4852. {
  4853. c = pre2.coeffs[idx++];
  4854. f = this._mul_by_024(
  4855. f,
  4856. c.ell_0,
  4857. this.F2.mulScalar(c.ell_VW, pre1.PY),
  4858. this.F2.mulScalar(c.ell_VV, pre1.PX));
  4859. }
  4860. }
  4861. if (this.loopCountNeg)
  4862. {
  4863. f = this.F12.inverse(f);
  4864. }
  4865. c = pre2.coeffs[idx++];
  4866. f = this._mul_by_024(
  4867. f,
  4868. c.ell_0,
  4869. this.F2.mulScalar(c.ell_VW, pre1.PY),
  4870. this.F2.mulScalar(c.ell_VV, pre1.PX));
  4871. c = pre2.coeffs[idx++];
  4872. f = this._mul_by_024(
  4873. f,
  4874. c.ell_0,
  4875. this.F2.mulScalar(c.ell_VW, pre1.PY),
  4876. this.F2.mulScalar(c.ell_VV, pre1.PX));
  4877. return f;
  4878. }
  4879. finalExponentiation(elt) {
  4880. // TODO: There is an optimization in FF
  4881. const res = this.F12.exp(elt,this.final_exponent);
  4882. return res;
  4883. }
  4884. _doubleStep(current) {
  4885. const X = current.X;
  4886. const Y = current.Y;
  4887. const Z = current.Z;
  4888. const A = this.F2.mulScalar(this.F2.mul(X,Y), this.two_inv); // A = X1 * Y1 / 2
  4889. const B = this.F2.square(Y); // B = Y1^2
  4890. const C = this.F2.square(Z); // C = Z1^2
  4891. const D = this.F2.add(C, this.F2.add(C,C)); // D = 3 * C
  4892. const E = this.F2.mul(this.twist_coeff_b, D); // E = twist_b * D
  4893. const F = this.F2.add(E, this.F2.add(E,E)); // F = 3 * E
  4894. const G =
  4895. this.F2.mulScalar(
  4896. this.F2.add( B , F ),
  4897. this.two_inv); // G = (B+F)/2
  4898. const H =
  4899. this.F2.sub(
  4900. this.F2.square( this.F2.add(Y,Z) ),
  4901. this.F2.add( B , C)); // H = (Y1+Z1)^2-(B+C)
  4902. const I = this.F2.sub(E, B); // I = E-B
  4903. const J = this.F2.square(X); // J = X1^2
  4904. const E_squared = this.F2.square(E); // E_squared = E^2
  4905. current.X = this.F2.mul( A, this.F2.sub(B,F) ); // X3 = A * (B-F)
  4906. current.Y =
  4907. this.F2.sub(
  4908. this.F2.sub( this.F2.square(G) , E_squared ),
  4909. this.F2.add( E_squared , E_squared )); // Y3 = G^2 - 3*E^2
  4910. current.Z = this.F2.mul( B, H ); // Z3 = B * H
  4911. const c = {
  4912. ell_0 : this.F2.mul( I, this.twist), // ell_0 = xi * I
  4913. ell_VW: this.F2.neg( H ), // ell_VW = - H (later: * yP)
  4914. ell_VV: this.F2.add( J , this.F2.add(J,J) ) // ell_VV = 3*J (later: * xP)
  4915. };
  4916. return c;
  4917. }
  4918. _addStep(base, current) {
  4919. const X1 = current.X;
  4920. const Y1 = current.Y;
  4921. const Z1 = current.Z;
  4922. const x2 = base[0];
  4923. const y2 = base[1];
  4924. const D = this.F2.sub( X1, this.F2.mul(x2,Z1) ); // D = X1 - X2*Z1
  4925. // console.log("Y: "+ A[0].affine(this.q).toString(16));
  4926. const E = this.F2.sub( Y1, this.F2.mul(y2,Z1) ); // E = Y1 - Y2*Z1
  4927. const F = this.F2.square(D); // F = D^2
  4928. const G = this.F2.square(E); // G = E^2
  4929. const H = this.F2.mul(D,F); // H = D*F
  4930. const I = this.F2.mul(X1,F); // I = X1 * F
  4931. const J =
  4932. this.F2.sub(
  4933. this.F2.add( H, this.F2.mul(Z1,G) ),
  4934. this.F2.add( I, I )); // J = H + Z1*G - (I+I)
  4935. current.X = this.F2.mul( D , J ); // X3 = D*J
  4936. current.Y =
  4937. this.F2.sub(
  4938. this.F2.mul( E , this.F2.sub(I,J) ),
  4939. this.F2.mul( H , Y1)); // Y3 = E*(I-J)-(H*Y1)
  4940. current.Z = this.F2.mul(Z1,H);
  4941. const c = {
  4942. ell_0 :
  4943. this.F2.mul(
  4944. this.twist,
  4945. this.F2.sub(
  4946. this.F2.mul(E , x2),
  4947. this.F2.mul(D , y2))), // ell_0 = xi * (E * X2 - D * Y2)
  4948. ell_VV : this.F2.neg(E), // ell_VV = - E (later: * xP)
  4949. ell_VW : D // ell_VW = D (later: * yP )
  4950. };
  4951. return c;
  4952. }
  4953. _mul_by_024(a, ell_0, ell_VW, ell_VV) {
  4954. // Old implementation
  4955. /*
  4956. const b = [
  4957. [ell_0, this.F2.zero, ell_VV],
  4958. [this.F2.zero, ell_VW, this.F2.zero]
  4959. ];
  4960. return this.F12.mul(a,b);
  4961. */
  4962. // This is a new implementation,
  4963. // But it does not look worthy
  4964. // at least in javascript.
  4965. let z0 = a[0][0];
  4966. let z1 = a[0][1];
  4967. let z2 = a[0][2];
  4968. let z3 = a[1][0];
  4969. let z4 = a[1][1];
  4970. let z5 = a[1][2];
  4971. const x0 = ell_0;
  4972. const x2 = ell_VV;
  4973. const x4 = ell_VW;
  4974. const D0 = this.F2.mul(z0, x0);
  4975. const D2 = this.F2.mul(z2, x2);
  4976. const D4 = this.F2.mul(z4, x4);
  4977. const t2 = this.F2.add(z0, z4);
  4978. let t1 = this.F2.add(z0, z2);
  4979. const s0 = this.F2.add(this.F2.add(z1,z3),z5);
  4980. // For z.a_.a_ = z0.
  4981. let S1 = this.F2.mul(z1, x2);
  4982. let T3 = this.F2.add(S1, D4);
  4983. let T4 = this.F2.add( this.F2.mul(this.nonResidueF6, T3),D0);
  4984. z0 = T4;
  4985. // For z.a_.b_ = z1
  4986. T3 = this.F2.mul(z5, x4);
  4987. S1 = this.F2.add(S1, T3);
  4988. T3 = this.F2.add(T3, D2);
  4989. T4 = this.F2.mul(this.nonResidueF6, T3);
  4990. T3 = this.F2.mul(z1, x0);
  4991. S1 = this.F2.add(S1, T3);
  4992. T4 = this.F2.add(T4, T3);
  4993. z1 = T4;
  4994. // For z.a_.c_ = z2
  4995. let t0 = this.F2.add(x0, x2);
  4996. T3 = this.F2.sub(
  4997. this.F2.mul(t1, t0),
  4998. this.F2.add(D0, D2));
  4999. T4 = this.F2.mul(z3, x4);
  5000. S1 = this.F2.add(S1, T4);
  5001. // For z.b_.a_ = z3 (z3 needs z2)
  5002. t0 = this.F2.add(z2, z4);
  5003. z2 = this.F2.add(T3, T4);
  5004. t1 = this.F2.add(x2, x4);
  5005. T3 = this.F2.sub(
  5006. this.F2.mul(t0,t1),
  5007. this.F2.add(D2, D4));
  5008. T4 = this.F2.mul(this.nonResidueF6, T3);
  5009. T3 = this.F2.mul(z3, x0);
  5010. S1 = this.F2.add(S1, T3);
  5011. T4 = this.F2.add(T4, T3);
  5012. z3 = T4;
  5013. // For z.b_.b_ = z4
  5014. T3 = this.F2.mul(z5, x2);
  5015. S1 = this.F2.add(S1, T3);
  5016. T4 = this.F2.mul(this.nonResidueF6, T3);
  5017. t0 = this.F2.add(x0, x4);
  5018. T3 = this.F2.sub(
  5019. this.F2.mul(t2,t0),
  5020. this.F2.add(D0, D4));
  5021. T4 = this.F2.add(T4, T3);
  5022. z4 = T4;
  5023. // For z.b_.c_ = z5.
  5024. t0 = this.F2.add(this.F2.add(x0, x2), x4);
  5025. T3 = this.F2.sub(this.F2.mul(s0, t0), S1);
  5026. z5 = T3;
  5027. return [
  5028. [z0, z1, z2],
  5029. [z3, z4, z5]
  5030. ];
  5031. }
  5032. _g2MulByQ(p) {
  5033. const fmx = [p[0][0], this.F1.mul(p[0][1], this.frobenius_coeffs_c1_1 )];
  5034. const fmy = [p[1][0], this.F1.mul(p[1][1], this.frobenius_coeffs_c1_1 )];
  5035. const fmz = [p[2][0], this.F1.mul(p[2][1], this.frobenius_coeffs_c1_1 )];
  5036. return [
  5037. this.F2.mul(this.twist_mul_by_q_X , fmx),
  5038. this.F2.mul(this.twist_mul_by_q_Y , fmy),
  5039. fmz
  5040. ];
  5041. }
  5042. }
  5043. module.exports = new BN128();
  5044. },{"./ec.js":14,"./f1field":15,"./f2field":18,"./f3field":19,"./scalar":22}],14:[function(require,module,exports){
  5045. /*
  5046. Copyright 2018 0kims association.
  5047. This file is part of snarkjs.
  5048. snarkjs is a free software: you can redistribute it and/or
  5049. modify it under the terms of the GNU General Public License as published by the
  5050. Free Software Foundation, either version 3 of the License, or (at your option)
  5051. any later version.
  5052. snarkjs is distributed in the hope that it will be useful,
  5053. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  5054. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  5055. more details.
  5056. You should have received a copy of the GNU General Public License along with
  5057. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  5058. */
  5059. const fUtils = require("./futils.js");
  5060. class EC {
  5061. constructor(F, g) {
  5062. this.F = F;
  5063. this.g = g;
  5064. if (this.g.length == 2) this.g[2] = this.F.one;
  5065. this.zero = [this.F.zero, this.F.one, this.F.zero];
  5066. }
  5067. add(p1, p2) {
  5068. const F = this.F;
  5069. if (this.eq(p1, this.zero)) return p2;
  5070. if (this.eq(p2, this.zero)) return p1;
  5071. const res = new Array(3);
  5072. const Z1Z1 = F.square( p1[2] );
  5073. const Z2Z2 = F.square( p2[2] );
  5074. const U1 = F.mul( p1[0] , Z2Z2 ); // U1 = X1 * Z2Z2
  5075. const U2 = F.mul( p2[0] , Z1Z1 ); // U2 = X2 * Z1Z1
  5076. const Z1_cubed = F.mul( p1[2] , Z1Z1);
  5077. const Z2_cubed = F.mul( p2[2] , Z2Z2);
  5078. const S1 = F.mul( p1[1] , Z2_cubed); // S1 = Y1 * Z2 * Z2Z2
  5079. const S2 = F.mul( p2[1] , Z1_cubed); // S2 = Y2 * Z1 * Z1Z1
  5080. if (F.eq(U1,U2) && F.eq(S1,S2)) {
  5081. return this.double(p1);
  5082. }
  5083. const H = F.sub( U2 , U1 ); // H = U2-U1
  5084. const S2_minus_S1 = F.sub( S2 , S1 );
  5085. const I = F.square( F.add(H,H) ); // I = (2 * H)^2
  5086. const J = F.mul( H , I ); // J = H * I
  5087. const r = F.add( S2_minus_S1 , S2_minus_S1 ); // r = 2 * (S2-S1)
  5088. const V = F.mul( U1 , I ); // V = U1 * I
  5089. res[0] =
  5090. F.sub(
  5091. F.sub( F.square(r) , J ),
  5092. F.add( V , V )); // X3 = r^2 - J - 2 * V
  5093. const S1_J = F.mul( S1 , J );
  5094. res[1] =
  5095. F.sub(
  5096. F.mul( r , F.sub(V,res[0])),
  5097. F.add( S1_J,S1_J )); // Y3 = r * (V-X3)-2 S1 J
  5098. res[2] =
  5099. F.mul(
  5100. H,
  5101. F.sub(
  5102. F.square( F.add(p1[2],p2[2]) ),
  5103. F.add( Z1Z1 , Z2Z2 ))); // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H
  5104. return res;
  5105. }
  5106. neg(p) {
  5107. return [p[0], this.F.neg(p[1]), p[2]];
  5108. }
  5109. sub(a, b) {
  5110. return this.add(a, this.neg(b));
  5111. }
  5112. double(p) {
  5113. const F = this.F;
  5114. const res = new Array(3);
  5115. if (this.eq(p, this.zero)) return p;
  5116. const A = F.square( p[0] ); // A = X1^2
  5117. const B = F.square( p[1] ); // B = Y1^2
  5118. const C = F.square( B ); // C = B^2
  5119. let D =
  5120. F.sub(
  5121. F.square( F.add(p[0] , B )),
  5122. F.add( A , C));
  5123. D = F.add(D,D); // D = 2 * ((X1 + B)^2 - A - C)
  5124. const E = F.add( F.add(A,A), A); // E = 3 * A
  5125. const FF =F.square( E ); // F = E^2
  5126. res[0] = F.sub( FF , F.add(D,D) ); // X3 = F - 2 D
  5127. let eightC = F.add( C , C );
  5128. eightC = F.add( eightC , eightC );
  5129. eightC = F.add( eightC , eightC );
  5130. res[1] =
  5131. F.sub(
  5132. F.mul(
  5133. E,
  5134. F.sub( D, res[0] )),
  5135. eightC); // Y3 = E * (D - X3) - 8 * C
  5136. const Y1Z1 = F.mul( p[1] , p[2] );
  5137. res[2] = F.add( Y1Z1 , Y1Z1 ); // Z3 = 2 * Y1 * Z1
  5138. return res;
  5139. }
  5140. mulScalar(base, e) {
  5141. return fUtils.mulScalar(this, base, e);
  5142. }
  5143. affine(p) {
  5144. const F = this.F;
  5145. if (this.eq(p, this.zero)) {
  5146. return this.zero;
  5147. } else {
  5148. const Z_inv = F.inv(p[2]);
  5149. const Z2_inv = F.square(Z_inv);
  5150. const Z3_inv = F.mul(Z2_inv, Z_inv);
  5151. const res = new Array(3);
  5152. res[0] = F.mul(p[0],Z2_inv);
  5153. res[1] = F.mul(p[1],Z3_inv);
  5154. res[2] = F.one;
  5155. return res;
  5156. }
  5157. }
  5158. multiAffine(arr) {
  5159. const keys = Object.keys(arr);
  5160. const F = this.F;
  5161. const accMul = new Array(keys.length+1);
  5162. accMul[0] = F.one;
  5163. for (let i = 0; i< keys.length; i++) {
  5164. if (F.eq(arr[keys[i]][2], F.zero)) {
  5165. accMul[i+1] = accMul[i];
  5166. } else {
  5167. accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]);
  5168. }
  5169. }
  5170. accMul[keys.length] = F.inv(accMul[keys.length]);
  5171. for (let i = keys.length-1; i>=0; i--) {
  5172. if (F.eq(arr[keys[i]][2], F.zero)) {
  5173. accMul[i] = accMul[i+1];
  5174. arr[keys[i]] = this.zero;
  5175. } else {
  5176. const Z_inv = F.mul(accMul[i], accMul[i+1]);
  5177. accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]);
  5178. const Z2_inv = F.square(Z_inv);
  5179. const Z3_inv = F.mul(Z2_inv, Z_inv);
  5180. arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv);
  5181. arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv);
  5182. arr[keys[i]][2] = F.one;
  5183. }
  5184. }
  5185. }
  5186. eq(p1, p2) {
  5187. const F = this.F;
  5188. if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero);
  5189. if (this.F.eq(p2[2], this.F.zero)) return false;
  5190. const Z1Z1 = F.square( p1[2] );
  5191. const Z2Z2 = F.square( p2[2] );
  5192. const U1 = F.mul( p1[0] , Z2Z2 );
  5193. const U2 = F.mul( p2[0] , Z1Z1 );
  5194. const Z1_cubed = F.mul( p1[2] , Z1Z1);
  5195. const Z2_cubed = F.mul( p2[2] , Z2Z2);
  5196. const S1 = F.mul( p1[1] , Z2_cubed);
  5197. const S2 = F.mul( p2[1] , Z1_cubed);
  5198. return (F.eq(U1,U2) && F.eq(S1,S2));
  5199. }
  5200. toString(p) {
  5201. const cp = this.affine(p);
  5202. return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`;
  5203. }
  5204. }
  5205. module.exports = EC;
  5206. },{"./futils.js":20}],15:[function(require,module,exports){
  5207. const supportsNativeBigInt = typeof BigInt === "function";
  5208. if (supportsNativeBigInt) {
  5209. module.exports = require("./f1field_native");
  5210. } else {
  5211. module.exports = require("./f1field_bigint");
  5212. }
  5213. },{"./f1field_bigint":16,"./f1field_native":17}],16:[function(require,module,exports){
  5214. const bigInt = require("big-integer");
  5215. const assert = require("assert");
  5216. function getRandomByte() {
  5217. if (typeof window !== "undefined") { // Browser
  5218. if (typeof window.crypto !== "undefined") { // Supported
  5219. let array = new Uint8Array(1);
  5220. window.crypto.getRandomValues(array);
  5221. return array[0];
  5222. }
  5223. else { // fallback
  5224. return Math.floor(Math.random() * 256);
  5225. }
  5226. }
  5227. else { // NodeJS
  5228. return module.require("crypto").randomBytes(1)[0];
  5229. }
  5230. }
  5231. module.exports = class ZqField {
  5232. constructor(p) {
  5233. this.one = bigInt.one;
  5234. this.zero = bigInt.zero;
  5235. this.p = bigInt(p);
  5236. this.minusone = this.p.minus(bigInt.one);
  5237. this.two = bigInt(2);
  5238. this.half = this.p.shiftRight(1);
  5239. this.bitLength = this.p.bitLength();
  5240. this.mask = bigInt.one.shiftLeft(this.bitLength).minus(bigInt.one);
  5241. this.n64 = Math.floor((this.bitLength - 1) / 64)+1;
  5242. this.R = bigInt.one.shiftLeft(this.n64*64);
  5243. const e = this.minusone.shiftRight(this.one);
  5244. this.nqr = this.two;
  5245. let r = this.pow(this.nqr, e);
  5246. while (!r.equals(this.minusone)) {
  5247. this.nqr = this.nqr.add(this.one);
  5248. r = this.pow(this.nqr, e);
  5249. }
  5250. this.s = this.zero;
  5251. this.t = this.minusone;
  5252. while (!this.t.isOdd()) {
  5253. this.s = this.s.add(this.one);
  5254. this.t = this.t.shiftRight(this.one);
  5255. }
  5256. this.nqr_to_t = this.pow(this.nqr, this.t);
  5257. }
  5258. e(a,b) {
  5259. const res = bigInt(a,b);
  5260. return this.normalize(res);
  5261. }
  5262. add(a, b) {
  5263. let res = a.add(b);
  5264. if (res.geq(this.p)) {
  5265. res = res.minus(this.p);
  5266. }
  5267. return res;
  5268. }
  5269. sub(a, b) {
  5270. if (a.geq(b)) {
  5271. return a.minus(b);
  5272. } else {
  5273. return this.p.minus(b.minus(a));
  5274. }
  5275. }
  5276. neg(a) {
  5277. if (a.isZero()) return a;
  5278. return this.p.minus(a);
  5279. }
  5280. mul(a, b) {
  5281. return a.times(b).mod(this.p);
  5282. }
  5283. mulScalar(base, s) {
  5284. return base.times(bigInt(s)).mod(this.p);
  5285. }
  5286. square(a) {
  5287. return a.square().mod(this.p);
  5288. }
  5289. eq(a, b) {
  5290. return a.eq(b);
  5291. }
  5292. neq(a, b) {
  5293. return a.neq(b);
  5294. }
  5295. lt(a, b) {
  5296. const aa = a.gt(this.half) ? a.minus(this.p) : a;
  5297. const bb = b.gt(this.half) ? b.minus(this.p) : b;
  5298. return aa.lt(bb);
  5299. }
  5300. gt(a, b) {
  5301. const aa = a.gt(this.half) ? a.minus(this.p) : a;
  5302. const bb = b.gt(this.half) ? b.minus(this.p) : b;
  5303. return aa.gt(bb);
  5304. }
  5305. leq(a, b) {
  5306. const aa = a.gt(this.half) ? a.minus(this.p) : a;
  5307. const bb = b.gt(this.half) ? b.minus(this.p) : b;
  5308. return aa.leq(bb);
  5309. }
  5310. geq(a, b) {
  5311. const aa = a.gt(this.half) ? a.minus(this.p) : a;
  5312. const bb = b.gt(this.half) ? b.minus(this.p) : b;
  5313. return aa.geq(bb);
  5314. }
  5315. div(a, b) {
  5316. assert(!b.isZero(), "Division by zero");
  5317. return a.times(b.modInv(this.p)).mod(this.p);
  5318. }
  5319. idiv(a, b) {
  5320. assert(!b.isZero(), "Division by zero");
  5321. return a.divide(b);
  5322. }
  5323. inv(a) {
  5324. assert(!a.isZero(), "Division by zero");
  5325. return a.modInv(this.p);
  5326. }
  5327. mod(a, b) {
  5328. return a.mod(b);
  5329. }
  5330. pow(a, b) {
  5331. return a.modPow(b, this.p);
  5332. }
  5333. band(a, b) {
  5334. return a.and(b).and(this.mask).mod(this.p);
  5335. }
  5336. bor(a, b) {
  5337. return a.or(b).and(this.mask).mod(this.p);
  5338. }
  5339. bxor(a, b) {
  5340. return a.xor(b).and(this.mask).mod(this.p);
  5341. }
  5342. bnot(a) {
  5343. return a.xor(this.mask).mod(this.p);
  5344. }
  5345. shl(a, b) {
  5346. if (b.lt(this.bitLength)) {
  5347. return a.shiftLeft(b).and(this.mask).mod(this.p);
  5348. } else {
  5349. const nb = this.p.minus(b);
  5350. if (nb.lt(this.bitLength)) {
  5351. return this.shr(a, nb);
  5352. } else {
  5353. return bigInt.zero;
  5354. }
  5355. }
  5356. }
  5357. shr(a, b) {
  5358. if (b.lt(this.bitLength)) {
  5359. return a.shiftRight(b);
  5360. } else {
  5361. const nb = this.p.minus(b);
  5362. if (nb.lt(this.bitLength)) {
  5363. return this.shl(a, nb);
  5364. } else {
  5365. return bigInt.zero;
  5366. }
  5367. }
  5368. }
  5369. land(a, b) {
  5370. return (a.isZero() || b.isZero()) ? bigInt.zero : bigInt.one;
  5371. }
  5372. lor(a, b) {
  5373. return (a.isZero() && b.isZero()) ? bigInt.zero : bigInt.one;
  5374. }
  5375. lnot(a) {
  5376. return a.isZero() ? bigInt.one : bigInt.zero;
  5377. }
  5378. sqrt(n) {
  5379. if (n.equals(this.zero)) return this.zero;
  5380. // Test that have solution
  5381. const res = this.pow(n, this.minusone.shiftRight(this.one));
  5382. if (!res.equals(this.one)) return null;
  5383. let m = parseInt(this.s);
  5384. let c = this.nqr_to_t;
  5385. let t = this.pow(n, this.t);
  5386. let r = this.pow(n, this.add(this.t, this.one).shiftRight(this.one) );
  5387. while (!t.equals(this.one)) {
  5388. let sq = this.square(t);
  5389. let i = 1;
  5390. while (!sq.equals(this.one)) {
  5391. i++;
  5392. sq = this.square(sq);
  5393. }
  5394. // b = c ^ m-i-1
  5395. let b = c;
  5396. for (let j=0; j< m-i-1; j ++) b = this.square(b);
  5397. m = i;
  5398. c = this.square(b);
  5399. t = this.mul(t, c);
  5400. r = this.mul(r, b);
  5401. }
  5402. if (r.greater(this.p.shiftRight(this.one))) {
  5403. r = this.neg(r);
  5404. }
  5405. return r;
  5406. }
  5407. normalize(a) {
  5408. a = bigInt(a);
  5409. if (a.isNegative()) {
  5410. return this.p.minus(a.abs().mod(this.p));
  5411. } else {
  5412. return a.mod(this.p);
  5413. }
  5414. }
  5415. random() {
  5416. let res = bigInt(0);
  5417. let n = bigInt(this.p.square());
  5418. while (!n.isZero()) {
  5419. res = res.shiftLeft(8).add(bigInt(getRandomByte()));
  5420. n = n.shiftRight(8);
  5421. }
  5422. return res.mod(this.p);
  5423. }
  5424. toString(a, base) {
  5425. let vs;
  5426. if (!a.lesserOrEquals(this.p.shiftRight(bigInt(1)))) {
  5427. const v = this.p.minus(a);
  5428. vs = "-"+v.toString(base);
  5429. } else {
  5430. vs = a.toString(base);
  5431. }
  5432. return vs;
  5433. }
  5434. isZero(a) {
  5435. return a.isZero();
  5436. }
  5437. };
  5438. },{"assert":1,"big-integer":6}],17:[function(require,module,exports){
  5439. /* global BigInt */
  5440. const assert = require("assert");
  5441. const Scalar = require("./scalar");
  5442. const futils = require("./futils");
  5443. function getRandomByte() {
  5444. if (typeof window !== "undefined") { // Browser
  5445. if (typeof window.crypto !== "undefined") { // Supported
  5446. let array = new Uint8Array(1);
  5447. window.crypto.getRandomValues(array);
  5448. return array[0];
  5449. }
  5450. else { // fallback
  5451. return Math.floor(Math.random() * 256);
  5452. }
  5453. }
  5454. else { // NodeJS
  5455. return module.require("crypto").randomBytes(1)[0];
  5456. }
  5457. }
  5458. module.exports = class ZqField {
  5459. constructor(p) {
  5460. this.one = 1n;
  5461. this.zero = 0n;
  5462. this.p = BigInt(p);
  5463. this.minusone = this.p-1n;
  5464. this.two = 2n;
  5465. this.half = this.p >> 1n;
  5466. this.bitLength = Scalar.bitLength(this.p);
  5467. this.mask = (1n << BigInt(this.bitLength)) - 1n;
  5468. this.n64 = Math.floor((this.bitLength - 1) / 64)+1;
  5469. this.R = this.e(1n << BigInt(this.n64*64));
  5470. const e = this.minusone >> 1n;
  5471. this.nqr = this.two;
  5472. let r = this.pow(this.nqr, e);
  5473. while (!this.eq(r, this.minusone)) {
  5474. this.nqr = this.nqr + 1n;
  5475. r = this.pow(this.nqr, e);
  5476. }
  5477. this.s = 0;
  5478. this.t = this.minusone;
  5479. while ((this.t & 1n) == 0n) {
  5480. this.s = this.s + 1;
  5481. this.t = this.t >> 1n;
  5482. }
  5483. this.nqr_to_t = this.pow(this.nqr, this.t);
  5484. }
  5485. e(a,b) {
  5486. let res;
  5487. if (!b) {
  5488. res = BigInt(a);
  5489. } else if (b==16) {
  5490. res = BigInt("0x"+a);
  5491. }
  5492. if (res < 0) {
  5493. let nres = -res;
  5494. if (nres >= this.p) nres = nres % this.p;
  5495. return this.p - nres;
  5496. } else {
  5497. return (res>= this.p) ? res%this.p : res;
  5498. }
  5499. }
  5500. add(a, b) {
  5501. const res = a + b;
  5502. return res >= this.p ? res-this.p : res;
  5503. }
  5504. sub(a, b) {
  5505. return (a >= b) ? a-b : this.p-b+a;
  5506. }
  5507. neg(a) {
  5508. return a ? this.p-a : a;
  5509. }
  5510. mul(a, b) {
  5511. return (a*b)%this.p;
  5512. }
  5513. mulScalar(base, s) {
  5514. return (base * this.e(s)) % this.p;
  5515. }
  5516. square(a) {
  5517. return (a*a) % this.p;
  5518. }
  5519. eq(a, b) {
  5520. return a==b;
  5521. }
  5522. neq(a, b) {
  5523. return a!=b;
  5524. }
  5525. lt(a, b) {
  5526. const aa = (a > this.half) ? a - this.p : a;
  5527. const bb = (b > this.half) ? b - this.p : b;
  5528. return aa < bb;
  5529. }
  5530. gt(a, b) {
  5531. const aa = (a > this.half) ? a - this.p : a;
  5532. const bb = (b > this.half) ? b - this.p : b;
  5533. return aa > bb;
  5534. }
  5535. leq(a, b) {
  5536. const aa = (a > this.half) ? a - this.p : a;
  5537. const bb = (b > this.half) ? b - this.p : b;
  5538. return aa <= bb;
  5539. }
  5540. geq(a, b) {
  5541. const aa = (a > this.half) ? a - this.p : a;
  5542. const bb = (b > this.half) ? b - this.p : b;
  5543. return aa >= bb;
  5544. }
  5545. div(a, b) {
  5546. return this.mul(a, this.inv(b));
  5547. }
  5548. idiv(a, b) {
  5549. assert(b, "Division by zero");
  5550. return a / b;
  5551. }
  5552. inv(a) {
  5553. assert(a, "Division by zero");
  5554. let t = 0n;
  5555. let r = this.p;
  5556. let newt = 1n;
  5557. let newr = a % this.p;
  5558. while (newr) {
  5559. let q = r/newr;
  5560. [t, newt] = [newt, t-q*newt];
  5561. [r, newr] = [newr, r-q*newr];
  5562. }
  5563. if (t<0n) t += this.p;
  5564. return t;
  5565. }
  5566. mod(a, b) {
  5567. return a % b;
  5568. }
  5569. pow(b, e) {
  5570. return futils.exp(this, b, e);
  5571. }
  5572. band(a, b) {
  5573. const res = ((a & b) & this.mask);
  5574. return res >= this.p ? res-this.p : res;
  5575. }
  5576. bor(a, b) {
  5577. const res = ((a | b) & this.mask);
  5578. return res >= this.p ? res-this.p : res;
  5579. }
  5580. bxor(a, b) {
  5581. const res = ((a ^ b) & this.mask);
  5582. return res >= this.p ? res-this.p : res;
  5583. }
  5584. bnot(a) {
  5585. const res = a ^ this.mask;
  5586. return res >= this.p ? res-this.p : res;
  5587. }
  5588. shl(a, b) {
  5589. if (Number(b) < this.bitLength) {
  5590. const res = (a << b) & this.mask;
  5591. return res >= this.p ? res-this.p : res;
  5592. } else {
  5593. const nb = this.p - b;
  5594. if (Number(nb) < this.bitLength) {
  5595. return a >> nb;
  5596. } else {
  5597. return 0n;
  5598. }
  5599. }
  5600. }
  5601. shr(a, b) {
  5602. if (Number(b) < this.bitLength) {
  5603. return a >> b;
  5604. } else {
  5605. const nb = this.p - b;
  5606. if (Number(nb) < this.bitLength) {
  5607. const res = (a << nb) & this.mask;
  5608. return res >= this.p ? res-this.p : res;
  5609. } else {
  5610. return 0;
  5611. }
  5612. }
  5613. }
  5614. land(a, b) {
  5615. return (a && b) ? 1n : 0n;
  5616. }
  5617. lor(a, b) {
  5618. return (a || b) ? 1n : 0n;
  5619. }
  5620. lnot(a) {
  5621. return (a) ? 0n : 1n;
  5622. }
  5623. sqrt(n) {
  5624. if (n == 0n) return this.zero;
  5625. // Test that have solution
  5626. const res = this.pow(n, this.minusone >> this.one);
  5627. if ( res != 1n ) return null;
  5628. let m = this.s;
  5629. let c = this.nqr_to_t;
  5630. let t = this.pow(n, this.t);
  5631. let r = this.pow(n, this.add(this.t, this.one) >> 1n );
  5632. while ( t != 1n ) {
  5633. let sq = this.square(t);
  5634. let i = 1;
  5635. while (sq != 1n ) {
  5636. i++;
  5637. sq = this.square(sq);
  5638. }
  5639. // b = c ^ m-i-1
  5640. let b = c;
  5641. for (let j=0; j< m-i-1; j ++) b = this.square(b);
  5642. m = i;
  5643. c = this.square(b);
  5644. t = this.mul(t, c);
  5645. r = this.mul(r, b);
  5646. }
  5647. if (r > (this.p >> 1n)) {
  5648. r = this.neg(r);
  5649. }
  5650. return r;
  5651. }
  5652. normalize(a, b) {
  5653. a = BigInt(a,b);
  5654. if (a < 0) {
  5655. let na = -a;
  5656. if (na >= this.p) na = na % this.p;
  5657. return this.p - na;
  5658. } else {
  5659. return (a>= this.p) ? a%this.p : a;
  5660. }
  5661. }
  5662. random() {
  5663. const nBytes = (this.bitLength*2 / 8);
  5664. let res =0n;
  5665. for (let i=0; i<nBytes; i++) {
  5666. res = (res << 8n) + BigInt(getRandomByte());
  5667. }
  5668. return res % this.p;
  5669. }
  5670. toString(a, base) {
  5671. let vs;
  5672. if (a > this.half) {
  5673. const v = this.p-a;
  5674. vs = "-"+v.toString(base);
  5675. } else {
  5676. vs = a.toString(base);
  5677. }
  5678. return vs;
  5679. }
  5680. isZero(a) {
  5681. return a == 0n;
  5682. }
  5683. };
  5684. },{"./futils":20,"./scalar":22,"assert":1}],18:[function(require,module,exports){
  5685. /*
  5686. Copyright 2018 0kims association.
  5687. This file is part of snarkjs.
  5688. snarkjs is a free software: you can redistribute it and/or
  5689. modify it under the terms of the GNU General Public License as published by the
  5690. Free Software Foundation, either version 3 of the License, or (at your option)
  5691. any later version.
  5692. snarkjs is distributed in the hope that it will be useful,
  5693. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  5694. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  5695. more details.
  5696. You should have received a copy of the GNU General Public License along with
  5697. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  5698. */
  5699. const fUtils = require("./futils.js");
  5700. class F2Field {
  5701. constructor(F, nonResidue) {
  5702. this.F = F;
  5703. this.zero = [this.F.zero, this.F.zero];
  5704. this.one = [this.F.one, this.F.zero];
  5705. this.nonResidue = nonResidue;
  5706. }
  5707. _mulByNonResidue(a) {
  5708. return this.F.mul(this.nonResidue, a);
  5709. }
  5710. copy(a) {
  5711. return [this.F.copy(a[0]), this.F.copy(a[1])];
  5712. }
  5713. add(a, b) {
  5714. return [
  5715. this.F.add(a[0], b[0]),
  5716. this.F.add(a[1], b[1])
  5717. ];
  5718. }
  5719. double(a) {
  5720. return this.add(a,a);
  5721. }
  5722. sub(a, b) {
  5723. return [
  5724. this.F.sub(a[0], b[0]),
  5725. this.F.sub(a[1], b[1])
  5726. ];
  5727. }
  5728. neg(a) {
  5729. return this.sub(this.zero, a);
  5730. }
  5731. mul(a, b) {
  5732. const aA = this.F.mul(a[0] , b[0]);
  5733. const bB = this.F.mul(a[1] , b[1]);
  5734. return [
  5735. this.F.add( aA , this._mulByNonResidue(bB)),
  5736. this.F.sub(
  5737. this.F.mul(
  5738. this.F.add(a[0], a[1]),
  5739. this.F.add(b[0], b[1])),
  5740. this.F.add(aA, bB))];
  5741. }
  5742. inv(a) {
  5743. const t0 = this.F.square(a[0]);
  5744. const t1 = this.F.square(a[1]);
  5745. const t2 = this.F.sub(t0, this._mulByNonResidue(t1));
  5746. const t3 = this.F.inv(t2);
  5747. return [
  5748. this.F.mul(a[0], t3),
  5749. this.F.neg(this.F.mul( a[1], t3)) ];
  5750. }
  5751. div(a, b) {
  5752. return this.mul(a, this.inv(b));
  5753. }
  5754. square(a) {
  5755. const ab = this.F.mul(a[0] , a[1]);
  5756. /*
  5757. [
  5758. (a + b) * (a + non_residue * b) - ab - non_residue * ab,
  5759. ab + ab
  5760. ];
  5761. */
  5762. return [
  5763. this.F.sub(
  5764. this.F.mul(
  5765. this.F.add(a[0], a[1]) ,
  5766. this.F.add(
  5767. a[0] ,
  5768. this._mulByNonResidue(a[1]))),
  5769. this.F.add(
  5770. ab,
  5771. this._mulByNonResidue(ab))),
  5772. this.F.add(ab, ab)
  5773. ];
  5774. }
  5775. isZero(a) {
  5776. return this.F.isZero(a[0]) && this.F.isZero(a[1]);
  5777. }
  5778. eq(a, b) {
  5779. return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]);
  5780. }
  5781. mulScalar(base, e) {
  5782. return fUtils.mulScalar(this, base, e);
  5783. }
  5784. exp(base, e) {
  5785. return fUtils.exp(this, base, e);
  5786. }
  5787. toString(a) {
  5788. return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`;
  5789. }
  5790. }
  5791. module.exports = F2Field;
  5792. },{"./futils.js":20}],19:[function(require,module,exports){
  5793. /*
  5794. Copyright 2018 0kims association.
  5795. This file is part of snarkjs.
  5796. snarkjs is a free software: you can redistribute it and/or
  5797. modify it under the terms of the GNU General Public License as published by the
  5798. Free Software Foundation, either version 3 of the License, or (at your option)
  5799. any later version.
  5800. snarkjs is distributed in the hope that it will be useful,
  5801. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  5802. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  5803. more details.
  5804. You should have received a copy of the GNU General Public License along with
  5805. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  5806. */
  5807. const fUtils = require("./futils.js");
  5808. class F3Field {
  5809. constructor(F, nonResidue) {
  5810. this.F = F;
  5811. this.zero = [this.F.zero, this.F.zero, this.F.zero];
  5812. this.one = [this.F.one, this.F.zero, this.F.zero];
  5813. this.nonResidue = nonResidue;
  5814. }
  5815. _mulByNonResidue(a) {
  5816. return this.F.mul(this.nonResidue, a);
  5817. }
  5818. copy(a) {
  5819. return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])];
  5820. }
  5821. add(a, b) {
  5822. return [
  5823. this.F.add(a[0], b[0]),
  5824. this.F.add(a[1], b[1]),
  5825. this.F.add(a[2], b[2])
  5826. ];
  5827. }
  5828. double(a) {
  5829. return this.add(a,a);
  5830. }
  5831. sub(a, b) {
  5832. return [
  5833. this.F.sub(a[0], b[0]),
  5834. this.F.sub(a[1], b[1]),
  5835. this.F.sub(a[2], b[2])
  5836. ];
  5837. }
  5838. neg(a) {
  5839. return this.sub(this.zero, a);
  5840. }
  5841. mul(a, b) {
  5842. const aA = this.F.mul(a[0] , b[0]);
  5843. const bB = this.F.mul(a[1] , b[1]);
  5844. const cC = this.F.mul(a[2] , b[2]);
  5845. return [
  5846. this.F.add(
  5847. aA,
  5848. this._mulByNonResidue(
  5849. this.F.sub(
  5850. this.F.mul(
  5851. this.F.add(a[1], a[2]),
  5852. this.F.add(b[1], b[2])),
  5853. this.F.add(bB, cC)))), // aA + non_residue*((b+c)*(B+C)-bB-cC),
  5854. this.F.add(
  5855. this.F.sub(
  5856. this.F.mul(
  5857. this.F.add(a[0], a[1]),
  5858. this.F.add(b[0], b[1])),
  5859. this.F.add(aA, bB)),
  5860. this._mulByNonResidue( cC)), // (a+b)*(A+B)-aA-bB+non_residue*cC
  5861. this.F.add(
  5862. this.F.sub(
  5863. this.F.mul(
  5864. this.F.add(a[0], a[2]),
  5865. this.F.add(b[0], b[2])),
  5866. this.F.add(aA, cC)),
  5867. bB)]; // (a+c)*(A+C)-aA+bB-cC)
  5868. }
  5869. inv(a) {
  5870. const t0 = this.F.square(a[0]); // t0 = a^2 ;
  5871. const t1 = this.F.square(a[1]); // t1 = b^2 ;
  5872. const t2 = this.F.square(a[2]); // t2 = c^2;
  5873. const t3 = this.F.mul(a[0],a[1]); // t3 = ab
  5874. const t4 = this.F.mul(a[0],a[2]); // t4 = ac
  5875. const t5 = this.F.mul(a[1],a[2]); // t5 = bc;
  5876. // c0 = t0 - non_residue * t5;
  5877. const c0 = this.F.sub(t0, this._mulByNonResidue(t5));
  5878. // c1 = non_residue * t2 - t3;
  5879. const c1 = this.F.sub(this._mulByNonResidue(t2), t3);
  5880. const c2 = this.F.sub(t1, t4); // c2 = t1-t4
  5881. // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv();
  5882. const t6 =
  5883. this.F.inv(
  5884. this.F.add(
  5885. this.F.mul(a[0], c0),
  5886. this._mulByNonResidue(
  5887. this.F.add(
  5888. this.F.mul(a[2], c1),
  5889. this.F.mul(a[1], c2)))));
  5890. return [
  5891. this.F.mul(t6, c0), // t6*c0
  5892. this.F.mul(t6, c1), // t6*c1
  5893. this.F.mul(t6, c2)]; // t6*c2
  5894. }
  5895. div(a, b) {
  5896. return this.mul(a, this.inv(b));
  5897. }
  5898. square(a) {
  5899. const s0 = this.F.square(a[0]); // s0 = a^2
  5900. const ab = this.F.mul(a[0], a[1]); // ab = a*b
  5901. const s1 = this.F.add(ab, ab); // s1 = 2ab;
  5902. const s2 = this.F.square(
  5903. this.F.add(this.F.sub(a[0],a[1]), a[2])); // s2 = (a - b + c)^2;
  5904. const bc = this.F.mul(a[1],a[2]); // bc = b*c
  5905. const s3 = this.F.add(bc, bc); // s3 = 2*bc
  5906. const s4 = this.F.square(a[2]); // s4 = c^2
  5907. return [
  5908. this.F.add(
  5909. s0,
  5910. this._mulByNonResidue(s3)), // s0 + non_residue * s3,
  5911. this.F.add(
  5912. s1,
  5913. this._mulByNonResidue(s4)), // s1 + non_residue * s4,
  5914. this.F.sub(
  5915. this.F.add( this.F.add(s1, s2) , s3 ),
  5916. this.F.add(s0, s4))]; // s1 + s2 + s3 - s0 - s4
  5917. }
  5918. isZero(a) {
  5919. return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]);
  5920. }
  5921. eq(a, b) {
  5922. return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]);
  5923. }
  5924. affine(a) {
  5925. return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])];
  5926. }
  5927. mulScalar(base, e) {
  5928. return fUtils.mulScalar(this, base, e);
  5929. }
  5930. exp(base, e) {
  5931. return fUtils.exp(this, base, e);
  5932. }
  5933. toString(a) {
  5934. return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`;
  5935. }
  5936. }
  5937. module.exports = F3Field;
  5938. },{"./futils.js":20}],20:[function(require,module,exports){
  5939. /*
  5940. Copyright 2018 0kims association.
  5941. This file is part of snarkjs.
  5942. snarkjs is a free software: you can redistribute it and/or
  5943. modify it under the terms of the GNU General Public License as published by the
  5944. Free Software Foundation, either version 3 of the License, or (at your option)
  5945. any later version.
  5946. snarkjs is distributed in the hope that it will be useful,
  5947. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  5948. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  5949. more details.
  5950. You should have received a copy of the GNU General Public License along with
  5951. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  5952. */
  5953. const Scalar = require("./scalar.js");
  5954. const assert = require("assert");
  5955. exports.mulScalar = (F, base, e) => {
  5956. let res;
  5957. if (Scalar.isZero(e)) return F.zero;
  5958. const n = Scalar.naf(e);
  5959. if (n[n.length-1] == 1) {
  5960. res = base;
  5961. } else if (n[n.length-1] == -1) {
  5962. res = F.neg(base);
  5963. } else {
  5964. assert(false);
  5965. }
  5966. for (let i=n.length-2; i>=0; i--) {
  5967. res = F.double(res);
  5968. if (n[i] == 1) {
  5969. res = F.add(res, base);
  5970. } else if (n[i] == -1) {
  5971. res = F.sub(res, base);
  5972. }
  5973. }
  5974. return res;
  5975. };
  5976. /*
  5977. exports.mulScalar = (F, base, e) =>{
  5978. let res = F.zero;
  5979. let rem = bigInt(e);
  5980. let exp = base;
  5981. while (! rem.eq(bigInt.zero)) {
  5982. if (rem.and(bigInt.one).eq(bigInt.one)) {
  5983. res = F.add(res, exp);
  5984. }
  5985. exp = F.double(exp);
  5986. rem = rem.shiftRight(1);
  5987. }
  5988. return res;
  5989. };
  5990. */
  5991. exports.exp = (F, base, e) => {
  5992. if (Scalar.isZero(e)) return F.one;
  5993. const n = Scalar.bits(e);
  5994. if (n.legth==0) return F.one;
  5995. let res = base;
  5996. for (let i=n.length-2; i>=0; i--) {
  5997. res = F.square(res);
  5998. if (n[i]) {
  5999. res = F.mul(res, base);
  6000. }
  6001. }
  6002. return res;
  6003. };
  6004. },{"./scalar.js":22,"assert":1}],21:[function(require,module,exports){
  6005. /*
  6006. Copyright 2018 0kims association.
  6007. This file is part of snarkjs.
  6008. snarkjs is a free software: you can redistribute it and/or
  6009. modify it under the terms of the GNU General Public License as published by the
  6010. Free Software Foundation, either version 3 of the License, or (at your option)
  6011. any later version.
  6012. snarkjs is distributed in the hope that it will be useful,
  6013. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  6014. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  6015. more details.
  6016. You should have received a copy of the GNU General Public License along with
  6017. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  6018. */
  6019. /*
  6020. This library does operations on polynomials with coefficients in a field F.
  6021. A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n is represented
  6022. by the array [ p0, p1, p2, ... , pn ].
  6023. */
  6024. class PolField {
  6025. constructor (F) {
  6026. this.F = F;
  6027. let rem = F.t;
  6028. let s = F.s;
  6029. const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one);
  6030. this.w = new Array(s+1);
  6031. this.wi = new Array(s+1);
  6032. this.w[s] = this.F.pow(five, rem);
  6033. this.wi[s] = this.F.inv(this.w[s]);
  6034. let n=s-1;
  6035. while (n>=0) {
  6036. this.w[n] = this.F.square(this.w[n+1]);
  6037. this.wi[n] = this.F.square(this.wi[n+1]);
  6038. n--;
  6039. }
  6040. this.roots = [];
  6041. /* for (let i=0; i<16; i++) {
  6042. let r = this.F.one;
  6043. n = 1 << i;
  6044. const rootsi = new Array(n);
  6045. for (let j=0; j<n; j++) {
  6046. rootsi[j] = r;
  6047. r = this.F.mul(r, this.w[i]);
  6048. }
  6049. this.roots.push(rootsi);
  6050. }
  6051. */
  6052. this._setRoots(15);
  6053. }
  6054. _setRoots(n) {
  6055. for (let i=n; (i>=0) && (!this.roots[i]); i--) {
  6056. let r = this.F.one;
  6057. const nroots = 1 << i;
  6058. const rootsi = new Array(nroots);
  6059. for (let j=0; j<nroots; j++) {
  6060. rootsi[j] = r;
  6061. r = this.F.mul(r, this.w[i]);
  6062. }
  6063. this.roots[i] = rootsi;
  6064. }
  6065. }
  6066. add(a, b) {
  6067. const m = Math.max(a.length, b.length);
  6068. const res = new Array(m);
  6069. for (let i=0; i<m; i++) {
  6070. res[i] = this.F.add(a[i] || this.F.zero, b[i] || this.F.zero);
  6071. }
  6072. return this.reduce(res);
  6073. }
  6074. double(a) {
  6075. return this.add(a,a);
  6076. }
  6077. sub(a, b) {
  6078. const m = Math.max(a.length, b.length);
  6079. const res = new Array(m);
  6080. for (let i=0; i<m; i++) {
  6081. res[i] = this.F.sub(a[i] || this.F.zero, b[i] || this.F.zero);
  6082. }
  6083. return this.reduce(res);
  6084. }
  6085. mulScalar(p, b) {
  6086. if (this.F.eq(b, this.F.zero)) return [];
  6087. if (this.F.eq(b, this.F.one)) return p;
  6088. const res = new Array(p.length);
  6089. for (let i=0; i<p.length; i++) {
  6090. res[i] = this.F.mul(p[i], b);
  6091. }
  6092. return res;
  6093. }
  6094. mul(a, b) {
  6095. if (a.length == 0) return [];
  6096. if (b.length == 0) return [];
  6097. if (a.length == 1) return this.mulScalar(b, a[0]);
  6098. if (b.length == 1) return this.mulScalar(a, b[0]);
  6099. if (b.length > a.length) {
  6100. [b, a] = [a, b];
  6101. }
  6102. if ((b.length <= 2) || (b.length < log2(a.length))) {
  6103. return this.mulNormal(a,b);
  6104. } else {
  6105. return this.mulFFT(a,b);
  6106. }
  6107. }
  6108. mulNormal(a, b) {
  6109. let res = [];
  6110. for (let i=0; i<b.length; i++) {
  6111. res = this.add(res, this.scaleX(this.mulScalar(a, b[i]), i) );
  6112. }
  6113. return res;
  6114. }
  6115. mulFFT(a,b) {
  6116. const longestN = Math.max(a.length, b.length);
  6117. const bitsResult = log2(longestN-1)+2;
  6118. this._setRoots(bitsResult);
  6119. const m = 1 << bitsResult;
  6120. const ea = this.extend(a,m);
  6121. const eb = this.extend(b,m);
  6122. const ta = __fft(this, ea, bitsResult, 0, 1, false);
  6123. const tb = __fft(this, eb, bitsResult, 0, 1, false);
  6124. const tres = new Array(m);
  6125. for (let i=0; i<m; i++) {
  6126. tres[i] = this.F.mul(ta[i], tb[i]);
  6127. }
  6128. const res = __fft(this, tres, bitsResult, 0, 1, true);
  6129. const twoinvm = this.F.inv( this.F.mulScalar(this.F.one, m) );
  6130. const resn = new Array(m);
  6131. for (let i=0; i<m; i++) {
  6132. resn[i] = this.F.mul(res[(m-i)%m], twoinvm);
  6133. }
  6134. return this.reduce(resn);
  6135. }
  6136. square(a) {
  6137. return this.mul(a,a);
  6138. }
  6139. scaleX(p, n) {
  6140. if (n==0) {
  6141. return p;
  6142. } else if (n>0) {
  6143. const z = new Array(n).fill(this.F.zero);
  6144. return z.concat(p);
  6145. } else {
  6146. if (-n >= p.length) return [];
  6147. return p.slice(-n);
  6148. }
  6149. }
  6150. eval2(p, x) {
  6151. let v = this.F.zero;
  6152. let ix = this.F.one;
  6153. for (let i=0; i<p.length; i++) {
  6154. v = this.F.add(v, this.F.mul(p[i], ix));
  6155. ix = this.F.mul(ix, x);
  6156. }
  6157. return v;
  6158. }
  6159. eval(p,x) {
  6160. const F = this.F;
  6161. if (p.length == 0) return F.zero;
  6162. const m = this._next2Power(p.length);
  6163. const ep = this.extend(p, m);
  6164. return _eval(ep, x, 0, 1, m);
  6165. function _eval(p, x, offset, step, n) {
  6166. if (n==1) return p[offset];
  6167. const newX = F.square(x);
  6168. const res= F.add(
  6169. _eval(p, newX, offset, step << 1, n >> 1),
  6170. F.mul(
  6171. x,
  6172. _eval(p, newX, offset+step , step << 1, n >> 1)));
  6173. return res;
  6174. }
  6175. }
  6176. lagrange(points) {
  6177. let roots = [this.F.one];
  6178. for (let i=0; i<points.length; i++) {
  6179. roots = this.mul(roots, [this.F.neg(points[i][0]), this.F.one]);
  6180. }
  6181. let sum = [];
  6182. for (let i=0; i<points.length; i++) {
  6183. let mpol = this.ruffini(roots, points[i][0]);
  6184. const factor =
  6185. this.F.mul(
  6186. this.F.inv(this.eval(mpol, points[i][0])),
  6187. points[i][1]);
  6188. mpol = this.mulScalar(mpol, factor);
  6189. sum = this.add(sum, mpol);
  6190. }
  6191. return sum;
  6192. }
  6193. fft(p) {
  6194. if (p.length <= 1) return p;
  6195. const bits = log2(p.length-1)+1;
  6196. this._setRoots(bits);
  6197. const m = 1 << bits;
  6198. const ep = this.extend(p, m);
  6199. const res = __fft(this, ep, bits, 0, 1);
  6200. return res;
  6201. }
  6202. ifft(p) {
  6203. if (p.length <= 1) return p;
  6204. const bits = log2(p.length-1)+1;
  6205. this._setRoots(bits);
  6206. const m = 1 << bits;
  6207. const ep = this.extend(p, m);
  6208. const res = __fft(this, ep, bits, 0, 1);
  6209. const twoinvm = this.F.inv( this.F.mulScalar(this.F.one, m) );
  6210. const resn = new Array(m);
  6211. for (let i=0; i<m; i++) {
  6212. resn[i] = this.F.mul(res[(m-i)%m], twoinvm);
  6213. }
  6214. return resn;
  6215. }
  6216. _fft(pall, bits, offset, step) {
  6217. const n = 1 << bits;
  6218. if (n==1) {
  6219. return [ pall[offset] ];
  6220. }
  6221. const ndiv2 = n >> 1;
  6222. const p1 = this._fft(pall, bits-1, offset, step*2);
  6223. const p2 = this._fft(pall, bits-1, offset+step, step*2);
  6224. const out = new Array(n);
  6225. let m= this.F.one;
  6226. for (let i=0; i<ndiv2; i++) {
  6227. out[i] = this.F.add(p1[i], this.F.mul(m, p2[i]));
  6228. out[i+ndiv2] = this.F.sub(p1[i], this.F.mul(m, p2[i]));
  6229. m = this.F.mul(m, this.w[bits]);
  6230. }
  6231. return out;
  6232. }
  6233. extend(p, e) {
  6234. if (e == p.length) return p;
  6235. const z = new Array(e-p.length).fill(this.F.zero);
  6236. return p.concat(z);
  6237. }
  6238. reduce(p) {
  6239. if (p.length == 0) return p;
  6240. if (! this.F.eq(p[p.length-1], this.F.zero) ) return p;
  6241. let i=p.length-1;
  6242. while( i>0 && this.F.eq(p[i], this.F.zero) ) i--;
  6243. return p.slice(0, i+1);
  6244. }
  6245. eq(a, b) {
  6246. const pa = this.reduce(a);
  6247. const pb = this.reduce(b);
  6248. if (pa.length != pb.length) return false;
  6249. for (let i=0; i<pb.length; i++) {
  6250. if (!this.F.eq(pa[i], pb[i])) return false;
  6251. }
  6252. return true;
  6253. }
  6254. ruffini(p, r) {
  6255. const res = new Array(p.length-1);
  6256. res[res.length-1] = p[p.length-1];
  6257. for (let i = res.length-2; i>=0; i--) {
  6258. res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]);
  6259. }
  6260. return res;
  6261. }
  6262. _next2Power(v) {
  6263. v--;
  6264. v |= v >> 1;
  6265. v |= v >> 2;
  6266. v |= v >> 4;
  6267. v |= v >> 8;
  6268. v |= v >> 16;
  6269. v++;
  6270. return v;
  6271. }
  6272. toString(p) {
  6273. const ap = this.normalize(p);
  6274. let S = "";
  6275. for (let i=ap.length-1; i>=0; i--) {
  6276. if (!this.F.eq(p[i], this.F.zero)) {
  6277. if (S!="") S += " + ";
  6278. S = S + p[i].toString(10);
  6279. if (i>0) {
  6280. S = S + "x";
  6281. if (i>1) {
  6282. S = S + "^" +i;
  6283. }
  6284. }
  6285. }
  6286. }
  6287. return S;
  6288. }
  6289. normalize(p) {
  6290. const res = new Array(p.length);
  6291. for (let i=0; i<p.length; i++) {
  6292. res[i] = this.F.normalize(p[i]);
  6293. }
  6294. return res;
  6295. }
  6296. _reciprocal(p, bits) {
  6297. const k = 1 << bits;
  6298. if (k==1) {
  6299. return [ this.F.inv(p[0]) ];
  6300. }
  6301. const np = this.scaleX(p, -k/2);
  6302. const q = this._reciprocal(np, bits-1);
  6303. const a = this.scaleX(this.double(q), 3*k/2-2);
  6304. const b = this.mul( this.square(q), p);
  6305. return this.scaleX(this.sub(a,b), -(k-2));
  6306. }
  6307. // divides x^m / v
  6308. _div2(m, v) {
  6309. const kbits = log2(v.length-1)+1;
  6310. const k = 1 << kbits;
  6311. const scaleV = k - v.length;
  6312. // rec = x^(k - 2) / v* x^scaleV =>
  6313. // rec = x^(k-2-scaleV)/ v
  6314. //
  6315. // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v =>
  6316. // res = rec * x^(m - (2*k-2 - scaleV)) =>
  6317. // res = rec * x^(m - 2*k + 2 + scaleV)
  6318. const rec = this._reciprocal(this.scaleX(v, scaleV), kbits);
  6319. const res = this.scaleX(rec, m - 2*k + 2 + scaleV);
  6320. return res;
  6321. }
  6322. div(_u, _v) {
  6323. if (_u.length < _v.length) return [];
  6324. const kbits = log2(_v.length-1)+1;
  6325. const k = 1 << kbits;
  6326. const u = this.scaleX(_u, k-_v.length);
  6327. const v = this.scaleX(_v, k-_v.length);
  6328. const n = v.length-1;
  6329. let m = u.length-1;
  6330. const s = this._reciprocal(v, kbits);
  6331. let t;
  6332. if (m>2*n) {
  6333. t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v));
  6334. }
  6335. let q = [];
  6336. let rem = u;
  6337. let us, ut;
  6338. let finish = false;
  6339. while (!finish) {
  6340. us = this.mul(rem, s);
  6341. q = this.add(q, this.scaleX(us, -2*n));
  6342. if ( m > 2*n ) {
  6343. ut = this.mul(rem, t);
  6344. rem = this.scaleX(ut, -2*n);
  6345. m = rem.length-1;
  6346. } else {
  6347. finish = true;
  6348. }
  6349. }
  6350. return q;
  6351. }
  6352. // returns the ith nth-root of one
  6353. oneRoot(n, i) {
  6354. let nbits = log2(n-1)+1;
  6355. let res = this.F.one;
  6356. let r = i;
  6357. if(i>=n) {
  6358. throw new Error("Given 'i' should be lower than 'n'");
  6359. }
  6360. else if (1<<nbits !== n) {
  6361. throw new Error(`Internal errlr: ${n} should equal ${1<<nbits}`);
  6362. }
  6363. while (r>0) {
  6364. if (r & 1 == 1) {
  6365. res = this.F.mul(res, this.w[nbits]);
  6366. }
  6367. r = r >> 1;
  6368. nbits --;
  6369. }
  6370. return res;
  6371. }
  6372. computeVanishingPolinomial(bits, t) {
  6373. const m = 1 << bits;
  6374. return this.F.sub(this.F.pow(t, m), this.F.one);
  6375. }
  6376. evaluateLagrangePolynomials(bits, t) {
  6377. const m= 1 << bits;
  6378. const tm = this.F.pow(t, m);
  6379. const u= new Array(m).fill(this.F.zero);
  6380. this._setRoots(bits);
  6381. const omega = this.w[bits];
  6382. if (this.F.eq(tm, this.F.one)) {
  6383. for (let i = 0; i < m; i++) {
  6384. if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i
  6385. u[i] = this.F.one;
  6386. return u;
  6387. }
  6388. }
  6389. }
  6390. const z = this.F.sub(tm, this.F.one);
  6391. // let l = this.F.mul(z, this.F.pow(this.F.twoinv, m));
  6392. let l = this.F.mul(z, this.F.inv(this.F.e(m)));
  6393. for (let i = 0; i < m; i++) {
  6394. u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i])));
  6395. l = this.F.mul(l, omega);
  6396. }
  6397. return u;
  6398. }
  6399. log2(V) {
  6400. return log2(V);
  6401. }
  6402. }
  6403. function log2( V )
  6404. {
  6405. return( ( ( V & 0xFFFF0000 ) !== 0 ? ( V &= 0xFFFF0000, 16 ) : 0 ) | ( ( V & 0xFF00FF00 ) !== 0 ? ( V &= 0xFF00FF00, 8 ) : 0 ) | ( ( V & 0xF0F0F0F0 ) !== 0 ? ( V &= 0xF0F0F0F0, 4 ) : 0 ) | ( ( V & 0xCCCCCCCC ) !== 0 ? ( V &= 0xCCCCCCCC, 2 ) : 0 ) | ( ( V & 0xAAAAAAAA ) !== 0 ) );
  6406. }
  6407. function __fft(PF, pall, bits, offset, step) {
  6408. const n = 1 << bits;
  6409. if (n==1) {
  6410. return [ pall[offset] ];
  6411. } else if (n==2) {
  6412. return [
  6413. PF.F.add(pall[offset], pall[offset + step]),
  6414. PF.F.sub(pall[offset], pall[offset + step])];
  6415. }
  6416. const ndiv2 = n >> 1;
  6417. const p1 = __fft(PF, pall, bits-1, offset, step*2);
  6418. const p2 = __fft(PF, pall, bits-1, offset+step, step*2);
  6419. const out = new Array(n);
  6420. for (let i=0; i<ndiv2; i++) {
  6421. out[i] = PF.F.add(p1[i], PF.F.mul(PF.roots[bits][i], p2[i]));
  6422. out[i+ndiv2] = PF.F.sub(p1[i], PF.F.mul(PF.roots[bits][i], p2[i]));
  6423. }
  6424. return out;
  6425. }
  6426. module.exports = PolField;
  6427. },{}],22:[function(require,module,exports){
  6428. const supportsNativeBigInt = typeof BigInt === "function";
  6429. if (supportsNativeBigInt) {
  6430. module.exports = require("./scalar_native.js");
  6431. } else {
  6432. module.exports = require("./scalar_bigint.js");
  6433. }
  6434. },{"./scalar_bigint.js":23,"./scalar_native.js":24}],23:[function(require,module,exports){
  6435. const bigInt = require("big-integer");
  6436. const assert = require("assert");
  6437. module.exports.fromString = function fromString(s, radix) {
  6438. return bigInt(s,radix);
  6439. };
  6440. module.exports.fromArray = function fromArray(a, radix) {
  6441. return bigInt.fromArray(a, radix);
  6442. };
  6443. module.exports.bitLength = function (a) {
  6444. return bigInt(a).bitLength();
  6445. };
  6446. module.exports.isNegative = function (a) {
  6447. return bigInt(a).isNegative();
  6448. };
  6449. module.exports.isZero = function (a) {
  6450. return bigInt(a).isZero();
  6451. };
  6452. module.exports.shiftLeft = function (a, n) {
  6453. return bigInt(a).shiftLeft(n);
  6454. };
  6455. module.exports.shiftRight = function (a, n) {
  6456. return bigInt(a).shiftRight(n);
  6457. };
  6458. module.exports.shl = module.exports.shiftLeft;
  6459. module.exports.shr = module.exports.shiftRight;
  6460. module.exports.isOdd = function (a) {
  6461. return bigInt(a).isOdd();
  6462. };
  6463. module.exports.naf = function naf(n) {
  6464. let E = bigInt(n);
  6465. const res = [];
  6466. while (E.gt(bigInt.zero)) {
  6467. if (E.isOdd()) {
  6468. const z = 2 - E.mod(4).toJSNumber();
  6469. res.push( z );
  6470. E = E.minus(z);
  6471. } else {
  6472. res.push( 0 );
  6473. }
  6474. E = E.shiftRight(1);
  6475. }
  6476. return res;
  6477. };
  6478. module.exports.bits = function naf(n) {
  6479. let E = bigInt(n);
  6480. const res = [];
  6481. while (E.gt(bigInt.zero)) {
  6482. if (E.isOdd()) {
  6483. res.push(1);
  6484. } else {
  6485. res.push( 0 );
  6486. }
  6487. E = E.shiftRight(1);
  6488. }
  6489. return res;
  6490. };
  6491. module.exports.toNumber = function(s) {
  6492. assert(s.lt(bigInt("100000000", 16)));
  6493. return s.toJSNumber();
  6494. };
  6495. module.exports.toArray = function(s, radix) {
  6496. return bigInt(s).toArray(radix);
  6497. };
  6498. module.exports.e = function(a) {
  6499. return bigInt(a);
  6500. };
  6501. module.exports.add = function(a, b) {
  6502. return bigInt(a).add(bigInt(b));
  6503. };
  6504. module.exports.sub = function(a, b) {
  6505. return bigInt(a).minus(bigInt(b));
  6506. };
  6507. module.exports.neg = function(a) {
  6508. return bigInt.zero.minus(bigInt(a));
  6509. };
  6510. module.exports.mul = function(a, b) {
  6511. return bigInt(a).times(bigInt(b));
  6512. };
  6513. module.exports.square = function(a) {
  6514. return bigInt(a).square();
  6515. };
  6516. module.exports.div = function(a, b) {
  6517. return bigInt(a).divide(bigInt(b));
  6518. };
  6519. module.exports.mod = function(a, b) {
  6520. return bigInt(a).mod(bigInt(b));
  6521. };
  6522. module.exports.eq = function(a, b) {
  6523. return bigInt(a).eq(bigInt(b));
  6524. };
  6525. module.exports.neq = function(a, b) {
  6526. return bigInt(a).neq(bigInt(b));
  6527. };
  6528. module.exports.lt = function(a, b) {
  6529. return bigInt(a).lt(bigInt(b));
  6530. };
  6531. module.exports.gt = function(a, b) {
  6532. return bigInt(a).gt(bigInt(b));
  6533. };
  6534. module.exports.leq = function(a, b) {
  6535. return bigInt(a).leq(bigInt(b));
  6536. };
  6537. module.exports.geq = function(a, b) {
  6538. return bigInt(a).geq(bigInt(b));
  6539. };
  6540. module.exports.band = function(a, b) {
  6541. return bigInt(a).and(bigInt(b));
  6542. };
  6543. module.exports.bor = function(a, b) {
  6544. return bigInt(a).or(bigInt(b));
  6545. };
  6546. module.exports.bxor = function(a, b) {
  6547. return bigInt(a).xor(bigInt(b));
  6548. };
  6549. module.exports.band = function(a, b) {
  6550. return (!bigInt(a).isZero()) && (!bigInt(b).isZero());
  6551. };
  6552. module.exports.bor = function(a, b) {
  6553. return (!bigInt(a).isZero()) || (!bigInt(b).isZero());
  6554. };
  6555. module.exports.bnot = function(a) {
  6556. return bigInt(a).isZero();
  6557. };
  6558. },{"assert":1,"big-integer":6}],24:[function(require,module,exports){
  6559. /* global BigInt */
  6560. const assert = require("assert");
  6561. const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4];
  6562. module.exports.fromString = function fromString(s, radix) {
  6563. if ((!radix)||(radix==10)) {
  6564. return BigInt(s);
  6565. } else if (radix==16) {
  6566. return BigInt("0x"+s);
  6567. }
  6568. };
  6569. module.exports.fromArray = function fromArray(a, radix) {
  6570. let acc =0n;
  6571. radix = BigInt(radix);
  6572. for (let i=0; i<a.length; i++) {
  6573. acc = acc*radix + BigInt(a[i]);
  6574. }
  6575. return acc;
  6576. };
  6577. module.exports.bitLength = function (a) {
  6578. const aS =a.toString(16);
  6579. return (aS.length-1)*4 +hexLen[aS[0]];
  6580. };
  6581. module.exports.isNegative = function (a) {
  6582. return BigInt(a) < 0n;
  6583. };
  6584. module.exports.isZero = function (a) {
  6585. return !a;
  6586. };
  6587. module.exports.shiftLeft = function (a, n) {
  6588. return BigInt(a) << BigInt(n);
  6589. };
  6590. module.exports.shiftRight = function (a, n) {
  6591. return BigInt(a) >> BigInt(n);
  6592. };
  6593. module.exports.shl = module.exports.shiftLeft;
  6594. module.exports.shr = module.exports.shiftRight;
  6595. module.exports.isOdd = function (a) {
  6596. return (BigInt(a) & 1n) == 1n;
  6597. };
  6598. module.exports.naf = function naf(n) {
  6599. let E = BigInt(n);
  6600. const res = [];
  6601. while (E) {
  6602. if (E & 1n) {
  6603. const z = 2 - Number(E % 4n);
  6604. res.push( z );
  6605. E = E - BigInt(z);
  6606. } else {
  6607. res.push( 0 );
  6608. }
  6609. E = E >> 1n;
  6610. }
  6611. return res;
  6612. };
  6613. module.exports.bits = function naf(n) {
  6614. let E = BigInt(n);
  6615. const res = [];
  6616. while (E) {
  6617. if (E & 1n) {
  6618. res.push(1);
  6619. } else {
  6620. res.push( 0 );
  6621. }
  6622. E = E >> 1n;
  6623. }
  6624. return res;
  6625. };
  6626. module.exports.toNumber = function(s) {
  6627. assert(s<0x100000000n);
  6628. return Number(s);
  6629. };
  6630. module.exports.toArray = function(s, radix) {
  6631. const res = [];
  6632. let rem = BigInt(s);
  6633. radix = BigInt(radix);
  6634. while (rem) {
  6635. res.unshift( Number(rem % radix));
  6636. rem = rem / radix;
  6637. }
  6638. return res;
  6639. };
  6640. module.exports.e = function(a) {
  6641. return BigInt(a);
  6642. };
  6643. module.exports.add = function(a, b) {
  6644. return BigInt(a) + BigInt(b);
  6645. };
  6646. module.exports.sub = function(a, b) {
  6647. return BigInt(a) - BigInt(b);
  6648. };
  6649. module.exports.neg = function(a) {
  6650. return -BigInt(a);
  6651. };
  6652. module.exports.mul = function(a, b) {
  6653. return BigInt(a) * BigInt(b);
  6654. };
  6655. module.exports.square = function(a) {
  6656. return BigInt(a) * BigInt(a);
  6657. };
  6658. module.exports.div = function(a, b) {
  6659. return BigInt(a) / BigInt(b);
  6660. };
  6661. module.exports.mod = function(a, b) {
  6662. return BigInt(a) % BigInt(b);
  6663. };
  6664. module.exports.eq = function(a, b) {
  6665. return BigInt(a) == BigInt(b);
  6666. };
  6667. module.exports.neq = function(a, b) {
  6668. return BigInt(a) != BigInt(b);
  6669. };
  6670. module.exports.lt = function(a, b) {
  6671. return BigInt(a) < BigInt(b);
  6672. };
  6673. module.exports.gt = function(a, b) {
  6674. return BigInt(a) > BigInt(b);
  6675. };
  6676. module.exports.leq = function(a, b) {
  6677. return BigInt(a) <= BigInt(b);
  6678. };
  6679. module.exports.geq = function(a, b) {
  6680. return BigInt(a) >= BigInt(b);
  6681. };
  6682. module.exports.band = function(a, b) {
  6683. return BigInt(a) & BigInt(b);
  6684. };
  6685. module.exports.bor = function(a, b) {
  6686. return BigInt(a) | BigInt(b);
  6687. };
  6688. module.exports.bxor = function(a, b) {
  6689. return BigInt(a) ^ BigInt(b);
  6690. };
  6691. module.exports.band = function(a, b) {
  6692. return BigInt(a) && BigInt(b);
  6693. };
  6694. module.exports.bor = function(a, b) {
  6695. return BigInt(a) || BigInt(b);
  6696. };
  6697. module.exports.bnot = function(a) {
  6698. return !BigInt(a);
  6699. };
  6700. },{"assert":1}],25:[function(require,module,exports){
  6701. const supportsNativeBigInt = typeof BigInt === "function";
  6702. if (supportsNativeBigInt) {
  6703. module.exports = require("./utils_native.js");
  6704. } else {
  6705. module.exports = require("./utils_bigint.js");
  6706. }
  6707. },{"./utils_bigint.js":26,"./utils_native.js":27}],26:[function(require,module,exports){
  6708. (function (Buffer){
  6709. const assert = require("assert");
  6710. const bigInt = require("big-integer");
  6711. module.exports.stringifyBigInts = function stringifyBigInts(o) {
  6712. if ((typeof(o) == "bigint") || o.eq !== undefined) {
  6713. return o.toString(10);
  6714. } else if (Array.isArray(o)) {
  6715. return o.map(stringifyBigInts);
  6716. } else if (typeof o == "object") {
  6717. const res = {};
  6718. for (let k in o) {
  6719. res[k] = stringifyBigInts(o[k]);
  6720. }
  6721. return res;
  6722. } else {
  6723. return o;
  6724. }
  6725. };
  6726. module.exports.unstringifyBigInts = function unstringifyBigInts(o) {
  6727. if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
  6728. return bigInt(o);
  6729. } else if (Array.isArray(o)) {
  6730. return o.map(unstringifyBigInts);
  6731. } else if (typeof o == "object") {
  6732. const res = {};
  6733. for (let k in o) {
  6734. res[k] = unstringifyBigInts(o[k]);
  6735. }
  6736. return res;
  6737. } else {
  6738. return o;
  6739. }
  6740. };
  6741. module.exports.beBuff2int = function beBuff2int(buff) {
  6742. let res = bigInt.zero;
  6743. for (let i=0; i<buff.length; i++) {
  6744. const n = bigInt(buff[buff.length - i - 1]);
  6745. res = res.add(n.shiftLeft(i*8));
  6746. }
  6747. return res;
  6748. };
  6749. module.exports.beInt2Buff = function beInt2Buff(n, len) {
  6750. let r = n;
  6751. let o =len-1;
  6752. const buff = Buffer.alloc(len);
  6753. while ((r.gt(bigInt.zero))&&(o>=0)) {
  6754. let c = Number(r.and(bigInt("255")));
  6755. buff[o] = c;
  6756. o--;
  6757. r = r.shiftRight(8);
  6758. }
  6759. assert(r.eq(bigInt.zero));
  6760. return buff;
  6761. };
  6762. module.exports.leBuff2int = function leBuff2int (buff) {
  6763. let res = bigInt.zero;
  6764. for (let i=0; i<buff.length; i++) {
  6765. const n = bigInt(buff[i]);
  6766. res = res.add(n.shiftLeft(i*8));
  6767. }
  6768. return res;
  6769. };
  6770. module.exports.leInt2Buff = function leInt2Buff(n, len) {
  6771. let r = n;
  6772. let o =0;
  6773. const buff = Buffer.alloc(len);
  6774. while ((r.gt(bigInt.zero))&&(o<buff.length)) {
  6775. let c = Number(r.and(bigInt(255)));
  6776. buff[o] = c;
  6777. o++;
  6778. r = r.shiftRight(8);
  6779. }
  6780. assert(r.eq(bigInt.zero));
  6781. return buff;
  6782. };
  6783. }).call(this,require("buffer").Buffer)
  6784. },{"assert":1,"big-integer":6,"buffer":8}],27:[function(require,module,exports){
  6785. (function (Buffer){
  6786. /* global BigInt */
  6787. const assert = require("assert");
  6788. module.exports.stringifyBigInts = function stringifyBigInts(o) {
  6789. if ((typeof(o) == "bigint") || o.eq !== undefined) {
  6790. return o.toString(10);
  6791. } else if (Array.isArray(o)) {
  6792. return o.map(stringifyBigInts);
  6793. } else if (typeof o == "object") {
  6794. const res = {};
  6795. for (let k in o) {
  6796. res[k] = stringifyBigInts(o[k]);
  6797. }
  6798. return res;
  6799. } else {
  6800. return o;
  6801. }
  6802. };
  6803. module.exports.unstringifyBigInts = function unstringifyBigInts(o) {
  6804. if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) )) {
  6805. return BigInt(o);
  6806. } else if (Array.isArray(o)) {
  6807. return o.map(unstringifyBigInts);
  6808. } else if (typeof o == "object") {
  6809. const res = {};
  6810. for (let k in o) {
  6811. res[k] = unstringifyBigInts(o[k]);
  6812. }
  6813. return res;
  6814. } else {
  6815. return o;
  6816. }
  6817. };
  6818. module.exports.beBuff2int = function beBuff2int(buff) {
  6819. let res = 0n;
  6820. let i = buff.length;
  6821. while (i>0) {
  6822. if (i >= 4) {
  6823. i -= 4;
  6824. res += BigInt(buff.readUInt32BE(i)) << BigInt( i*8);
  6825. } else if (i >= 2) {
  6826. i -= 2;
  6827. res += BigInt(buff.readUInt16BE(i)) << BigInt( i*8);
  6828. } else {
  6829. i -= 1;
  6830. res += BigInt(buff.readUInt8(i)) << BigInt( i*8);
  6831. }
  6832. }
  6833. return res;
  6834. };
  6835. module.exports.beInt2Buff = function beInt2Buff(n, len) {
  6836. let r = n;
  6837. const buff = Buffer.alloc(len);
  6838. let o = len;
  6839. while (o > 0) {
  6840. if (o-4 >= 0) {
  6841. o -= 4;
  6842. buff.writeUInt32BE(Number(r & 0xFFFFFFFFn), o);
  6843. r = r >> 32n;
  6844. } else if (o-2 >= 0) {
  6845. o -= 2;
  6846. buff.writeUInt16BE(Number(r & 0xFFFFn), o);
  6847. r = r >> 16n;
  6848. } else {
  6849. o -= 1;
  6850. buff.writeUInt8(Number(r & 0xFFn),o );
  6851. r = r >> 8n;
  6852. }
  6853. }
  6854. assert(r == 0n);
  6855. return buff;
  6856. };
  6857. module.exports.leBuff2int = function leBuff2int(buff) {
  6858. let res = 0n;
  6859. let i = 0;
  6860. while (i<buff.length) {
  6861. if (i + 4 <= buff.length) {
  6862. res += BigInt(buff.readUInt32LE(i)) << BigInt( i*8);
  6863. i += 4;
  6864. } else if (i + 4 <= buff.length) {
  6865. res += BigInt(buff.readUInt16LE(i)) << BigInt( i*8);
  6866. i += 2;
  6867. } else {
  6868. res += BigInt(buff.readUInt8(i)) << BigInt( i*8);
  6869. i += 1;
  6870. }
  6871. }
  6872. return res;
  6873. };
  6874. module.exports.leInt2Buff = function leInt2Buff(n, len) {
  6875. let r = n;
  6876. const buff = Buffer.alloc(len);
  6877. let o = 0;
  6878. while (o < len) {
  6879. if (o+4 <= len) {
  6880. buff.writeUInt32LE(Number(r & 0xFFFFFFFFn), o );
  6881. o += 4;
  6882. r = r >> 32n;
  6883. } else if (o+2 <= len) {
  6884. buff.writeUInt16LE(Number(r & 0xFFFFn), o );
  6885. o += 2;
  6886. r = r >> 16n;
  6887. } else {
  6888. buff.writeUInt8(Number(r & 0xFFn), o );
  6889. o += 1;
  6890. r = r >> 8n;
  6891. }
  6892. }
  6893. assert(r == 0n);
  6894. return buff;
  6895. };
  6896. }).call(this,require("buffer").Buffer)
  6897. },{"assert":1,"buffer":8}],28:[function(require,module,exports){
  6898. exports.read = function (buffer, offset, isLE, mLen, nBytes) {
  6899. var e, m
  6900. var eLen = (nBytes * 8) - mLen - 1
  6901. var eMax = (1 << eLen) - 1
  6902. var eBias = eMax >> 1
  6903. var nBits = -7
  6904. var i = isLE ? (nBytes - 1) : 0
  6905. var d = isLE ? -1 : 1
  6906. var s = buffer[offset + i]
  6907. i += d
  6908. e = s & ((1 << (-nBits)) - 1)
  6909. s >>= (-nBits)
  6910. nBits += eLen
  6911. for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  6912. m = e & ((1 << (-nBits)) - 1)
  6913. e >>= (-nBits)
  6914. nBits += mLen
  6915. for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
  6916. if (e === 0) {
  6917. e = 1 - eBias
  6918. } else if (e === eMax) {
  6919. return m ? NaN : ((s ? -1 : 1) * Infinity)
  6920. } else {
  6921. m = m + Math.pow(2, mLen)
  6922. e = e - eBias
  6923. }
  6924. return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
  6925. }
  6926. exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
  6927. var e, m, c
  6928. var eLen = (nBytes * 8) - mLen - 1
  6929. var eMax = (1 << eLen) - 1
  6930. var eBias = eMax >> 1
  6931. var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
  6932. var i = isLE ? 0 : (nBytes - 1)
  6933. var d = isLE ? 1 : -1
  6934. var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
  6935. value = Math.abs(value)
  6936. if (isNaN(value) || value === Infinity) {
  6937. m = isNaN(value) ? 1 : 0
  6938. e = eMax
  6939. } else {
  6940. e = Math.floor(Math.log(value) / Math.LN2)
  6941. if (value * (c = Math.pow(2, -e)) < 1) {
  6942. e--
  6943. c *= 2
  6944. }
  6945. if (e + eBias >= 1) {
  6946. value += rt / c
  6947. } else {
  6948. value += rt * Math.pow(2, 1 - eBias)
  6949. }
  6950. if (value * c >= 2) {
  6951. e++
  6952. c /= 2
  6953. }
  6954. if (e + eBias >= eMax) {
  6955. m = 0
  6956. e = eMax
  6957. } else if (e + eBias >= 1) {
  6958. m = ((value * c) - 1) * Math.pow(2, mLen)
  6959. e = e + eBias
  6960. } else {
  6961. m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
  6962. e = 0
  6963. }
  6964. }
  6965. for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
  6966. e = (e << mLen) | m
  6967. eLen += mLen
  6968. for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
  6969. buffer[offset + i - d] |= s * 128
  6970. }
  6971. },{}],29:[function(require,module,exports){
  6972. if (typeof Object.create === 'function') {
  6973. // implementation from standard node.js 'util' module
  6974. module.exports = function inherits(ctor, superCtor) {
  6975. if (superCtor) {
  6976. ctor.super_ = superCtor
  6977. ctor.prototype = Object.create(superCtor.prototype, {
  6978. constructor: {
  6979. value: ctor,
  6980. enumerable: false,
  6981. writable: true,
  6982. configurable: true
  6983. }
  6984. })
  6985. }
  6986. };
  6987. } else {
  6988. // old school shim for old browsers
  6989. module.exports = function inherits(ctor, superCtor) {
  6990. if (superCtor) {
  6991. ctor.super_ = superCtor
  6992. var TempCtor = function () {}
  6993. TempCtor.prototype = superCtor.prototype
  6994. ctor.prototype = new TempCtor()
  6995. ctor.prototype.constructor = ctor
  6996. }
  6997. }
  6998. }
  6999. },{}],30:[function(require,module,exports){
  7000. /*!
  7001. * Determine if an object is a Buffer
  7002. *
  7003. * @author Feross Aboukhadijeh <https://feross.org>
  7004. * @license MIT
  7005. */
  7006. // The _isBuffer check is for Safari 5-7 support, because it's missing
  7007. // Object.prototype.constructor. Remove this eventually
  7008. module.exports = function (obj) {
  7009. return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
  7010. }
  7011. function isBuffer (obj) {
  7012. return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
  7013. }
  7014. // For Node v0.10 support. Remove this eventually.
  7015. function isSlowBuffer (obj) {
  7016. return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
  7017. }
  7018. },{}],31:[function(require,module,exports){
  7019. var toString = {}.toString;
  7020. module.exports = Array.isArray || function (arr) {
  7021. return toString.call(arr) == '[object Array]';
  7022. };
  7023. },{}],32:[function(require,module,exports){
  7024. module.exports = require('./lib/api')(require('./lib/keccak'))
  7025. },{"./lib/api":33,"./lib/keccak":37}],33:[function(require,module,exports){
  7026. const createKeccak = require('./keccak')
  7027. const createShake = require('./shake')
  7028. module.exports = function (KeccakState) {
  7029. const Keccak = createKeccak(KeccakState)
  7030. const Shake = createShake(KeccakState)
  7031. return function (algorithm, options) {
  7032. const hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm
  7033. switch (hash) {
  7034. case 'keccak224': return new Keccak(1152, 448, null, 224, options)
  7035. case 'keccak256': return new Keccak(1088, 512, null, 256, options)
  7036. case 'keccak384': return new Keccak(832, 768, null, 384, options)
  7037. case 'keccak512': return new Keccak(576, 1024, null, 512, options)
  7038. case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options)
  7039. case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options)
  7040. case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options)
  7041. case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options)
  7042. case 'shake128': return new Shake(1344, 256, 0x1f, options)
  7043. case 'shake256': return new Shake(1088, 512, 0x1f, options)
  7044. default: throw new Error('Invald algorithm: ' + algorithm)
  7045. }
  7046. }
  7047. }
  7048. },{"./keccak":34,"./shake":35}],34:[function(require,module,exports){
  7049. (function (Buffer){
  7050. const { Transform } = require('stream')
  7051. module.exports = (KeccakState) => class Keccak extends Transform {
  7052. constructor (rate, capacity, delimitedSuffix, hashBitLength, options) {
  7053. super(options)
  7054. this._rate = rate
  7055. this._capacity = capacity
  7056. this._delimitedSuffix = delimitedSuffix
  7057. this._hashBitLength = hashBitLength
  7058. this._options = options
  7059. this._state = new KeccakState()
  7060. this._state.initialize(rate, capacity)
  7061. this._finalized = false
  7062. }
  7063. _transform (chunk, encoding, callback) {
  7064. let error = null
  7065. try {
  7066. this.update(chunk, encoding)
  7067. } catch (err) {
  7068. error = err
  7069. }
  7070. callback(error)
  7071. }
  7072. _flush (callback) {
  7073. let error = null
  7074. try {
  7075. this.push(this.digest())
  7076. } catch (err) {
  7077. error = err
  7078. }
  7079. callback(error)
  7080. }
  7081. update (data, encoding) {
  7082. if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
  7083. if (this._finalized) throw new Error('Digest already called')
  7084. if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
  7085. this._state.absorb(data)
  7086. return this
  7087. }
  7088. digest (encoding) {
  7089. if (this._finalized) throw new Error('Digest already called')
  7090. this._finalized = true
  7091. if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix)
  7092. let digest = this._state.squeeze(this._hashBitLength / 8)
  7093. if (encoding !== undefined) digest = digest.toString(encoding)
  7094. this._resetState()
  7095. return digest
  7096. }
  7097. // remove result from memory
  7098. _resetState () {
  7099. this._state.initialize(this._rate, this._capacity)
  7100. return this
  7101. }
  7102. // because sometimes we need hash right now and little later
  7103. _clone () {
  7104. const clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options)
  7105. this._state.copy(clone._state)
  7106. clone._finalized = this._finalized
  7107. return clone
  7108. }
  7109. }
  7110. }).call(this,require("buffer").Buffer)
  7111. },{"buffer":8,"stream":51}],35:[function(require,module,exports){
  7112. (function (Buffer){
  7113. const { Transform } = require('stream')
  7114. module.exports = (KeccakState) => class Shake extends Transform {
  7115. constructor (rate, capacity, delimitedSuffix, options) {
  7116. super(options)
  7117. this._rate = rate
  7118. this._capacity = capacity
  7119. this._delimitedSuffix = delimitedSuffix
  7120. this._options = options
  7121. this._state = new KeccakState()
  7122. this._state.initialize(rate, capacity)
  7123. this._finalized = false
  7124. }
  7125. _transform (chunk, encoding, callback) {
  7126. let error = null
  7127. try {
  7128. this.update(chunk, encoding)
  7129. } catch (err) {
  7130. error = err
  7131. }
  7132. callback(error)
  7133. }
  7134. _flush () {}
  7135. _read (size) {
  7136. this.push(this.squeeze(size))
  7137. }
  7138. update (data, encoding) {
  7139. if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
  7140. if (this._finalized) throw new Error('Squeeze already called')
  7141. if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
  7142. this._state.absorb(data)
  7143. return this
  7144. }
  7145. squeeze (dataByteLength, encoding) {
  7146. if (!this._finalized) {
  7147. this._finalized = true
  7148. this._state.absorbLastFewBits(this._delimitedSuffix)
  7149. }
  7150. let data = this._state.squeeze(dataByteLength)
  7151. if (encoding !== undefined) data = data.toString(encoding)
  7152. return data
  7153. }
  7154. _resetState () {
  7155. this._state.initialize(this._rate, this._capacity)
  7156. return this
  7157. }
  7158. _clone () {
  7159. const clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options)
  7160. this._state.copy(clone._state)
  7161. clone._finalized = this._finalized
  7162. return clone
  7163. }
  7164. }
  7165. }).call(this,require("buffer").Buffer)
  7166. },{"buffer":8,"stream":51}],36:[function(require,module,exports){
  7167. const P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]
  7168. exports.p1600 = function (s) {
  7169. for (let round = 0; round < 24; ++round) {
  7170. // theta
  7171. const lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]
  7172. const hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]
  7173. const lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]
  7174. const hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]
  7175. const lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]
  7176. const hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]
  7177. const lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]
  7178. const hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]
  7179. const lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]
  7180. const hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]
  7181. let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31)
  7182. let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31)
  7183. const t1slo0 = s[0] ^ lo
  7184. const t1shi0 = s[1] ^ hi
  7185. const t1slo5 = s[10] ^ lo
  7186. const t1shi5 = s[11] ^ hi
  7187. const t1slo10 = s[20] ^ lo
  7188. const t1shi10 = s[21] ^ hi
  7189. const t1slo15 = s[30] ^ lo
  7190. const t1shi15 = s[31] ^ hi
  7191. const t1slo20 = s[40] ^ lo
  7192. const t1shi20 = s[41] ^ hi
  7193. lo = lo0 ^ (lo2 << 1 | hi2 >>> 31)
  7194. hi = hi0 ^ (hi2 << 1 | lo2 >>> 31)
  7195. const t1slo1 = s[2] ^ lo
  7196. const t1shi1 = s[3] ^ hi
  7197. const t1slo6 = s[12] ^ lo
  7198. const t1shi6 = s[13] ^ hi
  7199. const t1slo11 = s[22] ^ lo
  7200. const t1shi11 = s[23] ^ hi
  7201. const t1slo16 = s[32] ^ lo
  7202. const t1shi16 = s[33] ^ hi
  7203. const t1slo21 = s[42] ^ lo
  7204. const t1shi21 = s[43] ^ hi
  7205. lo = lo1 ^ (lo3 << 1 | hi3 >>> 31)
  7206. hi = hi1 ^ (hi3 << 1 | lo3 >>> 31)
  7207. const t1slo2 = s[4] ^ lo
  7208. const t1shi2 = s[5] ^ hi
  7209. const t1slo7 = s[14] ^ lo
  7210. const t1shi7 = s[15] ^ hi
  7211. const t1slo12 = s[24] ^ lo
  7212. const t1shi12 = s[25] ^ hi
  7213. const t1slo17 = s[34] ^ lo
  7214. const t1shi17 = s[35] ^ hi
  7215. const t1slo22 = s[44] ^ lo
  7216. const t1shi22 = s[45] ^ hi
  7217. lo = lo2 ^ (lo4 << 1 | hi4 >>> 31)
  7218. hi = hi2 ^ (hi4 << 1 | lo4 >>> 31)
  7219. const t1slo3 = s[6] ^ lo
  7220. const t1shi3 = s[7] ^ hi
  7221. const t1slo8 = s[16] ^ lo
  7222. const t1shi8 = s[17] ^ hi
  7223. const t1slo13 = s[26] ^ lo
  7224. const t1shi13 = s[27] ^ hi
  7225. const t1slo18 = s[36] ^ lo
  7226. const t1shi18 = s[37] ^ hi
  7227. const t1slo23 = s[46] ^ lo
  7228. const t1shi23 = s[47] ^ hi
  7229. lo = lo3 ^ (lo0 << 1 | hi0 >>> 31)
  7230. hi = hi3 ^ (hi0 << 1 | lo0 >>> 31)
  7231. const t1slo4 = s[8] ^ lo
  7232. const t1shi4 = s[9] ^ hi
  7233. const t1slo9 = s[18] ^ lo
  7234. const t1shi9 = s[19] ^ hi
  7235. const t1slo14 = s[28] ^ lo
  7236. const t1shi14 = s[29] ^ hi
  7237. const t1slo19 = s[38] ^ lo
  7238. const t1shi19 = s[39] ^ hi
  7239. const t1slo24 = s[48] ^ lo
  7240. const t1shi24 = s[49] ^ hi
  7241. // rho & pi
  7242. const t2slo0 = t1slo0
  7243. const t2shi0 = t1shi0
  7244. const t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28)
  7245. const t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28)
  7246. const t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29)
  7247. const t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29)
  7248. const t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23)
  7249. const t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23)
  7250. const t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14)
  7251. const t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14)
  7252. const t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31)
  7253. const t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31)
  7254. const t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20)
  7255. const t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20)
  7256. const t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22)
  7257. const t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22)
  7258. const t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19)
  7259. const t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19)
  7260. const t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30)
  7261. const t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30)
  7262. const t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2)
  7263. const t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2)
  7264. const t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26)
  7265. const t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26)
  7266. const t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21)
  7267. const t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21)
  7268. const t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17)
  7269. const t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17)
  7270. const t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3)
  7271. const t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3)
  7272. const t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4)
  7273. const t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4)
  7274. const t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9)
  7275. const t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9)
  7276. const t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7)
  7277. const t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7)
  7278. const t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11)
  7279. const t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11)
  7280. const t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8)
  7281. const t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8)
  7282. const t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5)
  7283. const t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5)
  7284. const t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12)
  7285. const t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12)
  7286. const t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25)
  7287. const t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25)
  7288. const t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24)
  7289. const t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24)
  7290. const t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18)
  7291. const t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18)
  7292. // chi
  7293. s[0] = t2slo0 ^ (~t2slo1 & t2slo2)
  7294. s[1] = t2shi0 ^ (~t2shi1 & t2shi2)
  7295. s[10] = t2slo5 ^ (~t2slo6 & t2slo7)
  7296. s[11] = t2shi5 ^ (~t2shi6 & t2shi7)
  7297. s[20] = t2slo10 ^ (~t2slo11 & t2slo12)
  7298. s[21] = t2shi10 ^ (~t2shi11 & t2shi12)
  7299. s[30] = t2slo15 ^ (~t2slo16 & t2slo17)
  7300. s[31] = t2shi15 ^ (~t2shi16 & t2shi17)
  7301. s[40] = t2slo20 ^ (~t2slo21 & t2slo22)
  7302. s[41] = t2shi20 ^ (~t2shi21 & t2shi22)
  7303. s[2] = t2slo1 ^ (~t2slo2 & t2slo3)
  7304. s[3] = t2shi1 ^ (~t2shi2 & t2shi3)
  7305. s[12] = t2slo6 ^ (~t2slo7 & t2slo8)
  7306. s[13] = t2shi6 ^ (~t2shi7 & t2shi8)
  7307. s[22] = t2slo11 ^ (~t2slo12 & t2slo13)
  7308. s[23] = t2shi11 ^ (~t2shi12 & t2shi13)
  7309. s[32] = t2slo16 ^ (~t2slo17 & t2slo18)
  7310. s[33] = t2shi16 ^ (~t2shi17 & t2shi18)
  7311. s[42] = t2slo21 ^ (~t2slo22 & t2slo23)
  7312. s[43] = t2shi21 ^ (~t2shi22 & t2shi23)
  7313. s[4] = t2slo2 ^ (~t2slo3 & t2slo4)
  7314. s[5] = t2shi2 ^ (~t2shi3 & t2shi4)
  7315. s[14] = t2slo7 ^ (~t2slo8 & t2slo9)
  7316. s[15] = t2shi7 ^ (~t2shi8 & t2shi9)
  7317. s[24] = t2slo12 ^ (~t2slo13 & t2slo14)
  7318. s[25] = t2shi12 ^ (~t2shi13 & t2shi14)
  7319. s[34] = t2slo17 ^ (~t2slo18 & t2slo19)
  7320. s[35] = t2shi17 ^ (~t2shi18 & t2shi19)
  7321. s[44] = t2slo22 ^ (~t2slo23 & t2slo24)
  7322. s[45] = t2shi22 ^ (~t2shi23 & t2shi24)
  7323. s[6] = t2slo3 ^ (~t2slo4 & t2slo0)
  7324. s[7] = t2shi3 ^ (~t2shi4 & t2shi0)
  7325. s[16] = t2slo8 ^ (~t2slo9 & t2slo5)
  7326. s[17] = t2shi8 ^ (~t2shi9 & t2shi5)
  7327. s[26] = t2slo13 ^ (~t2slo14 & t2slo10)
  7328. s[27] = t2shi13 ^ (~t2shi14 & t2shi10)
  7329. s[36] = t2slo18 ^ (~t2slo19 & t2slo15)
  7330. s[37] = t2shi18 ^ (~t2shi19 & t2shi15)
  7331. s[46] = t2slo23 ^ (~t2slo24 & t2slo20)
  7332. s[47] = t2shi23 ^ (~t2shi24 & t2shi20)
  7333. s[8] = t2slo4 ^ (~t2slo0 & t2slo1)
  7334. s[9] = t2shi4 ^ (~t2shi0 & t2shi1)
  7335. s[18] = t2slo9 ^ (~t2slo5 & t2slo6)
  7336. s[19] = t2shi9 ^ (~t2shi5 & t2shi6)
  7337. s[28] = t2slo14 ^ (~t2slo10 & t2slo11)
  7338. s[29] = t2shi14 ^ (~t2shi10 & t2shi11)
  7339. s[38] = t2slo19 ^ (~t2slo15 & t2slo16)
  7340. s[39] = t2shi19 ^ (~t2shi15 & t2shi16)
  7341. s[48] = t2slo24 ^ (~t2slo20 & t2slo21)
  7342. s[49] = t2shi24 ^ (~t2shi20 & t2shi21)
  7343. // iota
  7344. s[0] ^= P1600_ROUND_CONSTANTS[round * 2]
  7345. s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]
  7346. }
  7347. }
  7348. },{}],37:[function(require,module,exports){
  7349. (function (Buffer){
  7350. const keccakState = require('./keccak-state-unroll')
  7351. function Keccak () {
  7352. // much faster than `new Array(50)`
  7353. this.state = [
  7354. 0, 0, 0, 0, 0,
  7355. 0, 0, 0, 0, 0,
  7356. 0, 0, 0, 0, 0,
  7357. 0, 0, 0, 0, 0,
  7358. 0, 0, 0, 0, 0
  7359. ]
  7360. this.blockSize = null
  7361. this.count = 0
  7362. this.squeezing = false
  7363. }
  7364. Keccak.prototype.initialize = function (rate, capacity) {
  7365. for (let i = 0; i < 50; ++i) this.state[i] = 0
  7366. this.blockSize = rate / 8
  7367. this.count = 0
  7368. this.squeezing = false
  7369. }
  7370. Keccak.prototype.absorb = function (data) {
  7371. for (let i = 0; i < data.length; ++i) {
  7372. this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4))
  7373. this.count += 1
  7374. if (this.count === this.blockSize) {
  7375. keccakState.p1600(this.state)
  7376. this.count = 0
  7377. }
  7378. }
  7379. }
  7380. Keccak.prototype.absorbLastFewBits = function (bits) {
  7381. this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4))
  7382. if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state)
  7383. this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4))
  7384. keccakState.p1600(this.state)
  7385. this.count = 0
  7386. this.squeezing = true
  7387. }
  7388. Keccak.prototype.squeeze = function (length) {
  7389. if (!this.squeezing) this.absorbLastFewBits(0x01)
  7390. const output = Buffer.alloc(length)
  7391. for (let i = 0; i < length; ++i) {
  7392. output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff
  7393. this.count += 1
  7394. if (this.count === this.blockSize) {
  7395. keccakState.p1600(this.state)
  7396. this.count = 0
  7397. }
  7398. }
  7399. return output
  7400. }
  7401. Keccak.prototype.copy = function (dest) {
  7402. for (let i = 0; i < 50; ++i) dest.state[i] = this.state[i]
  7403. dest.blockSize = this.blockSize
  7404. dest.count = this.count
  7405. dest.squeezing = this.squeezing
  7406. }
  7407. module.exports = Keccak
  7408. }).call(this,require("buffer").Buffer)
  7409. },{"./keccak-state-unroll":36,"buffer":8}],38:[function(require,module,exports){
  7410. /*
  7411. object-assign
  7412. (c) Sindre Sorhus
  7413. @license MIT
  7414. */
  7415. 'use strict';
  7416. /* eslint-disable no-unused-vars */
  7417. var getOwnPropertySymbols = Object.getOwnPropertySymbols;
  7418. var hasOwnProperty = Object.prototype.hasOwnProperty;
  7419. var propIsEnumerable = Object.prototype.propertyIsEnumerable;
  7420. function toObject(val) {
  7421. if (val === null || val === undefined) {
  7422. throw new TypeError('Object.assign cannot be called with null or undefined');
  7423. }
  7424. return Object(val);
  7425. }
  7426. function shouldUseNative() {
  7427. try {
  7428. if (!Object.assign) {
  7429. return false;
  7430. }
  7431. // Detect buggy property enumeration order in older V8 versions.
  7432. // https://bugs.chromium.org/p/v8/issues/detail?id=4118
  7433. var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
  7434. test1[5] = 'de';
  7435. if (Object.getOwnPropertyNames(test1)[0] === '5') {
  7436. return false;
  7437. }
  7438. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  7439. var test2 = {};
  7440. for (var i = 0; i < 10; i++) {
  7441. test2['_' + String.fromCharCode(i)] = i;
  7442. }
  7443. var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
  7444. return test2[n];
  7445. });
  7446. if (order2.join('') !== '0123456789') {
  7447. return false;
  7448. }
  7449. // https://bugs.chromium.org/p/v8/issues/detail?id=3056
  7450. var test3 = {};
  7451. 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
  7452. test3[letter] = letter;
  7453. });
  7454. if (Object.keys(Object.assign({}, test3)).join('') !==
  7455. 'abcdefghijklmnopqrst') {
  7456. return false;
  7457. }
  7458. return true;
  7459. } catch (err) {
  7460. // We don't expect any of the above to throw, but better to be safe.
  7461. return false;
  7462. }
  7463. }
  7464. module.exports = shouldUseNative() ? Object.assign : function (target, source) {
  7465. var from;
  7466. var to = toObject(target);
  7467. var symbols;
  7468. for (var s = 1; s < arguments.length; s++) {
  7469. from = Object(arguments[s]);
  7470. for (var key in from) {
  7471. if (hasOwnProperty.call(from, key)) {
  7472. to[key] = from[key];
  7473. }
  7474. }
  7475. if (getOwnPropertySymbols) {
  7476. symbols = getOwnPropertySymbols(from);
  7477. for (var i = 0; i < symbols.length; i++) {
  7478. if (propIsEnumerable.call(from, symbols[i])) {
  7479. to[symbols[i]] = from[symbols[i]];
  7480. }
  7481. }
  7482. }
  7483. }
  7484. return to;
  7485. };
  7486. },{}],39:[function(require,module,exports){
  7487. (function (process){
  7488. 'use strict';
  7489. if (typeof process === 'undefined' ||
  7490. !process.version ||
  7491. process.version.indexOf('v0.') === 0 ||
  7492. process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
  7493. module.exports = { nextTick: nextTick };
  7494. } else {
  7495. module.exports = process
  7496. }
  7497. function nextTick(fn, arg1, arg2, arg3) {
  7498. if (typeof fn !== 'function') {
  7499. throw new TypeError('"callback" argument must be a function');
  7500. }
  7501. var len = arguments.length;
  7502. var args, i;
  7503. switch (len) {
  7504. case 0:
  7505. case 1:
  7506. return process.nextTick(fn);
  7507. case 2:
  7508. return process.nextTick(function afterTickOne() {
  7509. fn.call(null, arg1);
  7510. });
  7511. case 3:
  7512. return process.nextTick(function afterTickTwo() {
  7513. fn.call(null, arg1, arg2);
  7514. });
  7515. case 4:
  7516. return process.nextTick(function afterTickThree() {
  7517. fn.call(null, arg1, arg2, arg3);
  7518. });
  7519. default:
  7520. args = new Array(len - 1);
  7521. i = 0;
  7522. while (i < args.length) {
  7523. args[i++] = arguments[i];
  7524. }
  7525. return process.nextTick(function afterTick() {
  7526. fn.apply(null, args);
  7527. });
  7528. }
  7529. }
  7530. }).call(this,require('_process'))
  7531. },{"_process":9}],40:[function(require,module,exports){
  7532. /* eslint-disable node/no-deprecated-api */
  7533. var buffer = require('buffer')
  7534. var Buffer = buffer.Buffer
  7535. // alternative to using Object.keys for old browsers
  7536. function copyProps (src, dst) {
  7537. for (var key in src) {
  7538. dst[key] = src[key]
  7539. }
  7540. }
  7541. if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
  7542. module.exports = buffer
  7543. } else {
  7544. // Copy properties from require('buffer')
  7545. copyProps(buffer, exports)
  7546. exports.Buffer = SafeBuffer
  7547. }
  7548. function SafeBuffer (arg, encodingOrOffset, length) {
  7549. return Buffer(arg, encodingOrOffset, length)
  7550. }
  7551. // Copy static methods from Buffer
  7552. copyProps(Buffer, SafeBuffer)
  7553. SafeBuffer.from = function (arg, encodingOrOffset, length) {
  7554. if (typeof arg === 'number') {
  7555. throw new TypeError('Argument must not be a number')
  7556. }
  7557. return Buffer(arg, encodingOrOffset, length)
  7558. }
  7559. SafeBuffer.alloc = function (size, fill, encoding) {
  7560. if (typeof size !== 'number') {
  7561. throw new TypeError('Argument must be a number')
  7562. }
  7563. var buf = Buffer(size)
  7564. if (fill !== undefined) {
  7565. if (typeof encoding === 'string') {
  7566. buf.fill(fill, encoding)
  7567. } else {
  7568. buf.fill(fill)
  7569. }
  7570. } else {
  7571. buf.fill(0)
  7572. }
  7573. return buf
  7574. }
  7575. SafeBuffer.allocUnsafe = function (size) {
  7576. if (typeof size !== 'number') {
  7577. throw new TypeError('Argument must be a number')
  7578. }
  7579. return Buffer(size)
  7580. }
  7581. SafeBuffer.allocUnsafeSlow = function (size) {
  7582. if (typeof size !== 'number') {
  7583. throw new TypeError('Argument must be a number')
  7584. }
  7585. return buffer.SlowBuffer(size)
  7586. }
  7587. },{"buffer":8}],41:[function(require,module,exports){
  7588. /*
  7589. Copyright 2018 0kims association.
  7590. This file is part of snarkjs.
  7591. snarkjs is a free software: you can redistribute it and/or
  7592. modify it under the terms of the GNU General Public License as published by the
  7593. Free Software Foundation, either version 3 of the License, or (at your option)
  7594. any later version.
  7595. snarkjs is distributed in the hope that it will be useful,
  7596. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  7597. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  7598. more details.
  7599. You should have received a copy of the GNU General Public License along with
  7600. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  7601. */
  7602. exports.original = {
  7603. setup: require("./src/setup_original.js"),
  7604. genProof: require("./src/prover_original.js"),
  7605. isValid: require("./src/verifier_original.js")
  7606. };
  7607. exports.groth = {
  7608. setup: require("./src/setup_groth.js"),
  7609. genProof: require("./src/prover_groth.js"),
  7610. isValid: require("./src/verifier_groth.js")
  7611. };
  7612. exports.kimleeoh = {
  7613. setup: require("./src/setup_kimleeoh.js"),
  7614. genProof: require("./src/prover_kimleeoh.js"),
  7615. isValid: require("./src/verifier_kimleeoh.js")
  7616. };
  7617. },{"./src/prover_groth.js":42,"./src/prover_kimleeoh.js":43,"./src/prover_original.js":44,"./src/setup_groth.js":45,"./src/setup_kimleeoh.js":46,"./src/setup_original.js":47,"./src/verifier_groth.js":48,"./src/verifier_kimleeoh.js":49,"./src/verifier_original.js":50}],42:[function(require,module,exports){
  7618. /*
  7619. Copyright 2018 0kims association.
  7620. This file is part of snarkjs.
  7621. snarkjs is a free software: you can redistribute it and/or
  7622. modify it under the terms of the GNU General Public License as published by the
  7623. Free Software Foundation, either version 3 of the License, or (at your option)
  7624. any later version.
  7625. snarkjs is distributed in the hope that it will be useful,
  7626. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  7627. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  7628. more details.
  7629. You should have received a copy of the GNU General Public License along with
  7630. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  7631. */
  7632. /* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
  7633. const bn128 = require("ffjavascript").bn128;
  7634. const PolField = require("ffjavascript").PolField;
  7635. const ZqField = require("ffjavascript").ZqField;
  7636. const PolF = new PolField(new ZqField(bn128.r));
  7637. const G1 = bn128.G1;
  7638. const G2 = bn128.G2;
  7639. module.exports = function genProof(vk_proof, witness, verbose) {
  7640. const proof = {};
  7641. const r = PolF.F.random();
  7642. const s = PolF.F.random();
  7643. /* Uncomment to generate a deterministic proof to debug
  7644. const r = PolF.F.zero;
  7645. const s = PolF.F.zero;
  7646. */
  7647. proof.pi_a = G1.zero;
  7648. proof.pi_b = G2.zero;
  7649. proof.pi_c = G1.zero;
  7650. let pib1 = G1.zero;
  7651. // Skip public entries and the "1" signal that are forced by the verifier
  7652. for (let s= 0; s< vk_proof.nVars; s++) {
  7653. // pi_a = pi_a + A[s] * witness[s];
  7654. proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
  7655. // pi_b = pi_b + B[s] * witness[s];
  7656. proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B2[s], witness[s]));
  7657. pib1 = G1.add( pib1, G1.mulScalar( vk_proof.B1[s], witness[s]));
  7658. if ((verbose)&&(s%1000 == 1)) console.log("A, B1, B2: ", s);
  7659. }
  7660. for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
  7661. // pi_a = pi_a + A[s] * witness[s];
  7662. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
  7663. if ((verbose)&&(s%1000 == 1)) console.log("C: ", s);
  7664. }
  7665. proof.pi_a = G1.add( proof.pi_a, vk_proof.vk_alfa_1 );
  7666. proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.vk_delta_1, r ));
  7667. proof.pi_b = G2.add( proof.pi_b, vk_proof.vk_beta_2 );
  7668. proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.vk_delta_2, s ));
  7669. pib1 = G1.add( pib1, vk_proof.vk_beta_1 );
  7670. pib1 = G1.add( pib1, G1.mulScalar( vk_proof.vk_delta_1, s ));
  7671. const h = calculateH(vk_proof, witness);
  7672. // proof.pi_c = G1.affine(proof.pi_c);
  7673. // console.log("pi_onlyc", proof.pi_c);
  7674. for (let i = 0; i < h.length; i++) {
  7675. // console.log(i + "->" + h[i].toString());
  7676. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.hExps[i], h[i]));
  7677. if ((verbose)&&(i%1000 == 1)) console.log("H: ", i);
  7678. }
  7679. // proof.pi_c = G1.affine(proof.pi_c);
  7680. // console.log("pi_candh", proof.pi_c);
  7681. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( proof.pi_a, s ));
  7682. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( pib1, r ));
  7683. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.vk_delta_1, PolF.F.neg(PolF.F.mul(r,s) )));
  7684. const publicSignals = witness.slice(1, vk_proof.nPublic+1);
  7685. proof.pi_a = G1.affine(proof.pi_a);
  7686. proof.pi_b = G2.affine(proof.pi_b);
  7687. proof.pi_c = G1.affine(proof.pi_c);
  7688. proof.protocol = "groth";
  7689. return {proof, publicSignals};
  7690. };
  7691. /*
  7692. // Old Method. (It's clear for academic understanding)
  7693. function calculateH(vk_proof, witness) {
  7694. const F = PolF.F;
  7695. const m = vk_proof.domainSize;
  7696. const polA_T = new Array(m).fill(PolF.F.zero);
  7697. const polB_T = new Array(m).fill(PolF.F.zero);
  7698. const polC_T = new Array(m).fill(PolF.F.zero);
  7699. for (let s=0; s<vk_proof.nVars; s++) {
  7700. for (let c in vk_proof.polsA[s]) {
  7701. polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
  7702. }
  7703. for (let c in vk_proof.polsB[s]) {
  7704. polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
  7705. }
  7706. for (let c in vk_proof.polsC[s]) {
  7707. polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
  7708. }
  7709. }
  7710. const polA_S = PolF.ifft(polA_T);
  7711. const polB_S = PolF.ifft(polB_T);
  7712. const polAB_S = PolF.mul(polA_S, polB_S);
  7713. const polC_S = PolF.ifft(polC_T);
  7714. const polABC_S = PolF.sub(polAB_S, polC_S);
  7715. const H_S = polABC_S.slice(m);
  7716. return H_S;
  7717. }
  7718. */
  7719. function calculateH(vk_proof, witness) {
  7720. const F = PolF.F;
  7721. const m = vk_proof.domainSize;
  7722. const polA_T = new Array(m).fill(PolF.F.zero);
  7723. const polB_T = new Array(m).fill(PolF.F.zero);
  7724. for (let s=0; s<vk_proof.nVars; s++) {
  7725. for (let c in vk_proof.polsA[s]) {
  7726. polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
  7727. }
  7728. for (let c in vk_proof.polsB[s]) {
  7729. polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
  7730. }
  7731. }
  7732. const polA_S = PolF.ifft(polA_T);
  7733. const polB_S = PolF.ifft(polB_T);
  7734. // F(wx) = [1, w, w^2, ...... w^(m-1)] in time is the same than shift in in frequency
  7735. const r = PolF.log2(m)+1;
  7736. PolF._setRoots(r);
  7737. for (let i=0; i<polA_S.length; i++) {
  7738. polA_S[i] = PolF.F.mul( polA_S[i], PolF.roots[r][i]);
  7739. polB_S[i] = PolF.F.mul( polB_S[i], PolF.roots[r][i]);
  7740. }
  7741. const polA_Todd = PolF.fft(polA_S);
  7742. const polB_Todd = PolF.fft(polB_S);
  7743. const polAB_T = new Array(polA_S.length*2);
  7744. for (let i=0; i<polA_S.length; i++) {
  7745. polAB_T[2*i] = PolF.F.mul( polA_T[i], polB_T[i]);
  7746. polAB_T[2*i+1] = PolF.F.mul( polA_Todd[i], polB_Todd[i]);
  7747. }
  7748. // We only need the to half of the fft, so we could optimize at least by m multiplications.
  7749. let H_S = PolF.ifft(polAB_T);
  7750. H_S = H_S.slice(m);
  7751. return H_S;
  7752. }
  7753. },{"ffjavascript":12}],43:[function(require,module,exports){
  7754. (function (Buffer){
  7755. /*
  7756. Copyright 2018 0kims association.
  7757. This file is part of snarkjs.
  7758. snarkjs is a free software: you can redistribute it and/or
  7759. modify it under the terms of the GNU General Public License as published by the
  7760. Free Software Foundation, either version 3 of the License, or (at your option)
  7761. any later version.
  7762. snarkjs is distributed in the hope that it will be useful,
  7763. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  7764. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  7765. more details.
  7766. You should have received a copy of the GNU General Public License along with
  7767. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  7768. */
  7769. /* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
  7770. const bn128 = require("ffjavascript").bn128;
  7771. const PolField = require("ffjavascript").PolField;
  7772. const ZqField = require("ffjavascript").ZqField;
  7773. const createKeccakHash = require("keccak");
  7774. const utils = require("ffjavascript").utils;
  7775. const PolF = new PolField(new ZqField(bn128.r));
  7776. const G1 = bn128.G1;
  7777. const G2 = bn128.G2;
  7778. module.exports = function genProof(vk_proof, witness) {
  7779. const proof = {};
  7780. const r = PolF.F.random();
  7781. const s = PolF.F.random();
  7782. // const r = PolF.F.zero;
  7783. // const s = PolF.F.zero;
  7784. /* Uncomment to generate a deterministic proof to debug
  7785. const r = PolF.F.zero;
  7786. const s = PolF.F.zero;
  7787. */
  7788. proof.pi_a = G1.zero;
  7789. proof.pi_b = G2.zero;
  7790. proof.pi_c = G1.zero;
  7791. let pib1 = G1.zero;
  7792. let piadelta = G1.zero;
  7793. // Skip public entries and the "1" signal that are forced by the verifier
  7794. for (let s= 0; s< vk_proof.nVars; s++) {
  7795. // pi_a = pi_a + A[s] * witness[s];
  7796. proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
  7797. // pi_b = pi_b + B[s] * witness[s];
  7798. proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B2[s], witness[s]));
  7799. piadelta = G1.add( piadelta, G1.mulScalar( vk_proof.Adelta[s], witness[s]));
  7800. pib1 = G1.add( pib1, G1.mulScalar( vk_proof.B1[s], witness[s]));
  7801. }
  7802. for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
  7803. // pi_a = pi_a + A[s] * witness[s];
  7804. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
  7805. }
  7806. proof.pi_a = G1.add( proof.pi_a, vk_proof.vk_alfa_1 );
  7807. proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( G1.g, r ));
  7808. piadelta = G1.add( piadelta, vk_proof.vk_alfadelta_1);
  7809. piadelta = G1.add( piadelta, G1.mulScalar( vk_proof.vk_delta_1, r ));
  7810. proof.pi_b = G2.add( proof.pi_b, vk_proof.vk_beta_2 );
  7811. proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( G2.g, s ));
  7812. pib1 = G1.add( pib1, vk_proof.vk_beta_1 );
  7813. pib1 = G1.add( pib1, G1.mulScalar( G1.g, s ));
  7814. proof.pi_a = G1.affine(proof.pi_a);
  7815. proof.pi_b = G2.affine(proof.pi_b);
  7816. const buff = Buffer.concat([
  7817. utils.beInt2Buff(proof.pi_a[0],32),
  7818. utils.beInt2Buff(proof.pi_a[1],32),
  7819. utils.beInt2Buff(proof.pi_b[0][0],32),
  7820. utils.beInt2Buff(proof.pi_b[0][1],32),
  7821. utils.beInt2Buff(proof.pi_b[1][0],32),
  7822. utils.beInt2Buff(proof.pi_b[1][1],32)
  7823. ]);
  7824. const h1buff = createKeccakHash("keccak256").update(buff).digest();
  7825. const h2buff = createKeccakHash("keccak256").update(h1buff).digest();
  7826. const h1 = utils.beBuff2int(h1buff);
  7827. const h2 = utils.beBuff2int(h2buff);
  7828. // const h1 = PolF.F.zero;
  7829. // const h2 = PolF.F.zero;
  7830. // console.log(h1.toString());
  7831. // console.log(h2.toString());
  7832. const h = calculateH(vk_proof, witness);
  7833. // proof.pi_c = G1.affine(proof.pi_c);
  7834. // console.log("pi_onlyc", proof.pi_c);
  7835. for (let i = 0; i < h.length; i++) {
  7836. // console.log(i + "->" + h[i].toString());
  7837. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.hExps[i], h[i]));
  7838. }
  7839. // proof.pi_c = G1.affine(proof.pi_c);
  7840. // console.log("pi_candh", proof.pi_c);
  7841. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( proof.pi_a, s ));
  7842. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( pib1, r ));
  7843. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( G1.g, PolF.F.neg(PolF.F.mul(r,s) )));
  7844. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( piadelta, h2 ));
  7845. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( pib1, h1 ));
  7846. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.vk_delta_1, PolF.F.mul(h1,h2)));
  7847. const publicSignals = witness.slice(1, vk_proof.nPublic+1);
  7848. proof.pi_c = G1.affine(proof.pi_c);
  7849. proof.protocol = "kimleeoh";
  7850. return {proof, publicSignals};
  7851. };
  7852. function calculateH(vk_proof, witness) {
  7853. const F = PolF.F;
  7854. const m = vk_proof.domainSize;
  7855. const polA_T = new Array(m).fill(PolF.F.zero);
  7856. const polB_T = new Array(m).fill(PolF.F.zero);
  7857. const polC_T = new Array(m).fill(PolF.F.zero);
  7858. for (let s=0; s<vk_proof.nVars; s++) {
  7859. for (let c in vk_proof.polsA[s]) {
  7860. polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
  7861. }
  7862. for (let c in vk_proof.polsB[s]) {
  7863. polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
  7864. }
  7865. for (let c in vk_proof.polsC[s]) {
  7866. polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
  7867. }
  7868. }
  7869. const polA_S = PolF.ifft(polA_T);
  7870. const polB_S = PolF.ifft(polB_T);
  7871. const polAB_S = PolF.mul(polA_S, polB_S);
  7872. const polC_S = PolF.ifft(polC_T);
  7873. const polABC_S = PolF.sub(polAB_S, polC_S);
  7874. const H_S = polABC_S.slice(m);
  7875. return H_S;
  7876. }
  7877. }).call(this,require("buffer").Buffer)
  7878. },{"buffer":8,"ffjavascript":12,"keccak":32}],44:[function(require,module,exports){
  7879. /*
  7880. Copyright 2018 0kims association.
  7881. This file is part of snarkjs.
  7882. snarkjs is a free software: you can redistribute it and/or
  7883. modify it under the terms of the GNU General Public License as published by the
  7884. Free Software Foundation, either version 3 of the License, or (at your option)
  7885. any later version.
  7886. snarkjs is distributed in the hope that it will be useful,
  7887. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  7888. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  7889. more details.
  7890. You should have received a copy of the GNU General Public License along with
  7891. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  7892. */
  7893. const bn128 = require("ffjavascript").bn128;
  7894. const PolField = require("ffjavascript").PolField;
  7895. const ZqField = require("ffjavascript").ZqField;
  7896. const PolF = new PolField(new ZqField(bn128.r));
  7897. const G1 = bn128.G1;
  7898. const G2 = bn128.G2;
  7899. module.exports = function genProof(vk_proof, witness) {
  7900. const proof = {};
  7901. const d1 = PolF.F.random();
  7902. const d2 = PolF.F.random();
  7903. const d3 = PolF.F.random();
  7904. proof.pi_a = G1.zero;
  7905. proof.pi_ap = G1.zero;
  7906. proof.pi_b = G2.zero;
  7907. proof.pi_bp = G1.zero;
  7908. proof.pi_c = G1.zero;
  7909. proof.pi_cp = G1.zero;
  7910. proof.pi_kp = G1.zero;
  7911. proof.pi_h = G1.zero;
  7912. // Skip public entries and the "1" signal that are forced by the verifier
  7913. for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
  7914. // pi_a = pi_a + A[s] * witness[s];
  7915. proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
  7916. // pi_ap = pi_ap + Ap[s] * witness[s];
  7917. proof.pi_ap = G1.add( proof.pi_ap, G1.mulScalar( vk_proof.Ap[s], witness[s]));
  7918. }
  7919. for (let s= 0; s< vk_proof.nVars; s++) {
  7920. // pi_a = pi_a + A[s] * witness[s];
  7921. proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B[s], witness[s]));
  7922. // pi_ap = pi_ap + Ap[s] * witness[s];
  7923. proof.pi_bp = G1.add( proof.pi_bp, G1.mulScalar( vk_proof.Bp[s], witness[s]));
  7924. // pi_a = pi_a + A[s] * witness[s];
  7925. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
  7926. // pi_ap = pi_ap + Ap[s] * witness[s];
  7927. proof.pi_cp = G1.add( proof.pi_cp, G1.mulScalar( vk_proof.Cp[s], witness[s]));
  7928. // pi_ap = pi_ap + Ap[s] * witness[s];
  7929. proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[s], witness[s]));
  7930. }
  7931. proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[vk_proof.nVars], d1));
  7932. proof.pi_ap = G1.add( proof.pi_ap, G1.mulScalar( vk_proof.Ap[vk_proof.nVars], d1));
  7933. proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B[vk_proof.nVars], d2));
  7934. proof.pi_bp = G1.add( proof.pi_bp, G1.mulScalar( vk_proof.Bp[vk_proof.nVars], d2));
  7935. proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[vk_proof.nVars], d3));
  7936. proof.pi_cp = G1.add( proof.pi_cp, G1.mulScalar( vk_proof.Cp[vk_proof.nVars], d3));
  7937. proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars ], d1));
  7938. proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars+1], d2));
  7939. proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars+2], d3));
  7940. /*
  7941. let polA = [];
  7942. let polB = [];
  7943. let polC = [];
  7944. for (let s= 0; s< vk_proof.nVars; s++) {
  7945. polA = PolF.add(
  7946. polA,
  7947. PolF.mul(
  7948. vk_proof.polsA[s],
  7949. [witness[s]] ));
  7950. polB = PolF.add(
  7951. polB,
  7952. PolF.mul(
  7953. vk_proof.polsB[s],
  7954. [witness[s]] ));
  7955. polC = PolF.add(
  7956. polC,
  7957. PolF.mul(
  7958. vk_proof.polsC[s],
  7959. [witness[s]] ));
  7960. }
  7961. let polFull = PolF.sub(PolF.mul( polA, polB), polC);
  7962. const h = PolF.div(polFull, vk_proof.polZ );
  7963. */
  7964. const h = calculateH(vk_proof, witness, d1, d2, d3);
  7965. // console.log(h.length + "/" + vk_proof.hExps.length);
  7966. for (let i = 0; i < h.length; i++) {
  7967. proof.pi_h = G1.add( proof.pi_h, G1.mulScalar( vk_proof.hExps[i], h[i]));
  7968. }
  7969. proof.pi_a = G1.affine(proof.pi_a);
  7970. proof.pi_b = G2.affine(proof.pi_b);
  7971. proof.pi_c = G1.affine(proof.pi_c);
  7972. proof.pi_ap = G1.affine(proof.pi_ap);
  7973. proof.pi_bp = G1.affine(proof.pi_bp);
  7974. proof.pi_cp = G1.affine(proof.pi_cp);
  7975. proof.pi_kp = G1.affine(proof.pi_kp);
  7976. proof.pi_h = G1.affine(proof.pi_h);
  7977. // proof.h=h;
  7978. proof.protocol = "original";
  7979. const publicSignals = witness.slice(1, vk_proof.nPublic+1);
  7980. return {proof, publicSignals};
  7981. };
  7982. function calculateH(vk_proof, witness, d1, d2, d3) {
  7983. const F = PolF.F;
  7984. const m = vk_proof.domainSize;
  7985. const polA_T = new Array(m).fill(PolF.F.zero);
  7986. const polB_T = new Array(m).fill(PolF.F.zero);
  7987. const polC_T = new Array(m).fill(PolF.F.zero);
  7988. for (let s=0; s<vk_proof.nVars; s++) {
  7989. for (let c in vk_proof.polsA[s]) {
  7990. polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
  7991. }
  7992. for (let c in vk_proof.polsB[s]) {
  7993. polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
  7994. }
  7995. for (let c in vk_proof.polsC[s]) {
  7996. polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
  7997. }
  7998. }
  7999. const polA_S = PolF.ifft(polA_T);
  8000. const polB_S = PolF.ifft(polB_T);
  8001. const polAB_S = PolF.mul(polA_S, polB_S);
  8002. const polC_S = PolF.ifft(polC_T);
  8003. const polABC_S = PolF.sub(polAB_S, polC_S);
  8004. const polZ_S = new Array(m+1).fill(F.zero);
  8005. polZ_S[m] = F.one;
  8006. polZ_S[0] = F.neg(F.one);
  8007. let H_S = PolF.div(polABC_S, polZ_S);
  8008. /*
  8009. const H2S = PolF.mul(H_S, polZ_S);
  8010. if (PolF.equals(H2S, polABC_S)) {
  8011. console.log("Is Divisible!");
  8012. } else {
  8013. console.log("ERROR: Not divisible!");
  8014. }
  8015. */
  8016. /* add coefficients of the polynomial (d2*A + d1*B - d3) + d1*d2*Z */
  8017. H_S = PolF.extend(H_S, m+1);
  8018. for (let i=0; i<m; i++) {
  8019. const d2A = PolF.F.mul(d2, polA_S[i]);
  8020. const d1B = PolF.F.mul(d1, polB_S[i]);
  8021. H_S[i] = PolF.F.add(H_S[i], PolF.F.add(d2A, d1B));
  8022. }
  8023. H_S[0] = PolF.F.sub(H_S[0], d3);
  8024. // Z = x^m -1
  8025. const d1d2 = PolF.F.mul(d1, d2);
  8026. H_S[m] = PolF.F.add(H_S[m], d1d2);
  8027. H_S[0] = PolF.F.sub(H_S[0], d1d2);
  8028. H_S = PolF.reduce(H_S);
  8029. return H_S;
  8030. }
  8031. },{"ffjavascript":12}],45:[function(require,module,exports){
  8032. /*
  8033. Copyright 2018 0kims association.
  8034. This file is part of snarkjs.
  8035. snarkjs is a free software: you can redistribute it and/or
  8036. modify it under the terms of the GNU General Public License as published by the
  8037. Free Software Foundation, either version 3 of the License, or (at your option)
  8038. any later version.
  8039. snarkjs is distributed in the hope that it will be useful,
  8040. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  8041. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  8042. more details.
  8043. You should have received a copy of the GNU General Public License along with
  8044. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  8045. */
  8046. /* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
  8047. const bigInt = require("big-integer");
  8048. const bn128 = require("ffjavascript").bn128;
  8049. const PolField = require("ffjavascript").PolField;
  8050. const ZqField = require("ffjavascript").ZqField;
  8051. const G1 = bn128.G1;
  8052. const G2 = bn128.G2;
  8053. const PolF = new PolField(new ZqField(bn128.r));
  8054. const F = new ZqField(bn128.r);
  8055. module.exports = function setup(circuit, verbose) {
  8056. const setup = {
  8057. vk_proof : {
  8058. protocol: "groth",
  8059. nVars: circuit.nVars,
  8060. nPublic: circuit.nPubInputs + circuit.nOutputs
  8061. },
  8062. vk_verifier: {
  8063. protocol: "groth",
  8064. nPublic: circuit.nPubInputs + circuit.nOutputs
  8065. },
  8066. toxic: {}
  8067. };
  8068. setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
  8069. setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
  8070. calculatePolinomials(setup, circuit);
  8071. setup.toxic.t = F.random();
  8072. calculateEncriptedValuesAtT(setup, circuit, verbose);
  8073. return setup;
  8074. };
  8075. function calculatePolinomials(setup, circuit) {
  8076. setup.vk_proof.polsA = new Array(circuit.nVars);
  8077. setup.vk_proof.polsB = new Array(circuit.nVars);
  8078. setup.vk_proof.polsC = new Array(circuit.nVars);
  8079. for (let i=0; i<circuit.nVars; i++) {
  8080. setup.vk_proof.polsA[i] = {};
  8081. setup.vk_proof.polsB[i] = {};
  8082. setup.vk_proof.polsC[i] = {};
  8083. }
  8084. for (let c=0; c<circuit.nConstraints; c++) {
  8085. for (let s in circuit.constraints[c][0]) {
  8086. setup.vk_proof.polsA[s][c] = circuit.constraints[c][0][s];
  8087. }
  8088. for (let s in circuit.constraints[c][1]) {
  8089. setup.vk_proof.polsB[s][c] = circuit.constraints[c][1][s];
  8090. }
  8091. for (let s in circuit.constraints[c][2]) {
  8092. setup.vk_proof.polsC[s][c] = circuit.constraints[c][2][s];
  8093. }
  8094. }
  8095. /**
  8096. * add and process the constraints
  8097. * input_i * 0 = 0
  8098. * to ensure soundness of input consistency
  8099. */
  8100. for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
  8101. {
  8102. setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
  8103. }
  8104. }
  8105. function calculateValuesAtT(setup, circuit) {
  8106. const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
  8107. const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
  8108. const a_t = new Array(circuit.nVars).fill(F.zero);
  8109. const b_t = new Array(circuit.nVars).fill(F.zero);
  8110. const c_t = new Array(circuit.nVars).fill(F.zero);
  8111. // TODO: substitute setup.polsA for coeficients
  8112. for (let s=0; s<circuit.nVars; s++) {
  8113. for (let c in setup.vk_proof.polsA[s]) {
  8114. a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
  8115. }
  8116. for (let c in setup.vk_proof.polsB[s]) {
  8117. b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
  8118. }
  8119. for (let c in setup.vk_proof.polsC[s]) {
  8120. c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
  8121. }
  8122. }
  8123. return {a_t, b_t, c_t, z_t};
  8124. }
  8125. function calculateEncriptedValuesAtT(setup, circuit, verbose) {
  8126. const v = calculateValuesAtT(setup, circuit);
  8127. setup.vk_proof.A = new Array(circuit.nVars);
  8128. setup.vk_proof.B1 = new Array(circuit.nVars);
  8129. setup.vk_proof.B2 = new Array(circuit.nVars);
  8130. setup.vk_proof.C = new Array(circuit.nVars);
  8131. setup.vk_verifier.IC = new Array(circuit.nPubInputs + circuit.nOutputs + 1);
  8132. setup.toxic.kalfa = F.random();
  8133. setup.toxic.kbeta = F.random();
  8134. setup.toxic.kgamma = F.random();
  8135. setup.toxic.kdelta = F.random();
  8136. let invDelta = F.inv(setup.toxic.kdelta);
  8137. let invGamma = F.inv(setup.toxic.kgamma);
  8138. setup.vk_proof.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
  8139. setup.vk_proof.vk_beta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kbeta));
  8140. setup.vk_proof.vk_delta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kdelta));
  8141. setup.vk_proof.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
  8142. setup.vk_proof.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
  8143. setup.vk_verifier.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
  8144. setup.vk_verifier.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
  8145. setup.vk_verifier.vk_gamma_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
  8146. setup.vk_verifier.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
  8147. setup.vk_verifier.vk_alfabeta_12 = bn128.pairing( setup.vk_verifier.vk_alfa_1 , setup.vk_verifier.vk_beta_2 );
  8148. for (let s=0; s<circuit.nVars; s++) {
  8149. const A = G1.mulScalar(G1.g, v.a_t[s]);
  8150. setup.vk_proof.A[s] = A;
  8151. const B1 = G1.mulScalar(G1.g, v.b_t[s]);
  8152. setup.vk_proof.B1[s] = B1;
  8153. const B2 = G2.mulScalar(G2.g, v.b_t[s]);
  8154. setup.vk_proof.B2[s] = B2;
  8155. if ((verbose)&&(s%1000 == 1)) console.log("A, B1, B2: ", s);
  8156. }
  8157. for (let s=0; s<=setup.vk_proof.nPublic; s++) {
  8158. let ps =
  8159. F.mul(
  8160. invGamma,
  8161. F.add(
  8162. F.add(
  8163. F.mul(v.a_t[s], setup.toxic.kbeta),
  8164. F.mul(v.b_t[s], setup.toxic.kalfa)),
  8165. v.c_t[s]));
  8166. const IC = G1.mulScalar(G1.g, ps);
  8167. setup.vk_verifier.IC[s]=IC;
  8168. }
  8169. for (let s=setup.vk_proof.nPublic+1; s<circuit.nVars; s++) {
  8170. let ps =
  8171. F.mul(
  8172. invDelta,
  8173. F.add(
  8174. F.add(
  8175. F.mul(v.a_t[s], setup.toxic.kbeta),
  8176. F.mul(v.b_t[s], setup.toxic.kalfa)),
  8177. v.c_t[s]));
  8178. const C = G1.mulScalar(G1.g, ps);
  8179. setup.vk_proof.C[s]=C;
  8180. if ((verbose)&&(s%1000 == 1)) console.log("C: ", s);
  8181. }
  8182. // Calculate HExps
  8183. const maxH = setup.vk_proof.domainSize+1;
  8184. setup.vk_proof.hExps = new Array(maxH);
  8185. const zod = F.mul(invDelta, v.z_t);
  8186. setup.vk_proof.hExps[0] = G1.affine(G1.mulScalar(G1.g, zod));
  8187. let eT = setup.toxic.t;
  8188. for (let i=1; i<maxH; i++) {
  8189. setup.vk_proof.hExps[i] = G1.mulScalar(G1.g, F.mul(eT, zod));
  8190. eT = F.mul(eT, setup.toxic.t);
  8191. if ((verbose)&&(i%1000 == 1)) console.log("Tau: ", i);
  8192. }
  8193. G1.multiAffine(setup.vk_proof.A);
  8194. G1.multiAffine(setup.vk_proof.B1);
  8195. G2.multiAffine(setup.vk_proof.B2);
  8196. G1.multiAffine(setup.vk_proof.C);
  8197. G1.multiAffine(setup.vk_proof.hExps);
  8198. G1.multiAffine(setup.vk_verifier.IC);
  8199. }
  8200. },{"big-integer":6,"ffjavascript":12}],46:[function(require,module,exports){
  8201. /*
  8202. Copyright 2018 0kims association.
  8203. This file is part of snarkjs.
  8204. snarkjs is a free software: you can redistribute it and/or
  8205. modify it under the terms of the GNU General Public License as published by the
  8206. Free Software Foundation, either version 3 of the License, or (at your option)
  8207. any later version.
  8208. snarkjs is distributed in the hope that it will be useful,
  8209. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  8210. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  8211. more details.
  8212. You should have received a copy of the GNU General Public License along with
  8213. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  8214. */
  8215. /* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
  8216. const bigInt = require("big-integer");
  8217. const bn128 = require("ffjavascript").bn128;
  8218. const PolField = require("ffjavascript").PolField;
  8219. const ZqField = require("ffjavascript").ZqField;
  8220. const G1 = bn128.G1;
  8221. const G2 = bn128.G2;
  8222. const PolF = new PolField(new ZqField(bn128.r));
  8223. const F = new ZqField(bn128.r);
  8224. module.exports = function setup(circuit) {
  8225. const setup = {
  8226. vk_proof : {
  8227. protocol: "kimleeoh",
  8228. nVars: circuit.nVars,
  8229. nPublic: circuit.nPubInputs + circuit.nOutputs
  8230. },
  8231. vk_verifier: {
  8232. protocol: "kimleeoh",
  8233. nPublic: circuit.nPubInputs + circuit.nOutputs
  8234. },
  8235. toxic: {}
  8236. };
  8237. setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
  8238. setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
  8239. calculatePolinomials(setup, circuit);
  8240. setup.toxic.t = F.random();
  8241. calculateEncriptedValuesAtT(setup, circuit);
  8242. return setup;
  8243. };
  8244. function calculatePolinomials(setup, circuit) {
  8245. setup.vk_proof.polsA = new Array(circuit.nVars);
  8246. setup.vk_proof.polsB = new Array(circuit.nVars);
  8247. setup.vk_proof.polsC = new Array(circuit.nVars);
  8248. for (let i=0; i<circuit.nVars; i++) {
  8249. setup.vk_proof.polsA[i] = {};
  8250. setup.vk_proof.polsB[i] = {};
  8251. setup.vk_proof.polsC[i] = {};
  8252. }
  8253. for (let c=0; c<circuit.nConstraints; c++) {
  8254. for (let s in circuit.constraints[c][0]) {
  8255. setup.vk_proof.polsA[s][c] = circuit.constraints[c][0][s];
  8256. }
  8257. for (let s in circuit.constraints[c][1]) {
  8258. setup.vk_proof.polsB[s][c] = circuit.constraints[c][1][s];
  8259. }
  8260. for (let s in circuit.constraints[c][2]) {
  8261. setup.vk_proof.polsC[s][c] = circuit.constraints[c][2][s];
  8262. }
  8263. }
  8264. /**
  8265. * add and process the constraints
  8266. * input_i * 0 = 0
  8267. * to ensure soundness of input consistency
  8268. */
  8269. for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
  8270. {
  8271. setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
  8272. }
  8273. }
  8274. function calculateValuesAtT(setup, circuit) {
  8275. const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
  8276. const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
  8277. const a_t = new Array(circuit.nVars).fill(F.zero);
  8278. const b_t = new Array(circuit.nVars).fill(F.zero);
  8279. const c_t = new Array(circuit.nVars).fill(F.zero);
  8280. // TODO: substitute setup.polsA for coeficients
  8281. for (let s=0; s<circuit.nVars; s++) {
  8282. for (let c in setup.vk_proof.polsA[s]) {
  8283. a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
  8284. }
  8285. for (let c in setup.vk_proof.polsB[s]) {
  8286. b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
  8287. }
  8288. for (let c in setup.vk_proof.polsC[s]) {
  8289. c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
  8290. }
  8291. }
  8292. return {a_t, b_t, c_t, z_t};
  8293. }
  8294. function calculateEncriptedValuesAtT(setup, circuit) {
  8295. const v = calculateValuesAtT(setup, circuit);
  8296. setup.vk_proof.A = new Array(circuit.nVars);
  8297. setup.vk_proof.Adelta = new Array(circuit.nVars);
  8298. setup.vk_proof.B1 = new Array(circuit.nVars);
  8299. setup.vk_proof.B2 = new Array(circuit.nVars);
  8300. setup.vk_proof.C = new Array(circuit.nVars);
  8301. setup.vk_verifier.IC = new Array(circuit.nPubInputs + circuit.nOutputs + 1);
  8302. setup.toxic.kalfa = F.random();
  8303. setup.toxic.kbeta = F.random();
  8304. setup.toxic.kgamma = F.random();
  8305. setup.toxic.kdelta = F.random();
  8306. const gammaSquare = F.mul(setup.toxic.kgamma, setup.toxic.kgamma);
  8307. setup.vk_proof.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
  8308. setup.vk_proof.vk_beta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kbeta));
  8309. setup.vk_proof.vk_delta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kdelta));
  8310. setup.vk_proof.vk_alfadelta_1 = G1.affine(G1.mulScalar( G1.g, F.mul(setup.toxic.kalfa, setup.toxic.kdelta)));
  8311. setup.vk_proof.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
  8312. setup.vk_verifier.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
  8313. setup.vk_verifier.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
  8314. setup.vk_verifier.vk_gamma_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
  8315. setup.vk_verifier.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
  8316. setup.vk_verifier.vk_alfabeta_12 = bn128.pairing( setup.vk_verifier.vk_alfa_1 , setup.vk_verifier.vk_beta_2 );
  8317. for (let s=0; s<circuit.nVars; s++) {
  8318. const A = G1.affine(G1.mulScalar(G1.g, F.mul(setup.toxic.kgamma, v.a_t[s])));
  8319. setup.vk_proof.A[s] = A;
  8320. setup.vk_proof.Adelta[s] = G1.affine(G1.mulScalar(A, setup.toxic.kdelta));
  8321. const B1 = G1.affine(G1.mulScalar(G1.g, F.mul(setup.toxic.kgamma, v.b_t[s])));
  8322. setup.vk_proof.B1[s] = B1;
  8323. const B2 = G2.affine(G2.mulScalar(G2.g, F.mul(setup.toxic.kgamma, v.b_t[s])));
  8324. setup.vk_proof.B2[s] = B2;
  8325. }
  8326. for (let s=0; s<=setup.vk_proof.nPublic; s++) {
  8327. let ps =
  8328. F.add(
  8329. F.mul(
  8330. setup.toxic.kgamma,
  8331. v.c_t[s]
  8332. ),
  8333. F.add(
  8334. F.mul(
  8335. setup.toxic.kbeta,
  8336. v.a_t[s]
  8337. ),
  8338. F.mul(
  8339. setup.toxic.kalfa,
  8340. v.b_t[s]
  8341. )
  8342. )
  8343. );
  8344. const IC = G1.affine(G1.mulScalar(G1.g, ps));
  8345. setup.vk_verifier.IC[s]=IC;
  8346. }
  8347. for (let s=setup.vk_proof.nPublic+1; s<circuit.nVars; s++) {
  8348. let ps =
  8349. F.add(
  8350. F.mul(
  8351. gammaSquare,
  8352. v.c_t[s]
  8353. ),
  8354. F.add(
  8355. F.mul(
  8356. F.mul(setup.toxic.kbeta, setup.toxic.kgamma),
  8357. v.a_t[s]
  8358. ),
  8359. F.mul(
  8360. F.mul(setup.toxic.kalfa, setup.toxic.kgamma),
  8361. v.b_t[s]
  8362. )
  8363. )
  8364. );
  8365. const C = G1.affine(G1.mulScalar(G1.g, ps));
  8366. setup.vk_proof.C[s]=C;
  8367. }
  8368. // Calculate HExps
  8369. const maxH = setup.vk_proof.domainSize+1;
  8370. setup.vk_proof.hExps = new Array(maxH);
  8371. const zod = F.mul(gammaSquare, v.z_t);
  8372. setup.vk_proof.hExps[0] = G1.affine(G1.mulScalar(G1.g, zod));
  8373. let eT = setup.toxic.t;
  8374. for (let i=1; i<maxH; i++) {
  8375. setup.vk_proof.hExps[i] = G1.affine(G1.mulScalar(G1.g, F.mul(eT, zod)));
  8376. eT = F.mul(eT, setup.toxic.t);
  8377. }
  8378. }
  8379. },{"big-integer":6,"ffjavascript":12}],47:[function(require,module,exports){
  8380. /*
  8381. Copyright 2018 0kims association.
  8382. This file is part of snarkjs.
  8383. snarkjs is a free software: you can redistribute it and/or
  8384. modify it under the terms of the GNU General Public License as published by the
  8385. Free Software Foundation, either version 3 of the License, or (at your option)
  8386. any later version.
  8387. snarkjs is distributed in the hope that it will be useful,
  8388. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  8389. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  8390. more details.
  8391. You should have received a copy of the GNU General Public License along with
  8392. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  8393. */
  8394. const bigInt = require("big-integer");
  8395. const bn128 = require("ffjavascript").bn128;
  8396. const PolField = require("ffjavascript").PolField;
  8397. const ZqField = require("ffjavascript").ZqField;
  8398. const G1 = bn128.G1;
  8399. const G2 = bn128.G2;
  8400. const PolF = new PolField(new ZqField(bn128.r));
  8401. const F = new ZqField(bn128.r);
  8402. module.exports = function setup(circuit) {
  8403. const setup = {
  8404. vk_proof : {
  8405. protocol: "original",
  8406. nVars: circuit.nVars,
  8407. nPublic: circuit.nPubInputs + circuit.nOutputs
  8408. },
  8409. vk_verifier: {
  8410. protocol: "original",
  8411. nPublic: circuit.nPubInputs + circuit.nOutputs
  8412. },
  8413. toxic: {}
  8414. };
  8415. setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
  8416. setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
  8417. calculatePolinomials(setup, circuit);
  8418. setup.toxic.t = F.random();
  8419. calculateEncriptedValuesAtT(setup, circuit);
  8420. calculateHexps(setup, circuit);
  8421. return setup;
  8422. };
  8423. function calculatePolinomials(setup, circuit) {
  8424. setup.vk_proof.polsA = new Array(circuit.nVars);
  8425. setup.vk_proof.polsB = new Array(circuit.nVars);
  8426. setup.vk_proof.polsC = new Array(circuit.nVars);
  8427. for (let i=0; i<circuit.nVars; i++) {
  8428. setup.vk_proof.polsA[i] = {};
  8429. setup.vk_proof.polsB[i] = {};
  8430. setup.vk_proof.polsC[i] = {};
  8431. }
  8432. for (let c=0; c<circuit.nConstraints; c++) {
  8433. for (let s in circuit.constraints[c][0]) {
  8434. setup.vk_proof.polsA[s][c] = circuit.constraints[c][0][s];
  8435. }
  8436. for (let s in circuit.constraints[c][1]) {
  8437. setup.vk_proof.polsB[s][c] = circuit.constraints[c][1][s];
  8438. }
  8439. for (let s in circuit.constraints[c][2]) {
  8440. setup.vk_proof.polsC[s][c] = circuit.constraints[c][2][s];
  8441. }
  8442. }
  8443. /**
  8444. * add and process the constraints
  8445. * input_i * 0 = 0
  8446. * to ensure soundness of input consistency
  8447. */
  8448. for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
  8449. {
  8450. setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
  8451. }
  8452. }
  8453. function calculateValuesAtT(setup, circuit) {
  8454. const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
  8455. const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
  8456. const a_t = new Array(circuit.nVars).fill(F.zero);
  8457. const b_t = new Array(circuit.nVars).fill(F.zero);
  8458. const c_t = new Array(circuit.nVars).fill(F.zero);
  8459. // TODO: substitute setup.polsA for coeficients
  8460. for (let s=0; s<circuit.nVars; s++) {
  8461. for (let c in setup.vk_proof.polsA[s]) {
  8462. a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
  8463. }
  8464. for (let c in setup.vk_proof.polsB[s]) {
  8465. b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
  8466. }
  8467. for (let c in setup.vk_proof.polsC[s]) {
  8468. c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
  8469. }
  8470. }
  8471. return {a_t, b_t, c_t, z_t};
  8472. }
  8473. function calculateEncriptedValuesAtT(setup, circuit) {
  8474. const v = calculateValuesAtT(setup, circuit);
  8475. setup.vk_proof.A = new Array(circuit.nVars+1);
  8476. setup.vk_proof.B = new Array(circuit.nVars+1);
  8477. setup.vk_proof.C = new Array(circuit.nVars+1);
  8478. setup.vk_proof.Ap = new Array(circuit.nVars+1);
  8479. setup.vk_proof.Bp = new Array(circuit.nVars+1);
  8480. setup.vk_proof.Cp = new Array(circuit.nVars+1);
  8481. setup.vk_proof.Kp = new Array(circuit.nVars+3);
  8482. setup.vk_verifier.IC = new Array(circuit.nPubInputs);
  8483. setup.vk_verifier.IC = new Array(circuit.nPubInputs + circuit.nOutputs + 1);
  8484. setup.toxic.ka = F.random();
  8485. setup.toxic.kb = F.random();
  8486. setup.toxic.kc = F.random();
  8487. setup.toxic.ra = F.random();
  8488. setup.toxic.rb = F.random();
  8489. setup.toxic.rc = F.mul(setup.toxic.ra, setup.toxic.rb);
  8490. setup.toxic.kbeta = F.random();
  8491. setup.toxic.kgamma = F.random();
  8492. const gb = F.mul(setup.toxic.kbeta, setup.toxic.kgamma);
  8493. setup.vk_verifier.vk_a = G2.affine(G2.mulScalar( G2.g, setup.toxic.ka));
  8494. setup.vk_verifier.vk_b = G1.affine(G1.mulScalar( G1.g, setup.toxic.kb));
  8495. setup.vk_verifier.vk_c = G2.affine(G2.mulScalar( G2.g, setup.toxic.kc));
  8496. setup.vk_verifier.vk_gb_1 = G1.affine(G1.mulScalar( G1.g, gb));
  8497. setup.vk_verifier.vk_gb_2 = G2.affine(G2.mulScalar( G2.g, gb));
  8498. setup.vk_verifier.vk_g = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
  8499. for (let s=0; s<circuit.nVars; s++) {
  8500. // A[i] = G1 * polA(t)
  8501. const raat = F.mul(setup.toxic.ra, v.a_t[s]);
  8502. const A = G1.affine(G1.mulScalar(G1.g, raat));
  8503. setup.vk_proof.A[s] = A;
  8504. if (s <= setup.vk_proof.nPublic) {
  8505. setup.vk_verifier.IC[s]=A;
  8506. }
  8507. // B1[i] = G1 * polB(t)
  8508. const rbbt = F.mul(setup.toxic.rb, v.b_t[s]);
  8509. const B1 = G1.affine(G1.mulScalar(G1.g, rbbt));
  8510. // B2[i] = G2 * polB(t)
  8511. const B2 = G2.affine(G2.mulScalar(G2.g, rbbt));
  8512. setup.vk_proof.B[s]=B2;
  8513. // C[i] = G1 * polC(t)
  8514. const rcct = F.mul(setup.toxic.rc, v.c_t[s]);
  8515. const C = G1.affine(G1.mulScalar( G1.g, rcct));
  8516. setup.vk_proof.C[s] =C;
  8517. // K = G1 * (A+B+C)
  8518. const kt = F.add(F.add(raat, rbbt), rcct);
  8519. const K = G1.affine(G1.mulScalar( G1.g, kt));
  8520. /*
  8521. // Comment this lines to improve the process
  8522. const Ktest = G1.affine(G1.add(G1.add(A, B1), C));
  8523. if (!G1.equals(K, Ktest)) {
  8524. console.log ("=====FAIL======");
  8525. }
  8526. */
  8527. if (s > setup.vk_proof.nPublic) {
  8528. setup.vk_proof.Ap[s] = G1.affine(G1.mulScalar(A, setup.toxic.ka));
  8529. }
  8530. setup.vk_proof.Bp[s] = G1.affine(G1.mulScalar(B1, setup.toxic.kb));
  8531. setup.vk_proof.Cp[s] = G1.affine(G1.mulScalar(C, setup.toxic.kc));
  8532. setup.vk_proof.Kp[s] = G1.affine(G1.mulScalar(K, setup.toxic.kbeta));
  8533. }
  8534. // Extra coeficients
  8535. const A = G1.mulScalar( G1.g, F.mul(setup.toxic.ra, v.z_t));
  8536. setup.vk_proof.A[circuit.nVars] = G1.affine(A);
  8537. setup.vk_proof.Ap[circuit.nVars] = G1.affine(G1.mulScalar(A, setup.toxic.ka));
  8538. const B1 = G1.mulScalar( G1.g, F.mul(setup.toxic.rb, v.z_t));
  8539. const B2 = G2.mulScalar( G2.g, F.mul(setup.toxic.rb, v.z_t));
  8540. setup.vk_proof.B[circuit.nVars] = G2.affine(B2);
  8541. setup.vk_proof.Bp[circuit.nVars] = G1.affine(G1.mulScalar(B1, setup.toxic.kb));
  8542. const C = G1.mulScalar( G1.g, F.mul(setup.toxic.rc, v.z_t));
  8543. setup.vk_proof.C[circuit.nVars] = G1.affine(C);
  8544. setup.vk_proof.Cp[circuit.nVars] = G1.affine(G1.mulScalar(C, setup.toxic.kc));
  8545. setup.vk_proof.Kp[circuit.nVars ] = G1.affine(G1.mulScalar(A, setup.toxic.kbeta));
  8546. setup.vk_proof.Kp[circuit.nVars+1] = G1.affine(G1.mulScalar(B1, setup.toxic.kbeta));
  8547. setup.vk_proof.Kp[circuit.nVars+2] = G1.affine(G1.mulScalar(C, setup.toxic.kbeta));
  8548. // setup.vk_verifier.A[0] = G1.affine(G1.add(setup.vk_verifier.A[0], setup.vk_proof.A[circuit.nVars]));
  8549. // vk_z
  8550. setup.vk_verifier.vk_z = G2.affine(G2.mulScalar(
  8551. G2.g,
  8552. F.mul(setup.toxic.rc, v.z_t)));
  8553. }
  8554. function calculateHexps(setup) {
  8555. const maxH = setup.vk_proof.domainSize+1;
  8556. setup.vk_proof.hExps = new Array(maxH);
  8557. setup.vk_proof.hExps[0] = G1.g;
  8558. let eT = setup.toxic.t;
  8559. for (let i=1; i<maxH; i++) {
  8560. setup.vk_proof.hExps[i] = G1.affine(G1.mulScalar(G1.g, eT));
  8561. eT = F.mul(eT, setup.toxic.t);
  8562. }
  8563. }
  8564. },{"big-integer":6,"ffjavascript":12}],48:[function(require,module,exports){
  8565. /*
  8566. Copyright 2018 0kims association.
  8567. This file is part of snarkjs.
  8568. snarkjs is a free software: you can redistribute it and/or
  8569. modify it under the terms of the GNU General Public License as published by the
  8570. Free Software Foundation, either version 3 of the License, or (at your option)
  8571. any later version.
  8572. snarkjs is distributed in the hope that it will be useful,
  8573. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  8574. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  8575. more details.
  8576. You should have received a copy of the GNU General Public License along with
  8577. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  8578. */
  8579. /* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
  8580. const bn128 = require("ffjavascript").bn128;
  8581. const G1 = bn128.G1;
  8582. module.exports = function isValid(vk_verifier, proof, publicSignals) {
  8583. let cpub = vk_verifier.IC[0];
  8584. for (let s= 0; s< vk_verifier.nPublic; s++) {
  8585. cpub = G1.add( cpub, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
  8586. }
  8587. if (! bn128.F12.eq(
  8588. bn128.pairing( proof.pi_a , proof.pi_b ),
  8589. bn128.F12.mul(
  8590. vk_verifier.vk_alfabeta_12,
  8591. bn128.F12.mul(
  8592. bn128.pairing( cpub , vk_verifier.vk_gamma_2 ),
  8593. bn128.pairing( proof.pi_c , vk_verifier.vk_delta_2 )
  8594. ))))
  8595. return false;
  8596. return true;
  8597. };
  8598. },{"ffjavascript":12}],49:[function(require,module,exports){
  8599. (function (Buffer){
  8600. /*
  8601. Copyright 2018 0kims association.
  8602. This file is part of snarkjs.
  8603. snarkjs is a free software: you can redistribute it and/or
  8604. modify it under the terms of the GNU General Public License as published by the
  8605. Free Software Foundation, either version 3 of the License, or (at your option)
  8606. any later version.
  8607. snarkjs is distributed in the hope that it will be useful,
  8608. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  8609. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  8610. more details.
  8611. You should have received a copy of the GNU General Public License along with
  8612. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  8613. */
  8614. /* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
  8615. const bn128 = require("ffjavascript").bn128;
  8616. const createKeccakHash = require("keccak");
  8617. const utils = require("ffjavascript").utils;
  8618. const G1 = bn128.G1;
  8619. const G2 = bn128.G2;
  8620. module.exports = function isValid(vk_verifier, proof, publicSignals) {
  8621. let cpub = vk_verifier.IC[0];
  8622. for (let s= 0; s< vk_verifier.nPublic; s++) {
  8623. cpub = G1.add( cpub, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
  8624. }
  8625. const buff = Buffer.concat([
  8626. utils.beInt2Buff(proof.pi_a[0], 32),
  8627. utils.beInt2Buff(proof.pi_a[1], 32),
  8628. utils.beInt2Buff(proof.pi_b[0][0], 32),
  8629. utils.beInt2Buff(proof.pi_b[0][1], 32),
  8630. utils.beInt2Buff(proof.pi_b[1][0], 32),
  8631. utils.beInt2Buff(proof.pi_b[1][1], 32),
  8632. ]);
  8633. const h1buff = createKeccakHash("keccak256").update(buff).digest();
  8634. const h2buff = createKeccakHash("keccak256").update(h1buff).digest();
  8635. const h1 = utils.beBuff2int(h1buff);
  8636. const h2 = utils.beBuff2int(h2buff);
  8637. // const h1 = bn128.Fr.zero;
  8638. // const h2 = bn128.Fr.zero;
  8639. // console.log(h1.toString());
  8640. // console.log(h2.toString());
  8641. if (! bn128.F12.eq(
  8642. bn128.pairing(
  8643. G1.add(proof.pi_a, G1.mulScalar(G1.g, h1)),
  8644. G2.add(proof.pi_b, G2.mulScalar(vk_verifier.vk_delta_2, h2))
  8645. ),
  8646. bn128.F12.mul(
  8647. vk_verifier.vk_alfabeta_12,
  8648. bn128.F12.mul(
  8649. bn128.pairing( cpub , vk_verifier.vk_gamma_2 ),
  8650. bn128.pairing( proof.pi_c , G2.g )
  8651. ))))
  8652. return false;
  8653. return true;
  8654. };
  8655. }).call(this,require("buffer").Buffer)
  8656. },{"buffer":8,"ffjavascript":12,"keccak":32}],50:[function(require,module,exports){
  8657. /*
  8658. Copyright 2018 0kims association.
  8659. This file is part of snarkjs.
  8660. snarkjs is a free software: you can redistribute it and/or
  8661. modify it under the terms of the GNU General Public License as published by the
  8662. Free Software Foundation, either version 3 of the License, or (at your option)
  8663. any later version.
  8664. snarkjs is distributed in the hope that it will be useful,
  8665. but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
  8666. or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  8667. more details.
  8668. You should have received a copy of the GNU General Public License along with
  8669. snarkjs. If not, see <https://www.gnu.org/licenses/>.
  8670. */
  8671. const bn128 = require("ffjavascript").bn128;
  8672. const G1 = bn128.G1;
  8673. const G2 = bn128.G2;
  8674. module.exports = function isValid(vk_verifier, proof, publicSignals) {
  8675. let full_pi_a = vk_verifier.IC[0];
  8676. for (let s= 0; s< vk_verifier.nPublic; s++) {
  8677. full_pi_a = G1.add( full_pi_a, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
  8678. }
  8679. full_pi_a = G1.add( full_pi_a, proof.pi_a);
  8680. if (! bn128.F12.eq(
  8681. bn128.pairing( proof.pi_a , vk_verifier.vk_a ),
  8682. bn128.pairing( proof.pi_ap , G2.g )))
  8683. return false;
  8684. if (! bn128.F12.eq(
  8685. bn128.pairing( vk_verifier.vk_b, proof.pi_b ),
  8686. bn128.pairing( proof.pi_bp , G2.g )))
  8687. return false;
  8688. if (! bn128.F12.eq(
  8689. bn128.pairing( proof.pi_c , vk_verifier.vk_c ),
  8690. bn128.pairing( proof.pi_cp , G2.g )))
  8691. return false;
  8692. if (! bn128.F12.eq(
  8693. bn128.F12.mul(
  8694. bn128.pairing( G1.add(full_pi_a, proof.pi_c) , vk_verifier.vk_gb_2 ),
  8695. bn128.pairing( vk_verifier.vk_gb_1 , proof.pi_b )
  8696. ),
  8697. bn128.pairing( proof.pi_kp , vk_verifier.vk_g )))
  8698. return false;
  8699. if (! bn128.F12.eq(
  8700. bn128.pairing( full_pi_a , proof.pi_b ),
  8701. bn128.F12.mul(
  8702. bn128.pairing( proof.pi_h , vk_verifier.vk_z ),
  8703. bn128.pairing( proof.pi_c , G2.g )
  8704. )))
  8705. return false;
  8706. return true;
  8707. };
  8708. },{"ffjavascript":12}],51:[function(require,module,exports){
  8709. // Copyright Joyent, Inc. and other Node contributors.
  8710. //
  8711. // Permission is hereby granted, free of charge, to any person obtaining a
  8712. // copy of this software and associated documentation files (the
  8713. // "Software"), to deal in the Software without restriction, including
  8714. // without limitation the rights to use, copy, modify, merge, publish,
  8715. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8716. // persons to whom the Software is furnished to do so, subject to the
  8717. // following conditions:
  8718. //
  8719. // The above copyright notice and this permission notice shall be included
  8720. // in all copies or substantial portions of the Software.
  8721. //
  8722. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8723. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8724. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8725. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8726. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8727. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8728. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8729. module.exports = Stream;
  8730. var EE = require('events').EventEmitter;
  8731. var inherits = require('inherits');
  8732. inherits(Stream, EE);
  8733. Stream.Readable = require('readable-stream/readable.js');
  8734. Stream.Writable = require('readable-stream/writable.js');
  8735. Stream.Duplex = require('readable-stream/duplex.js');
  8736. Stream.Transform = require('readable-stream/transform.js');
  8737. Stream.PassThrough = require('readable-stream/passthrough.js');
  8738. // Backwards-compat with node 0.4.x
  8739. Stream.Stream = Stream;
  8740. // old-style streams. Note that the pipe method (the only relevant
  8741. // part of this class) is overridden in the Readable class.
  8742. function Stream() {
  8743. EE.call(this);
  8744. }
  8745. Stream.prototype.pipe = function(dest, options) {
  8746. var source = this;
  8747. function ondata(chunk) {
  8748. if (dest.writable) {
  8749. if (false === dest.write(chunk) && source.pause) {
  8750. source.pause();
  8751. }
  8752. }
  8753. }
  8754. source.on('data', ondata);
  8755. function ondrain() {
  8756. if (source.readable && source.resume) {
  8757. source.resume();
  8758. }
  8759. }
  8760. dest.on('drain', ondrain);
  8761. // If the 'end' option is not supplied, dest.end() will be called when
  8762. // source gets the 'end' or 'close' events. Only dest.end() once.
  8763. if (!dest._isStdio && (!options || options.end !== false)) {
  8764. source.on('end', onend);
  8765. source.on('close', onclose);
  8766. }
  8767. var didOnEnd = false;
  8768. function onend() {
  8769. if (didOnEnd) return;
  8770. didOnEnd = true;
  8771. dest.end();
  8772. }
  8773. function onclose() {
  8774. if (didOnEnd) return;
  8775. didOnEnd = true;
  8776. if (typeof dest.destroy === 'function') dest.destroy();
  8777. }
  8778. // don't leave dangling pipes when there are errors.
  8779. function onerror(er) {
  8780. cleanup();
  8781. if (EE.listenerCount(this, 'error') === 0) {
  8782. throw er; // Unhandled stream error in pipe.
  8783. }
  8784. }
  8785. source.on('error', onerror);
  8786. dest.on('error', onerror);
  8787. // remove all the event listeners that were added.
  8788. function cleanup() {
  8789. source.removeListener('data', ondata);
  8790. dest.removeListener('drain', ondrain);
  8791. source.removeListener('end', onend);
  8792. source.removeListener('close', onclose);
  8793. source.removeListener('error', onerror);
  8794. dest.removeListener('error', onerror);
  8795. source.removeListener('end', cleanup);
  8796. source.removeListener('close', cleanup);
  8797. dest.removeListener('close', cleanup);
  8798. }
  8799. source.on('end', cleanup);
  8800. source.on('close', cleanup);
  8801. dest.on('close', cleanup);
  8802. dest.emit('pipe', source);
  8803. // Allow for unix-like usage: A.pipe(B).pipe(C)
  8804. return dest;
  8805. };
  8806. },{"events":11,"inherits":29,"readable-stream/duplex.js":52,"readable-stream/passthrough.js":61,"readable-stream/readable.js":62,"readable-stream/transform.js":63,"readable-stream/writable.js":64}],52:[function(require,module,exports){
  8807. module.exports = require('./lib/_stream_duplex.js');
  8808. },{"./lib/_stream_duplex.js":53}],53:[function(require,module,exports){
  8809. // Copyright Joyent, Inc. and other Node contributors.
  8810. //
  8811. // Permission is hereby granted, free of charge, to any person obtaining a
  8812. // copy of this software and associated documentation files (the
  8813. // "Software"), to deal in the Software without restriction, including
  8814. // without limitation the rights to use, copy, modify, merge, publish,
  8815. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8816. // persons to whom the Software is furnished to do so, subject to the
  8817. // following conditions:
  8818. //
  8819. // The above copyright notice and this permission notice shall be included
  8820. // in all copies or substantial portions of the Software.
  8821. //
  8822. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8823. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8824. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8825. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8826. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8827. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8828. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8829. // a duplex stream is just a stream that is both readable and writable.
  8830. // Since JS doesn't have multiple prototypal inheritance, this class
  8831. // prototypally inherits from Readable, and then parasitically from
  8832. // Writable.
  8833. 'use strict';
  8834. /*<replacement>*/
  8835. var pna = require('process-nextick-args');
  8836. /*</replacement>*/
  8837. /*<replacement>*/
  8838. var objectKeys = Object.keys || function (obj) {
  8839. var keys = [];
  8840. for (var key in obj) {
  8841. keys.push(key);
  8842. }return keys;
  8843. };
  8844. /*</replacement>*/
  8845. module.exports = Duplex;
  8846. /*<replacement>*/
  8847. var util = Object.create(require('core-util-is'));
  8848. util.inherits = require('inherits');
  8849. /*</replacement>*/
  8850. var Readable = require('./_stream_readable');
  8851. var Writable = require('./_stream_writable');
  8852. util.inherits(Duplex, Readable);
  8853. {
  8854. // avoid scope creep, the keys array can then be collected
  8855. var keys = objectKeys(Writable.prototype);
  8856. for (var v = 0; v < keys.length; v++) {
  8857. var method = keys[v];
  8858. if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
  8859. }
  8860. }
  8861. function Duplex(options) {
  8862. if (!(this instanceof Duplex)) return new Duplex(options);
  8863. Readable.call(this, options);
  8864. Writable.call(this, options);
  8865. if (options && options.readable === false) this.readable = false;
  8866. if (options && options.writable === false) this.writable = false;
  8867. this.allowHalfOpen = true;
  8868. if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
  8869. this.once('end', onend);
  8870. }
  8871. Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
  8872. // making it explicit this property is not enumerable
  8873. // because otherwise some prototype manipulation in
  8874. // userland will fail
  8875. enumerable: false,
  8876. get: function () {
  8877. return this._writableState.highWaterMark;
  8878. }
  8879. });
  8880. // the no-half-open enforcer
  8881. function onend() {
  8882. // if we allow half-open state, or if the writable side ended,
  8883. // then we're ok.
  8884. if (this.allowHalfOpen || this._writableState.ended) return;
  8885. // no more data can be written.
  8886. // But allow more writes to happen in this tick.
  8887. pna.nextTick(onEndNT, this);
  8888. }
  8889. function onEndNT(self) {
  8890. self.end();
  8891. }
  8892. Object.defineProperty(Duplex.prototype, 'destroyed', {
  8893. get: function () {
  8894. if (this._readableState === undefined || this._writableState === undefined) {
  8895. return false;
  8896. }
  8897. return this._readableState.destroyed && this._writableState.destroyed;
  8898. },
  8899. set: function (value) {
  8900. // we ignore the value if the stream
  8901. // has not been initialized yet
  8902. if (this._readableState === undefined || this._writableState === undefined) {
  8903. return;
  8904. }
  8905. // backward compatibility, the user is explicitly
  8906. // managing destroyed
  8907. this._readableState.destroyed = value;
  8908. this._writableState.destroyed = value;
  8909. }
  8910. });
  8911. Duplex.prototype._destroy = function (err, cb) {
  8912. this.push(null);
  8913. this.end();
  8914. pna.nextTick(cb, err);
  8915. };
  8916. },{"./_stream_readable":55,"./_stream_writable":57,"core-util-is":10,"inherits":29,"process-nextick-args":39}],54:[function(require,module,exports){
  8917. // Copyright Joyent, Inc. and other Node contributors.
  8918. //
  8919. // Permission is hereby granted, free of charge, to any person obtaining a
  8920. // copy of this software and associated documentation files (the
  8921. // "Software"), to deal in the Software without restriction, including
  8922. // without limitation the rights to use, copy, modify, merge, publish,
  8923. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8924. // persons to whom the Software is furnished to do so, subject to the
  8925. // following conditions:
  8926. //
  8927. // The above copyright notice and this permission notice shall be included
  8928. // in all copies or substantial portions of the Software.
  8929. //
  8930. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8931. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8932. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8933. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8934. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8935. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8936. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8937. // a passthrough stream.
  8938. // basically just the most minimal sort of Transform stream.
  8939. // Every written chunk gets output as-is.
  8940. 'use strict';
  8941. module.exports = PassThrough;
  8942. var Transform = require('./_stream_transform');
  8943. /*<replacement>*/
  8944. var util = Object.create(require('core-util-is'));
  8945. util.inherits = require('inherits');
  8946. /*</replacement>*/
  8947. util.inherits(PassThrough, Transform);
  8948. function PassThrough(options) {
  8949. if (!(this instanceof PassThrough)) return new PassThrough(options);
  8950. Transform.call(this, options);
  8951. }
  8952. PassThrough.prototype._transform = function (chunk, encoding, cb) {
  8953. cb(null, chunk);
  8954. };
  8955. },{"./_stream_transform":56,"core-util-is":10,"inherits":29}],55:[function(require,module,exports){
  8956. (function (process,global){
  8957. // Copyright Joyent, Inc. and other Node contributors.
  8958. //
  8959. // Permission is hereby granted, free of charge, to any person obtaining a
  8960. // copy of this software and associated documentation files (the
  8961. // "Software"), to deal in the Software without restriction, including
  8962. // without limitation the rights to use, copy, modify, merge, publish,
  8963. // distribute, sublicense, and/or sell copies of the Software, and to permit
  8964. // persons to whom the Software is furnished to do so, subject to the
  8965. // following conditions:
  8966. //
  8967. // The above copyright notice and this permission notice shall be included
  8968. // in all copies or substantial portions of the Software.
  8969. //
  8970. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  8971. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  8972. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  8973. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  8974. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  8975. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  8976. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  8977. 'use strict';
  8978. /*<replacement>*/
  8979. var pna = require('process-nextick-args');
  8980. /*</replacement>*/
  8981. module.exports = Readable;
  8982. /*<replacement>*/
  8983. var isArray = require('isarray');
  8984. /*</replacement>*/
  8985. /*<replacement>*/
  8986. var Duplex;
  8987. /*</replacement>*/
  8988. Readable.ReadableState = ReadableState;
  8989. /*<replacement>*/
  8990. var EE = require('events').EventEmitter;
  8991. var EElistenerCount = function (emitter, type) {
  8992. return emitter.listeners(type).length;
  8993. };
  8994. /*</replacement>*/
  8995. /*<replacement>*/
  8996. var Stream = require('./internal/streams/stream');
  8997. /*</replacement>*/
  8998. /*<replacement>*/
  8999. var Buffer = require('safe-buffer').Buffer;
  9000. var OurUint8Array = global.Uint8Array || function () {};
  9001. function _uint8ArrayToBuffer(chunk) {
  9002. return Buffer.from(chunk);
  9003. }
  9004. function _isUint8Array(obj) {
  9005. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  9006. }
  9007. /*</replacement>*/
  9008. /*<replacement>*/
  9009. var util = Object.create(require('core-util-is'));
  9010. util.inherits = require('inherits');
  9011. /*</replacement>*/
  9012. /*<replacement>*/
  9013. var debugUtil = require('util');
  9014. var debug = void 0;
  9015. if (debugUtil && debugUtil.debuglog) {
  9016. debug = debugUtil.debuglog('stream');
  9017. } else {
  9018. debug = function () {};
  9019. }
  9020. /*</replacement>*/
  9021. var BufferList = require('./internal/streams/BufferList');
  9022. var destroyImpl = require('./internal/streams/destroy');
  9023. var StringDecoder;
  9024. util.inherits(Readable, Stream);
  9025. var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
  9026. function prependListener(emitter, event, fn) {
  9027. // Sadly this is not cacheable as some libraries bundle their own
  9028. // event emitter implementation with them.
  9029. if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
  9030. // This is a hack to make sure that our error handler is attached before any
  9031. // userland ones. NEVER DO THIS. This is here only because this code needs
  9032. // to continue to work with older versions of Node.js that do not include
  9033. // the prependListener() method. The goal is to eventually remove this hack.
  9034. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
  9035. }
  9036. function ReadableState(options, stream) {
  9037. Duplex = Duplex || require('./_stream_duplex');
  9038. options = options || {};
  9039. // Duplex streams are both readable and writable, but share
  9040. // the same options object.
  9041. // However, some cases require setting options to different
  9042. // values for the readable and the writable sides of the duplex stream.
  9043. // These options can be provided separately as readableXXX and writableXXX.
  9044. var isDuplex = stream instanceof Duplex;
  9045. // object stream flag. Used to make read(n) ignore n and to
  9046. // make all the buffer merging and length checks go away
  9047. this.objectMode = !!options.objectMode;
  9048. if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
  9049. // the point at which it stops calling _read() to fill the buffer
  9050. // Note: 0 is a valid value, means "don't call _read preemptively ever"
  9051. var hwm = options.highWaterMark;
  9052. var readableHwm = options.readableHighWaterMark;
  9053. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  9054. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
  9055. // cast to ints.
  9056. this.highWaterMark = Math.floor(this.highWaterMark);
  9057. // A linked list is used to store data chunks instead of an array because the
  9058. // linked list can remove elements from the beginning faster than
  9059. // array.shift()
  9060. this.buffer = new BufferList();
  9061. this.length = 0;
  9062. this.pipes = null;
  9063. this.pipesCount = 0;
  9064. this.flowing = null;
  9065. this.ended = false;
  9066. this.endEmitted = false;
  9067. this.reading = false;
  9068. // a flag to be able to tell if the event 'readable'/'data' is emitted
  9069. // immediately, or on a later tick. We set this to true at first, because
  9070. // any actions that shouldn't happen until "later" should generally also
  9071. // not happen before the first read call.
  9072. this.sync = true;
  9073. // whenever we return null, then we set a flag to say
  9074. // that we're awaiting a 'readable' event emission.
  9075. this.needReadable = false;
  9076. this.emittedReadable = false;
  9077. this.readableListening = false;
  9078. this.resumeScheduled = false;
  9079. // has it been destroyed
  9080. this.destroyed = false;
  9081. // Crypto is kind of old and crusty. Historically, its default string
  9082. // encoding is 'binary' so we have to make this configurable.
  9083. // Everything else in the universe uses 'utf8', though.
  9084. this.defaultEncoding = options.defaultEncoding || 'utf8';
  9085. // the number of writers that are awaiting a drain event in .pipe()s
  9086. this.awaitDrain = 0;
  9087. // if true, a maybeReadMore has been scheduled
  9088. this.readingMore = false;
  9089. this.decoder = null;
  9090. this.encoding = null;
  9091. if (options.encoding) {
  9092. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  9093. this.decoder = new StringDecoder(options.encoding);
  9094. this.encoding = options.encoding;
  9095. }
  9096. }
  9097. function Readable(options) {
  9098. Duplex = Duplex || require('./_stream_duplex');
  9099. if (!(this instanceof Readable)) return new Readable(options);
  9100. this._readableState = new ReadableState(options, this);
  9101. // legacy
  9102. this.readable = true;
  9103. if (options) {
  9104. if (typeof options.read === 'function') this._read = options.read;
  9105. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  9106. }
  9107. Stream.call(this);
  9108. }
  9109. Object.defineProperty(Readable.prototype, 'destroyed', {
  9110. get: function () {
  9111. if (this._readableState === undefined) {
  9112. return false;
  9113. }
  9114. return this._readableState.destroyed;
  9115. },
  9116. set: function (value) {
  9117. // we ignore the value if the stream
  9118. // has not been initialized yet
  9119. if (!this._readableState) {
  9120. return;
  9121. }
  9122. // backward compatibility, the user is explicitly
  9123. // managing destroyed
  9124. this._readableState.destroyed = value;
  9125. }
  9126. });
  9127. Readable.prototype.destroy = destroyImpl.destroy;
  9128. Readable.prototype._undestroy = destroyImpl.undestroy;
  9129. Readable.prototype._destroy = function (err, cb) {
  9130. this.push(null);
  9131. cb(err);
  9132. };
  9133. // Manually shove something into the read() buffer.
  9134. // This returns true if the highWaterMark has not been hit yet,
  9135. // similar to how Writable.write() returns true if you should
  9136. // write() some more.
  9137. Readable.prototype.push = function (chunk, encoding) {
  9138. var state = this._readableState;
  9139. var skipChunkCheck;
  9140. if (!state.objectMode) {
  9141. if (typeof chunk === 'string') {
  9142. encoding = encoding || state.defaultEncoding;
  9143. if (encoding !== state.encoding) {
  9144. chunk = Buffer.from(chunk, encoding);
  9145. encoding = '';
  9146. }
  9147. skipChunkCheck = true;
  9148. }
  9149. } else {
  9150. skipChunkCheck = true;
  9151. }
  9152. return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
  9153. };
  9154. // Unshift should *always* be something directly out of read()
  9155. Readable.prototype.unshift = function (chunk) {
  9156. return readableAddChunk(this, chunk, null, true, false);
  9157. };
  9158. function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
  9159. var state = stream._readableState;
  9160. if (chunk === null) {
  9161. state.reading = false;
  9162. onEofChunk(stream, state);
  9163. } else {
  9164. var er;
  9165. if (!skipChunkCheck) er = chunkInvalid(state, chunk);
  9166. if (er) {
  9167. stream.emit('error', er);
  9168. } else if (state.objectMode || chunk && chunk.length > 0) {
  9169. if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
  9170. chunk = _uint8ArrayToBuffer(chunk);
  9171. }
  9172. if (addToFront) {
  9173. if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
  9174. } else if (state.ended) {
  9175. stream.emit('error', new Error('stream.push() after EOF'));
  9176. } else {
  9177. state.reading = false;
  9178. if (state.decoder && !encoding) {
  9179. chunk = state.decoder.write(chunk);
  9180. if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
  9181. } else {
  9182. addChunk(stream, state, chunk, false);
  9183. }
  9184. }
  9185. } else if (!addToFront) {
  9186. state.reading = false;
  9187. }
  9188. }
  9189. return needMoreData(state);
  9190. }
  9191. function addChunk(stream, state, chunk, addToFront) {
  9192. if (state.flowing && state.length === 0 && !state.sync) {
  9193. stream.emit('data', chunk);
  9194. stream.read(0);
  9195. } else {
  9196. // update the buffer info.
  9197. state.length += state.objectMode ? 1 : chunk.length;
  9198. if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
  9199. if (state.needReadable) emitReadable(stream);
  9200. }
  9201. maybeReadMore(stream, state);
  9202. }
  9203. function chunkInvalid(state, chunk) {
  9204. var er;
  9205. if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  9206. er = new TypeError('Invalid non-string/buffer chunk');
  9207. }
  9208. return er;
  9209. }
  9210. // if it's past the high water mark, we can push in some more.
  9211. // Also, if we have no data yet, we can stand some
  9212. // more bytes. This is to work around cases where hwm=0,
  9213. // such as the repl. Also, if the push() triggered a
  9214. // readable event, and the user called read(largeNumber) such that
  9215. // needReadable was set, then we ought to push more, so that another
  9216. // 'readable' event will be triggered.
  9217. function needMoreData(state) {
  9218. return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
  9219. }
  9220. Readable.prototype.isPaused = function () {
  9221. return this._readableState.flowing === false;
  9222. };
  9223. // backwards compatibility.
  9224. Readable.prototype.setEncoding = function (enc) {
  9225. if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
  9226. this._readableState.decoder = new StringDecoder(enc);
  9227. this._readableState.encoding = enc;
  9228. return this;
  9229. };
  9230. // Don't raise the hwm > 8MB
  9231. var MAX_HWM = 0x800000;
  9232. function computeNewHighWaterMark(n) {
  9233. if (n >= MAX_HWM) {
  9234. n = MAX_HWM;
  9235. } else {
  9236. // Get the next highest power of 2 to prevent increasing hwm excessively in
  9237. // tiny amounts
  9238. n--;
  9239. n |= n >>> 1;
  9240. n |= n >>> 2;
  9241. n |= n >>> 4;
  9242. n |= n >>> 8;
  9243. n |= n >>> 16;
  9244. n++;
  9245. }
  9246. return n;
  9247. }
  9248. // This function is designed to be inlinable, so please take care when making
  9249. // changes to the function body.
  9250. function howMuchToRead(n, state) {
  9251. if (n <= 0 || state.length === 0 && state.ended) return 0;
  9252. if (state.objectMode) return 1;
  9253. if (n !== n) {
  9254. // Only flow one buffer at a time
  9255. if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
  9256. }
  9257. // If we're asking for more than the current hwm, then raise the hwm.
  9258. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
  9259. if (n <= state.length) return n;
  9260. // Don't have enough
  9261. if (!state.ended) {
  9262. state.needReadable = true;
  9263. return 0;
  9264. }
  9265. return state.length;
  9266. }
  9267. // you can override either this method, or the async _read(n) below.
  9268. Readable.prototype.read = function (n) {
  9269. debug('read', n);
  9270. n = parseInt(n, 10);
  9271. var state = this._readableState;
  9272. var nOrig = n;
  9273. if (n !== 0) state.emittedReadable = false;
  9274. // if we're doing read(0) to trigger a readable event, but we
  9275. // already have a bunch of data in the buffer, then just trigger
  9276. // the 'readable' event and move on.
  9277. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
  9278. debug('read: emitReadable', state.length, state.ended);
  9279. if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
  9280. return null;
  9281. }
  9282. n = howMuchToRead(n, state);
  9283. // if we've ended, and we're now clear, then finish it up.
  9284. if (n === 0 && state.ended) {
  9285. if (state.length === 0) endReadable(this);
  9286. return null;
  9287. }
  9288. // All the actual chunk generation logic needs to be
  9289. // *below* the call to _read. The reason is that in certain
  9290. // synthetic stream cases, such as passthrough streams, _read
  9291. // may be a completely synchronous operation which may change
  9292. // the state of the read buffer, providing enough data when
  9293. // before there was *not* enough.
  9294. //
  9295. // So, the steps are:
  9296. // 1. Figure out what the state of things will be after we do
  9297. // a read from the buffer.
  9298. //
  9299. // 2. If that resulting state will trigger a _read, then call _read.
  9300. // Note that this may be asynchronous, or synchronous. Yes, it is
  9301. // deeply ugly to write APIs this way, but that still doesn't mean
  9302. // that the Readable class should behave improperly, as streams are
  9303. // designed to be sync/async agnostic.
  9304. // Take note if the _read call is sync or async (ie, if the read call
  9305. // has returned yet), so that we know whether or not it's safe to emit
  9306. // 'readable' etc.
  9307. //
  9308. // 3. Actually pull the requested chunks out of the buffer and return.
  9309. // if we need a readable event, then we need to do some reading.
  9310. var doRead = state.needReadable;
  9311. debug('need readable', doRead);
  9312. // if we currently have less than the highWaterMark, then also read some
  9313. if (state.length === 0 || state.length - n < state.highWaterMark) {
  9314. doRead = true;
  9315. debug('length less than watermark', doRead);
  9316. }
  9317. // however, if we've ended, then there's no point, and if we're already
  9318. // reading, then it's unnecessary.
  9319. if (state.ended || state.reading) {
  9320. doRead = false;
  9321. debug('reading or ended', doRead);
  9322. } else if (doRead) {
  9323. debug('do read');
  9324. state.reading = true;
  9325. state.sync = true;
  9326. // if the length is currently zero, then we *need* a readable event.
  9327. if (state.length === 0) state.needReadable = true;
  9328. // call internal read method
  9329. this._read(state.highWaterMark);
  9330. state.sync = false;
  9331. // If _read pushed data synchronously, then `reading` will be false,
  9332. // and we need to re-evaluate how much data we can return to the user.
  9333. if (!state.reading) n = howMuchToRead(nOrig, state);
  9334. }
  9335. var ret;
  9336. if (n > 0) ret = fromList(n, state);else ret = null;
  9337. if (ret === null) {
  9338. state.needReadable = true;
  9339. n = 0;
  9340. } else {
  9341. state.length -= n;
  9342. }
  9343. if (state.length === 0) {
  9344. // If we have nothing in the buffer, then we want to know
  9345. // as soon as we *do* get something into the buffer.
  9346. if (!state.ended) state.needReadable = true;
  9347. // If we tried to read() past the EOF, then emit end on the next tick.
  9348. if (nOrig !== n && state.ended) endReadable(this);
  9349. }
  9350. if (ret !== null) this.emit('data', ret);
  9351. return ret;
  9352. };
  9353. function onEofChunk(stream, state) {
  9354. if (state.ended) return;
  9355. if (state.decoder) {
  9356. var chunk = state.decoder.end();
  9357. if (chunk && chunk.length) {
  9358. state.buffer.push(chunk);
  9359. state.length += state.objectMode ? 1 : chunk.length;
  9360. }
  9361. }
  9362. state.ended = true;
  9363. // emit 'readable' now to make sure it gets picked up.
  9364. emitReadable(stream);
  9365. }
  9366. // Don't emit readable right away in sync mode, because this can trigger
  9367. // another read() call => stack overflow. This way, it might trigger
  9368. // a nextTick recursion warning, but that's not so bad.
  9369. function emitReadable(stream) {
  9370. var state = stream._readableState;
  9371. state.needReadable = false;
  9372. if (!state.emittedReadable) {
  9373. debug('emitReadable', state.flowing);
  9374. state.emittedReadable = true;
  9375. if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
  9376. }
  9377. }
  9378. function emitReadable_(stream) {
  9379. debug('emit readable');
  9380. stream.emit('readable');
  9381. flow(stream);
  9382. }
  9383. // at this point, the user has presumably seen the 'readable' event,
  9384. // and called read() to consume some data. that may have triggered
  9385. // in turn another _read(n) call, in which case reading = true if
  9386. // it's in progress.
  9387. // However, if we're not ended, or reading, and the length < hwm,
  9388. // then go ahead and try to read some more preemptively.
  9389. function maybeReadMore(stream, state) {
  9390. if (!state.readingMore) {
  9391. state.readingMore = true;
  9392. pna.nextTick(maybeReadMore_, stream, state);
  9393. }
  9394. }
  9395. function maybeReadMore_(stream, state) {
  9396. var len = state.length;
  9397. while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
  9398. debug('maybeReadMore read 0');
  9399. stream.read(0);
  9400. if (len === state.length)
  9401. // didn't get any data, stop spinning.
  9402. break;else len = state.length;
  9403. }
  9404. state.readingMore = false;
  9405. }
  9406. // abstract method. to be overridden in specific implementation classes.
  9407. // call cb(er, data) where data is <= n in length.
  9408. // for virtual (non-string, non-buffer) streams, "length" is somewhat
  9409. // arbitrary, and perhaps not very meaningful.
  9410. Readable.prototype._read = function (n) {
  9411. this.emit('error', new Error('_read() is not implemented'));
  9412. };
  9413. Readable.prototype.pipe = function (dest, pipeOpts) {
  9414. var src = this;
  9415. var state = this._readableState;
  9416. switch (state.pipesCount) {
  9417. case 0:
  9418. state.pipes = dest;
  9419. break;
  9420. case 1:
  9421. state.pipes = [state.pipes, dest];
  9422. break;
  9423. default:
  9424. state.pipes.push(dest);
  9425. break;
  9426. }
  9427. state.pipesCount += 1;
  9428. debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
  9429. var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
  9430. var endFn = doEnd ? onend : unpipe;
  9431. if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
  9432. dest.on('unpipe', onunpipe);
  9433. function onunpipe(readable, unpipeInfo) {
  9434. debug('onunpipe');
  9435. if (readable === src) {
  9436. if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
  9437. unpipeInfo.hasUnpiped = true;
  9438. cleanup();
  9439. }
  9440. }
  9441. }
  9442. function onend() {
  9443. debug('onend');
  9444. dest.end();
  9445. }
  9446. // when the dest drains, it reduces the awaitDrain counter
  9447. // on the source. This would be more elegant with a .once()
  9448. // handler in flow(), but adding and removing repeatedly is
  9449. // too slow.
  9450. var ondrain = pipeOnDrain(src);
  9451. dest.on('drain', ondrain);
  9452. var cleanedUp = false;
  9453. function cleanup() {
  9454. debug('cleanup');
  9455. // cleanup event handlers once the pipe is broken
  9456. dest.removeListener('close', onclose);
  9457. dest.removeListener('finish', onfinish);
  9458. dest.removeListener('drain', ondrain);
  9459. dest.removeListener('error', onerror);
  9460. dest.removeListener('unpipe', onunpipe);
  9461. src.removeListener('end', onend);
  9462. src.removeListener('end', unpipe);
  9463. src.removeListener('data', ondata);
  9464. cleanedUp = true;
  9465. // if the reader is waiting for a drain event from this
  9466. // specific writer, then it would cause it to never start
  9467. // flowing again.
  9468. // So, if this is awaiting a drain, then we just call it now.
  9469. // If we don't know, then assume that we are waiting for one.
  9470. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
  9471. }
  9472. // If the user pushes more data while we're writing to dest then we'll end up
  9473. // in ondata again. However, we only want to increase awaitDrain once because
  9474. // dest will only emit one 'drain' event for the multiple writes.
  9475. // => Introduce a guard on increasing awaitDrain.
  9476. var increasedAwaitDrain = false;
  9477. src.on('data', ondata);
  9478. function ondata(chunk) {
  9479. debug('ondata');
  9480. increasedAwaitDrain = false;
  9481. var ret = dest.write(chunk);
  9482. if (false === ret && !increasedAwaitDrain) {
  9483. // If the user unpiped during `dest.write()`, it is possible
  9484. // to get stuck in a permanently paused state if that write
  9485. // also returned false.
  9486. // => Check whether `dest` is still a piping destination.
  9487. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
  9488. debug('false write response, pause', src._readableState.awaitDrain);
  9489. src._readableState.awaitDrain++;
  9490. increasedAwaitDrain = true;
  9491. }
  9492. src.pause();
  9493. }
  9494. }
  9495. // if the dest has an error, then stop piping into it.
  9496. // however, don't suppress the throwing behavior for this.
  9497. function onerror(er) {
  9498. debug('onerror', er);
  9499. unpipe();
  9500. dest.removeListener('error', onerror);
  9501. if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
  9502. }
  9503. // Make sure our error handler is attached before userland ones.
  9504. prependListener(dest, 'error', onerror);
  9505. // Both close and finish should trigger unpipe, but only once.
  9506. function onclose() {
  9507. dest.removeListener('finish', onfinish);
  9508. unpipe();
  9509. }
  9510. dest.once('close', onclose);
  9511. function onfinish() {
  9512. debug('onfinish');
  9513. dest.removeListener('close', onclose);
  9514. unpipe();
  9515. }
  9516. dest.once('finish', onfinish);
  9517. function unpipe() {
  9518. debug('unpipe');
  9519. src.unpipe(dest);
  9520. }
  9521. // tell the dest that it's being piped to
  9522. dest.emit('pipe', src);
  9523. // start the flow if it hasn't been started already.
  9524. if (!state.flowing) {
  9525. debug('pipe resume');
  9526. src.resume();
  9527. }
  9528. return dest;
  9529. };
  9530. function pipeOnDrain(src) {
  9531. return function () {
  9532. var state = src._readableState;
  9533. debug('pipeOnDrain', state.awaitDrain);
  9534. if (state.awaitDrain) state.awaitDrain--;
  9535. if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
  9536. state.flowing = true;
  9537. flow(src);
  9538. }
  9539. };
  9540. }
  9541. Readable.prototype.unpipe = function (dest) {
  9542. var state = this._readableState;
  9543. var unpipeInfo = { hasUnpiped: false };
  9544. // if we're not piping anywhere, then do nothing.
  9545. if (state.pipesCount === 0) return this;
  9546. // just one destination. most common case.
  9547. if (state.pipesCount === 1) {
  9548. // passed in one, but it's not the right one.
  9549. if (dest && dest !== state.pipes) return this;
  9550. if (!dest) dest = state.pipes;
  9551. // got a match.
  9552. state.pipes = null;
  9553. state.pipesCount = 0;
  9554. state.flowing = false;
  9555. if (dest) dest.emit('unpipe', this, unpipeInfo);
  9556. return this;
  9557. }
  9558. // slow case. multiple pipe destinations.
  9559. if (!dest) {
  9560. // remove all.
  9561. var dests = state.pipes;
  9562. var len = state.pipesCount;
  9563. state.pipes = null;
  9564. state.pipesCount = 0;
  9565. state.flowing = false;
  9566. for (var i = 0; i < len; i++) {
  9567. dests[i].emit('unpipe', this, unpipeInfo);
  9568. }return this;
  9569. }
  9570. // try to find the right one.
  9571. var index = indexOf(state.pipes, dest);
  9572. if (index === -1) return this;
  9573. state.pipes.splice(index, 1);
  9574. state.pipesCount -= 1;
  9575. if (state.pipesCount === 1) state.pipes = state.pipes[0];
  9576. dest.emit('unpipe', this, unpipeInfo);
  9577. return this;
  9578. };
  9579. // set up data events if they are asked for
  9580. // Ensure readable listeners eventually get something
  9581. Readable.prototype.on = function (ev, fn) {
  9582. var res = Stream.prototype.on.call(this, ev, fn);
  9583. if (ev === 'data') {
  9584. // Start flowing on next tick if stream isn't explicitly paused
  9585. if (this._readableState.flowing !== false) this.resume();
  9586. } else if (ev === 'readable') {
  9587. var state = this._readableState;
  9588. if (!state.endEmitted && !state.readableListening) {
  9589. state.readableListening = state.needReadable = true;
  9590. state.emittedReadable = false;
  9591. if (!state.reading) {
  9592. pna.nextTick(nReadingNextTick, this);
  9593. } else if (state.length) {
  9594. emitReadable(this);
  9595. }
  9596. }
  9597. }
  9598. return res;
  9599. };
  9600. Readable.prototype.addListener = Readable.prototype.on;
  9601. function nReadingNextTick(self) {
  9602. debug('readable nexttick read 0');
  9603. self.read(0);
  9604. }
  9605. // pause() and resume() are remnants of the legacy readable stream API
  9606. // If the user uses them, then switch into old mode.
  9607. Readable.prototype.resume = function () {
  9608. var state = this._readableState;
  9609. if (!state.flowing) {
  9610. debug('resume');
  9611. state.flowing = true;
  9612. resume(this, state);
  9613. }
  9614. return this;
  9615. };
  9616. function resume(stream, state) {
  9617. if (!state.resumeScheduled) {
  9618. state.resumeScheduled = true;
  9619. pna.nextTick(resume_, stream, state);
  9620. }
  9621. }
  9622. function resume_(stream, state) {
  9623. if (!state.reading) {
  9624. debug('resume read 0');
  9625. stream.read(0);
  9626. }
  9627. state.resumeScheduled = false;
  9628. state.awaitDrain = 0;
  9629. stream.emit('resume');
  9630. flow(stream);
  9631. if (state.flowing && !state.reading) stream.read(0);
  9632. }
  9633. Readable.prototype.pause = function () {
  9634. debug('call pause flowing=%j', this._readableState.flowing);
  9635. if (false !== this._readableState.flowing) {
  9636. debug('pause');
  9637. this._readableState.flowing = false;
  9638. this.emit('pause');
  9639. }
  9640. return this;
  9641. };
  9642. function flow(stream) {
  9643. var state = stream._readableState;
  9644. debug('flow', state.flowing);
  9645. while (state.flowing && stream.read() !== null) {}
  9646. }
  9647. // wrap an old-style stream as the async data source.
  9648. // This is *not* part of the readable stream interface.
  9649. // It is an ugly unfortunate mess of history.
  9650. Readable.prototype.wrap = function (stream) {
  9651. var _this = this;
  9652. var state = this._readableState;
  9653. var paused = false;
  9654. stream.on('end', function () {
  9655. debug('wrapped end');
  9656. if (state.decoder && !state.ended) {
  9657. var chunk = state.decoder.end();
  9658. if (chunk && chunk.length) _this.push(chunk);
  9659. }
  9660. _this.push(null);
  9661. });
  9662. stream.on('data', function (chunk) {
  9663. debug('wrapped data');
  9664. if (state.decoder) chunk = state.decoder.write(chunk);
  9665. // don't skip over falsy values in objectMode
  9666. if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
  9667. var ret = _this.push(chunk);
  9668. if (!ret) {
  9669. paused = true;
  9670. stream.pause();
  9671. }
  9672. });
  9673. // proxy all the other methods.
  9674. // important when wrapping filters and duplexes.
  9675. for (var i in stream) {
  9676. if (this[i] === undefined && typeof stream[i] === 'function') {
  9677. this[i] = function (method) {
  9678. return function () {
  9679. return stream[method].apply(stream, arguments);
  9680. };
  9681. }(i);
  9682. }
  9683. }
  9684. // proxy certain important events.
  9685. for (var n = 0; n < kProxyEvents.length; n++) {
  9686. stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
  9687. }
  9688. // when we try to consume some more bytes, simply unpause the
  9689. // underlying stream.
  9690. this._read = function (n) {
  9691. debug('wrapped _read', n);
  9692. if (paused) {
  9693. paused = false;
  9694. stream.resume();
  9695. }
  9696. };
  9697. return this;
  9698. };
  9699. Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
  9700. // making it explicit this property is not enumerable
  9701. // because otherwise some prototype manipulation in
  9702. // userland will fail
  9703. enumerable: false,
  9704. get: function () {
  9705. return this._readableState.highWaterMark;
  9706. }
  9707. });
  9708. // exposed for testing purposes only.
  9709. Readable._fromList = fromList;
  9710. // Pluck off n bytes from an array of buffers.
  9711. // Length is the combined lengths of all the buffers in the list.
  9712. // This function is designed to be inlinable, so please take care when making
  9713. // changes to the function body.
  9714. function fromList(n, state) {
  9715. // nothing buffered
  9716. if (state.length === 0) return null;
  9717. var ret;
  9718. if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
  9719. // read it all, truncate the list
  9720. if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length);
  9721. state.buffer.clear();
  9722. } else {
  9723. // read part of list
  9724. ret = fromListPartial(n, state.buffer, state.decoder);
  9725. }
  9726. return ret;
  9727. }
  9728. // Extracts only enough buffered data to satisfy the amount requested.
  9729. // This function is designed to be inlinable, so please take care when making
  9730. // changes to the function body.
  9731. function fromListPartial(n, list, hasStrings) {
  9732. var ret;
  9733. if (n < list.head.data.length) {
  9734. // slice is the same for buffers and strings
  9735. ret = list.head.data.slice(0, n);
  9736. list.head.data = list.head.data.slice(n);
  9737. } else if (n === list.head.data.length) {
  9738. // first chunk is a perfect match
  9739. ret = list.shift();
  9740. } else {
  9741. // result spans more than one buffer
  9742. ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
  9743. }
  9744. return ret;
  9745. }
  9746. // Copies a specified amount of characters from the list of buffered data
  9747. // chunks.
  9748. // This function is designed to be inlinable, so please take care when making
  9749. // changes to the function body.
  9750. function copyFromBufferString(n, list) {
  9751. var p = list.head;
  9752. var c = 1;
  9753. var ret = p.data;
  9754. n -= ret.length;
  9755. while (p = p.next) {
  9756. var str = p.data;
  9757. var nb = n > str.length ? str.length : n;
  9758. if (nb === str.length) ret += str;else ret += str.slice(0, n);
  9759. n -= nb;
  9760. if (n === 0) {
  9761. if (nb === str.length) {
  9762. ++c;
  9763. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9764. } else {
  9765. list.head = p;
  9766. p.data = str.slice(nb);
  9767. }
  9768. break;
  9769. }
  9770. ++c;
  9771. }
  9772. list.length -= c;
  9773. return ret;
  9774. }
  9775. // Copies a specified amount of bytes from the list of buffered data chunks.
  9776. // This function is designed to be inlinable, so please take care when making
  9777. // changes to the function body.
  9778. function copyFromBuffer(n, list) {
  9779. var ret = Buffer.allocUnsafe(n);
  9780. var p = list.head;
  9781. var c = 1;
  9782. p.data.copy(ret);
  9783. n -= p.data.length;
  9784. while (p = p.next) {
  9785. var buf = p.data;
  9786. var nb = n > buf.length ? buf.length : n;
  9787. buf.copy(ret, ret.length - n, 0, nb);
  9788. n -= nb;
  9789. if (n === 0) {
  9790. if (nb === buf.length) {
  9791. ++c;
  9792. if (p.next) list.head = p.next;else list.head = list.tail = null;
  9793. } else {
  9794. list.head = p;
  9795. p.data = buf.slice(nb);
  9796. }
  9797. break;
  9798. }
  9799. ++c;
  9800. }
  9801. list.length -= c;
  9802. return ret;
  9803. }
  9804. function endReadable(stream) {
  9805. var state = stream._readableState;
  9806. // If we get here before consuming all the bytes, then that is a
  9807. // bug in node. Should never happen.
  9808. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
  9809. if (!state.endEmitted) {
  9810. state.ended = true;
  9811. pna.nextTick(endReadableNT, state, stream);
  9812. }
  9813. }
  9814. function endReadableNT(state, stream) {
  9815. // Check that we didn't get one last unshift.
  9816. if (!state.endEmitted && state.length === 0) {
  9817. state.endEmitted = true;
  9818. stream.readable = false;
  9819. stream.emit('end');
  9820. }
  9821. }
  9822. function indexOf(xs, x) {
  9823. for (var i = 0, l = xs.length; i < l; i++) {
  9824. if (xs[i] === x) return i;
  9825. }
  9826. return -1;
  9827. }
  9828. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  9829. },{"./_stream_duplex":53,"./internal/streams/BufferList":58,"./internal/streams/destroy":59,"./internal/streams/stream":60,"_process":9,"core-util-is":10,"events":11,"inherits":29,"isarray":31,"process-nextick-args":39,"safe-buffer":40,"string_decoder/":65,"util":7}],56:[function(require,module,exports){
  9830. // Copyright Joyent, Inc. and other Node contributors.
  9831. //
  9832. // Permission is hereby granted, free of charge, to any person obtaining a
  9833. // copy of this software and associated documentation files (the
  9834. // "Software"), to deal in the Software without restriction, including
  9835. // without limitation the rights to use, copy, modify, merge, publish,
  9836. // distribute, sublicense, and/or sell copies of the Software, and to permit
  9837. // persons to whom the Software is furnished to do so, subject to the
  9838. // following conditions:
  9839. //
  9840. // The above copyright notice and this permission notice shall be included
  9841. // in all copies or substantial portions of the Software.
  9842. //
  9843. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  9844. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  9845. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  9846. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  9847. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  9848. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  9849. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  9850. // a transform stream is a readable/writable stream where you do
  9851. // something with the data. Sometimes it's called a "filter",
  9852. // but that's not a great name for it, since that implies a thing where
  9853. // some bits pass through, and others are simply ignored. (That would
  9854. // be a valid example of a transform, of course.)
  9855. //
  9856. // While the output is causally related to the input, it's not a
  9857. // necessarily symmetric or synchronous transformation. For example,
  9858. // a zlib stream might take multiple plain-text writes(), and then
  9859. // emit a single compressed chunk some time in the future.
  9860. //
  9861. // Here's how this works:
  9862. //
  9863. // The Transform stream has all the aspects of the readable and writable
  9864. // stream classes. When you write(chunk), that calls _write(chunk,cb)
  9865. // internally, and returns false if there's a lot of pending writes
  9866. // buffered up. When you call read(), that calls _read(n) until
  9867. // there's enough pending readable data buffered up.
  9868. //
  9869. // In a transform stream, the written data is placed in a buffer. When
  9870. // _read(n) is called, it transforms the queued up data, calling the
  9871. // buffered _write cb's as it consumes chunks. If consuming a single
  9872. // written chunk would result in multiple output chunks, then the first
  9873. // outputted bit calls the readcb, and subsequent chunks just go into
  9874. // the read buffer, and will cause it to emit 'readable' if necessary.
  9875. //
  9876. // This way, back-pressure is actually determined by the reading side,
  9877. // since _read has to be called to start processing a new chunk. However,
  9878. // a pathological inflate type of transform can cause excessive buffering
  9879. // here. For example, imagine a stream where every byte of input is
  9880. // interpreted as an integer from 0-255, and then results in that many
  9881. // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
  9882. // 1kb of data being output. In this case, you could write a very small
  9883. // amount of input, and end up with a very large amount of output. In
  9884. // such a pathological inflating mechanism, there'd be no way to tell
  9885. // the system to stop doing the transform. A single 4MB write could
  9886. // cause the system to run out of memory.
  9887. //
  9888. // However, even in such a pathological case, only a single written chunk
  9889. // would be consumed, and then the rest would wait (un-transformed) until
  9890. // the results of the previous transformed chunk were consumed.
  9891. 'use strict';
  9892. module.exports = Transform;
  9893. var Duplex = require('./_stream_duplex');
  9894. /*<replacement>*/
  9895. var util = Object.create(require('core-util-is'));
  9896. util.inherits = require('inherits');
  9897. /*</replacement>*/
  9898. util.inherits(Transform, Duplex);
  9899. function afterTransform(er, data) {
  9900. var ts = this._transformState;
  9901. ts.transforming = false;
  9902. var cb = ts.writecb;
  9903. if (!cb) {
  9904. return this.emit('error', new Error('write callback called multiple times'));
  9905. }
  9906. ts.writechunk = null;
  9907. ts.writecb = null;
  9908. if (data != null) // single equals check for both `null` and `undefined`
  9909. this.push(data);
  9910. cb(er);
  9911. var rs = this._readableState;
  9912. rs.reading = false;
  9913. if (rs.needReadable || rs.length < rs.highWaterMark) {
  9914. this._read(rs.highWaterMark);
  9915. }
  9916. }
  9917. function Transform(options) {
  9918. if (!(this instanceof Transform)) return new Transform(options);
  9919. Duplex.call(this, options);
  9920. this._transformState = {
  9921. afterTransform: afterTransform.bind(this),
  9922. needTransform: false,
  9923. transforming: false,
  9924. writecb: null,
  9925. writechunk: null,
  9926. writeencoding: null
  9927. };
  9928. // start out asking for a readable event once data is transformed.
  9929. this._readableState.needReadable = true;
  9930. // we have implemented the _read method, and done the other things
  9931. // that Readable wants before the first _read call, so unset the
  9932. // sync guard flag.
  9933. this._readableState.sync = false;
  9934. if (options) {
  9935. if (typeof options.transform === 'function') this._transform = options.transform;
  9936. if (typeof options.flush === 'function') this._flush = options.flush;
  9937. }
  9938. // When the writable side finishes, then flush out anything remaining.
  9939. this.on('prefinish', prefinish);
  9940. }
  9941. function prefinish() {
  9942. var _this = this;
  9943. if (typeof this._flush === 'function') {
  9944. this._flush(function (er, data) {
  9945. done(_this, er, data);
  9946. });
  9947. } else {
  9948. done(this, null, null);
  9949. }
  9950. }
  9951. Transform.prototype.push = function (chunk, encoding) {
  9952. this._transformState.needTransform = false;
  9953. return Duplex.prototype.push.call(this, chunk, encoding);
  9954. };
  9955. // This is the part where you do stuff!
  9956. // override this function in implementation classes.
  9957. // 'chunk' is an input chunk.
  9958. //
  9959. // Call `push(newChunk)` to pass along transformed output
  9960. // to the readable side. You may call 'push' zero or more times.
  9961. //
  9962. // Call `cb(err)` when you are done with this chunk. If you pass
  9963. // an error, then that'll put the hurt on the whole operation. If you
  9964. // never call cb(), then you'll never get another chunk.
  9965. Transform.prototype._transform = function (chunk, encoding, cb) {
  9966. throw new Error('_transform() is not implemented');
  9967. };
  9968. Transform.prototype._write = function (chunk, encoding, cb) {
  9969. var ts = this._transformState;
  9970. ts.writecb = cb;
  9971. ts.writechunk = chunk;
  9972. ts.writeencoding = encoding;
  9973. if (!ts.transforming) {
  9974. var rs = this._readableState;
  9975. if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
  9976. }
  9977. };
  9978. // Doesn't matter what the args are here.
  9979. // _transform does all the work.
  9980. // That we got here means that the readable side wants more data.
  9981. Transform.prototype._read = function (n) {
  9982. var ts = this._transformState;
  9983. if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
  9984. ts.transforming = true;
  9985. this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
  9986. } else {
  9987. // mark that we need a transform, so that any data that comes in
  9988. // will get processed, now that we've asked for it.
  9989. ts.needTransform = true;
  9990. }
  9991. };
  9992. Transform.prototype._destroy = function (err, cb) {
  9993. var _this2 = this;
  9994. Duplex.prototype._destroy.call(this, err, function (err2) {
  9995. cb(err2);
  9996. _this2.emit('close');
  9997. });
  9998. };
  9999. function done(stream, er, data) {
  10000. if (er) return stream.emit('error', er);
  10001. if (data != null) // single equals check for both `null` and `undefined`
  10002. stream.push(data);
  10003. // if there's nothing in the write buffer, then that means
  10004. // that nothing more will ever be provided
  10005. if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
  10006. if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
  10007. return stream.push(null);
  10008. }
  10009. },{"./_stream_duplex":53,"core-util-is":10,"inherits":29}],57:[function(require,module,exports){
  10010. (function (process,global,setImmediate){
  10011. // Copyright Joyent, Inc. and other Node contributors.
  10012. //
  10013. // Permission is hereby granted, free of charge, to any person obtaining a
  10014. // copy of this software and associated documentation files (the
  10015. // "Software"), to deal in the Software without restriction, including
  10016. // without limitation the rights to use, copy, modify, merge, publish,
  10017. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10018. // persons to whom the Software is furnished to do so, subject to the
  10019. // following conditions:
  10020. //
  10021. // The above copyright notice and this permission notice shall be included
  10022. // in all copies or substantial portions of the Software.
  10023. //
  10024. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10025. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10026. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10027. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10028. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10029. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10030. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10031. // A bit simpler than readable streams.
  10032. // Implement an async ._write(chunk, encoding, cb), and it'll handle all
  10033. // the drain event emission and buffering.
  10034. 'use strict';
  10035. /*<replacement>*/
  10036. var pna = require('process-nextick-args');
  10037. /*</replacement>*/
  10038. module.exports = Writable;
  10039. /* <replacement> */
  10040. function WriteReq(chunk, encoding, cb) {
  10041. this.chunk = chunk;
  10042. this.encoding = encoding;
  10043. this.callback = cb;
  10044. this.next = null;
  10045. }
  10046. // It seems a linked list but it is not
  10047. // there will be only 2 of these for each stream
  10048. function CorkedRequest(state) {
  10049. var _this = this;
  10050. this.next = null;
  10051. this.entry = null;
  10052. this.finish = function () {
  10053. onCorkedFinish(_this, state);
  10054. };
  10055. }
  10056. /* </replacement> */
  10057. /*<replacement>*/
  10058. var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
  10059. /*</replacement>*/
  10060. /*<replacement>*/
  10061. var Duplex;
  10062. /*</replacement>*/
  10063. Writable.WritableState = WritableState;
  10064. /*<replacement>*/
  10065. var util = Object.create(require('core-util-is'));
  10066. util.inherits = require('inherits');
  10067. /*</replacement>*/
  10068. /*<replacement>*/
  10069. var internalUtil = {
  10070. deprecate: require('util-deprecate')
  10071. };
  10072. /*</replacement>*/
  10073. /*<replacement>*/
  10074. var Stream = require('./internal/streams/stream');
  10075. /*</replacement>*/
  10076. /*<replacement>*/
  10077. var Buffer = require('safe-buffer').Buffer;
  10078. var OurUint8Array = global.Uint8Array || function () {};
  10079. function _uint8ArrayToBuffer(chunk) {
  10080. return Buffer.from(chunk);
  10081. }
  10082. function _isUint8Array(obj) {
  10083. return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
  10084. }
  10085. /*</replacement>*/
  10086. var destroyImpl = require('./internal/streams/destroy');
  10087. util.inherits(Writable, Stream);
  10088. function nop() {}
  10089. function WritableState(options, stream) {
  10090. Duplex = Duplex || require('./_stream_duplex');
  10091. options = options || {};
  10092. // Duplex streams are both readable and writable, but share
  10093. // the same options object.
  10094. // However, some cases require setting options to different
  10095. // values for the readable and the writable sides of the duplex stream.
  10096. // These options can be provided separately as readableXXX and writableXXX.
  10097. var isDuplex = stream instanceof Duplex;
  10098. // object stream flag to indicate whether or not this stream
  10099. // contains buffers or objects.
  10100. this.objectMode = !!options.objectMode;
  10101. if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
  10102. // the point at which write() starts returning false
  10103. // Note: 0 is a valid value, means that we always return false if
  10104. // the entire buffer is not flushed immediately on write()
  10105. var hwm = options.highWaterMark;
  10106. var writableHwm = options.writableHighWaterMark;
  10107. var defaultHwm = this.objectMode ? 16 : 16 * 1024;
  10108. if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
  10109. // cast to ints.
  10110. this.highWaterMark = Math.floor(this.highWaterMark);
  10111. // if _final has been called
  10112. this.finalCalled = false;
  10113. // drain event flag.
  10114. this.needDrain = false;
  10115. // at the start of calling end()
  10116. this.ending = false;
  10117. // when end() has been called, and returned
  10118. this.ended = false;
  10119. // when 'finish' is emitted
  10120. this.finished = false;
  10121. // has it been destroyed
  10122. this.destroyed = false;
  10123. // should we decode strings into buffers before passing to _write?
  10124. // this is here so that some node-core streams can optimize string
  10125. // handling at a lower level.
  10126. var noDecode = options.decodeStrings === false;
  10127. this.decodeStrings = !noDecode;
  10128. // Crypto is kind of old and crusty. Historically, its default string
  10129. // encoding is 'binary' so we have to make this configurable.
  10130. // Everything else in the universe uses 'utf8', though.
  10131. this.defaultEncoding = options.defaultEncoding || 'utf8';
  10132. // not an actual buffer we keep track of, but a measurement
  10133. // of how much we're waiting to get pushed to some underlying
  10134. // socket or file.
  10135. this.length = 0;
  10136. // a flag to see when we're in the middle of a write.
  10137. this.writing = false;
  10138. // when true all writes will be buffered until .uncork() call
  10139. this.corked = 0;
  10140. // a flag to be able to tell if the onwrite cb is called immediately,
  10141. // or on a later tick. We set this to true at first, because any
  10142. // actions that shouldn't happen until "later" should generally also
  10143. // not happen before the first write call.
  10144. this.sync = true;
  10145. // a flag to know if we're processing previously buffered items, which
  10146. // may call the _write() callback in the same tick, so that we don't
  10147. // end up in an overlapped onwrite situation.
  10148. this.bufferProcessing = false;
  10149. // the callback that's passed to _write(chunk,cb)
  10150. this.onwrite = function (er) {
  10151. onwrite(stream, er);
  10152. };
  10153. // the callback that the user supplies to write(chunk,encoding,cb)
  10154. this.writecb = null;
  10155. // the amount that is being written when _write is called.
  10156. this.writelen = 0;
  10157. this.bufferedRequest = null;
  10158. this.lastBufferedRequest = null;
  10159. // number of pending user-supplied write callbacks
  10160. // this must be 0 before 'finish' can be emitted
  10161. this.pendingcb = 0;
  10162. // emit prefinish if the only thing we're waiting for is _write cbs
  10163. // This is relevant for synchronous Transform streams
  10164. this.prefinished = false;
  10165. // True if the error was already emitted and should not be thrown again
  10166. this.errorEmitted = false;
  10167. // count buffered requests
  10168. this.bufferedRequestCount = 0;
  10169. // allocate the first CorkedRequest, there is always
  10170. // one allocated and free to use, and we maintain at most two
  10171. this.corkedRequestsFree = new CorkedRequest(this);
  10172. }
  10173. WritableState.prototype.getBuffer = function getBuffer() {
  10174. var current = this.bufferedRequest;
  10175. var out = [];
  10176. while (current) {
  10177. out.push(current);
  10178. current = current.next;
  10179. }
  10180. return out;
  10181. };
  10182. (function () {
  10183. try {
  10184. Object.defineProperty(WritableState.prototype, 'buffer', {
  10185. get: internalUtil.deprecate(function () {
  10186. return this.getBuffer();
  10187. }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
  10188. });
  10189. } catch (_) {}
  10190. })();
  10191. // Test _writableState for inheritance to account for Duplex streams,
  10192. // whose prototype chain only points to Readable.
  10193. var realHasInstance;
  10194. if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
  10195. realHasInstance = Function.prototype[Symbol.hasInstance];
  10196. Object.defineProperty(Writable, Symbol.hasInstance, {
  10197. value: function (object) {
  10198. if (realHasInstance.call(this, object)) return true;
  10199. if (this !== Writable) return false;
  10200. return object && object._writableState instanceof WritableState;
  10201. }
  10202. });
  10203. } else {
  10204. realHasInstance = function (object) {
  10205. return object instanceof this;
  10206. };
  10207. }
  10208. function Writable(options) {
  10209. Duplex = Duplex || require('./_stream_duplex');
  10210. // Writable ctor is applied to Duplexes, too.
  10211. // `realHasInstance` is necessary because using plain `instanceof`
  10212. // would return false, as no `_writableState` property is attached.
  10213. // Trying to use the custom `instanceof` for Writable here will also break the
  10214. // Node.js LazyTransform implementation, which has a non-trivial getter for
  10215. // `_writableState` that would lead to infinite recursion.
  10216. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
  10217. return new Writable(options);
  10218. }
  10219. this._writableState = new WritableState(options, this);
  10220. // legacy.
  10221. this.writable = true;
  10222. if (options) {
  10223. if (typeof options.write === 'function') this._write = options.write;
  10224. if (typeof options.writev === 'function') this._writev = options.writev;
  10225. if (typeof options.destroy === 'function') this._destroy = options.destroy;
  10226. if (typeof options.final === 'function') this._final = options.final;
  10227. }
  10228. Stream.call(this);
  10229. }
  10230. // Otherwise people can pipe Writable streams, which is just wrong.
  10231. Writable.prototype.pipe = function () {
  10232. this.emit('error', new Error('Cannot pipe, not readable'));
  10233. };
  10234. function writeAfterEnd(stream, cb) {
  10235. var er = new Error('write after end');
  10236. // TODO: defer error events consistently everywhere, not just the cb
  10237. stream.emit('error', er);
  10238. pna.nextTick(cb, er);
  10239. }
  10240. // Checks that a user-supplied chunk is valid, especially for the particular
  10241. // mode the stream is in. Currently this means that `null` is never accepted
  10242. // and undefined/non-string values are only allowed in object mode.
  10243. function validChunk(stream, state, chunk, cb) {
  10244. var valid = true;
  10245. var er = false;
  10246. if (chunk === null) {
  10247. er = new TypeError('May not write null values to stream');
  10248. } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
  10249. er = new TypeError('Invalid non-string/buffer chunk');
  10250. }
  10251. if (er) {
  10252. stream.emit('error', er);
  10253. pna.nextTick(cb, er);
  10254. valid = false;
  10255. }
  10256. return valid;
  10257. }
  10258. Writable.prototype.write = function (chunk, encoding, cb) {
  10259. var state = this._writableState;
  10260. var ret = false;
  10261. var isBuf = !state.objectMode && _isUint8Array(chunk);
  10262. if (isBuf && !Buffer.isBuffer(chunk)) {
  10263. chunk = _uint8ArrayToBuffer(chunk);
  10264. }
  10265. if (typeof encoding === 'function') {
  10266. cb = encoding;
  10267. encoding = null;
  10268. }
  10269. if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
  10270. if (typeof cb !== 'function') cb = nop;
  10271. if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
  10272. state.pendingcb++;
  10273. ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
  10274. }
  10275. return ret;
  10276. };
  10277. Writable.prototype.cork = function () {
  10278. var state = this._writableState;
  10279. state.corked++;
  10280. };
  10281. Writable.prototype.uncork = function () {
  10282. var state = this._writableState;
  10283. if (state.corked) {
  10284. state.corked--;
  10285. if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
  10286. }
  10287. };
  10288. Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
  10289. // node::ParseEncoding() requires lower case.
  10290. if (typeof encoding === 'string') encoding = encoding.toLowerCase();
  10291. if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding);
  10292. this._writableState.defaultEncoding = encoding;
  10293. return this;
  10294. };
  10295. function decodeChunk(state, chunk, encoding) {
  10296. if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
  10297. chunk = Buffer.from(chunk, encoding);
  10298. }
  10299. return chunk;
  10300. }
  10301. Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
  10302. // making it explicit this property is not enumerable
  10303. // because otherwise some prototype manipulation in
  10304. // userland will fail
  10305. enumerable: false,
  10306. get: function () {
  10307. return this._writableState.highWaterMark;
  10308. }
  10309. });
  10310. // if we're already writing something, then just put this
  10311. // in the queue, and wait our turn. Otherwise, call _write
  10312. // If we return false, then we need a drain event, so set that flag.
  10313. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
  10314. if (!isBuf) {
  10315. var newChunk = decodeChunk(state, chunk, encoding);
  10316. if (chunk !== newChunk) {
  10317. isBuf = true;
  10318. encoding = 'buffer';
  10319. chunk = newChunk;
  10320. }
  10321. }
  10322. var len = state.objectMode ? 1 : chunk.length;
  10323. state.length += len;
  10324. var ret = state.length < state.highWaterMark;
  10325. // we must ensure that previous needDrain will not be reset to false.
  10326. if (!ret) state.needDrain = true;
  10327. if (state.writing || state.corked) {
  10328. var last = state.lastBufferedRequest;
  10329. state.lastBufferedRequest = {
  10330. chunk: chunk,
  10331. encoding: encoding,
  10332. isBuf: isBuf,
  10333. callback: cb,
  10334. next: null
  10335. };
  10336. if (last) {
  10337. last.next = state.lastBufferedRequest;
  10338. } else {
  10339. state.bufferedRequest = state.lastBufferedRequest;
  10340. }
  10341. state.bufferedRequestCount += 1;
  10342. } else {
  10343. doWrite(stream, state, false, len, chunk, encoding, cb);
  10344. }
  10345. return ret;
  10346. }
  10347. function doWrite(stream, state, writev, len, chunk, encoding, cb) {
  10348. state.writelen = len;
  10349. state.writecb = cb;
  10350. state.writing = true;
  10351. state.sync = true;
  10352. if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
  10353. state.sync = false;
  10354. }
  10355. function onwriteError(stream, state, sync, er, cb) {
  10356. --state.pendingcb;
  10357. if (sync) {
  10358. // defer the callback if we are being called synchronously
  10359. // to avoid piling up things on the stack
  10360. pna.nextTick(cb, er);
  10361. // this can emit finish, and it will always happen
  10362. // after error
  10363. pna.nextTick(finishMaybe, stream, state);
  10364. stream._writableState.errorEmitted = true;
  10365. stream.emit('error', er);
  10366. } else {
  10367. // the caller expect this to happen before if
  10368. // it is async
  10369. cb(er);
  10370. stream._writableState.errorEmitted = true;
  10371. stream.emit('error', er);
  10372. // this can emit finish, but finish must
  10373. // always follow error
  10374. finishMaybe(stream, state);
  10375. }
  10376. }
  10377. function onwriteStateUpdate(state) {
  10378. state.writing = false;
  10379. state.writecb = null;
  10380. state.length -= state.writelen;
  10381. state.writelen = 0;
  10382. }
  10383. function onwrite(stream, er) {
  10384. var state = stream._writableState;
  10385. var sync = state.sync;
  10386. var cb = state.writecb;
  10387. onwriteStateUpdate(state);
  10388. if (er) onwriteError(stream, state, sync, er, cb);else {
  10389. // Check if we're actually ready to finish, but don't emit yet
  10390. var finished = needFinish(state);
  10391. if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
  10392. clearBuffer(stream, state);
  10393. }
  10394. if (sync) {
  10395. /*<replacement>*/
  10396. asyncWrite(afterWrite, stream, state, finished, cb);
  10397. /*</replacement>*/
  10398. } else {
  10399. afterWrite(stream, state, finished, cb);
  10400. }
  10401. }
  10402. }
  10403. function afterWrite(stream, state, finished, cb) {
  10404. if (!finished) onwriteDrain(stream, state);
  10405. state.pendingcb--;
  10406. cb();
  10407. finishMaybe(stream, state);
  10408. }
  10409. // Must force callback to be called on nextTick, so that we don't
  10410. // emit 'drain' before the write() consumer gets the 'false' return
  10411. // value, and has a chance to attach a 'drain' listener.
  10412. function onwriteDrain(stream, state) {
  10413. if (state.length === 0 && state.needDrain) {
  10414. state.needDrain = false;
  10415. stream.emit('drain');
  10416. }
  10417. }
  10418. // if there's something in the buffer waiting, then process it
  10419. function clearBuffer(stream, state) {
  10420. state.bufferProcessing = true;
  10421. var entry = state.bufferedRequest;
  10422. if (stream._writev && entry && entry.next) {
  10423. // Fast case, write everything using _writev()
  10424. var l = state.bufferedRequestCount;
  10425. var buffer = new Array(l);
  10426. var holder = state.corkedRequestsFree;
  10427. holder.entry = entry;
  10428. var count = 0;
  10429. var allBuffers = true;
  10430. while (entry) {
  10431. buffer[count] = entry;
  10432. if (!entry.isBuf) allBuffers = false;
  10433. entry = entry.next;
  10434. count += 1;
  10435. }
  10436. buffer.allBuffers = allBuffers;
  10437. doWrite(stream, state, true, state.length, buffer, '', holder.finish);
  10438. // doWrite is almost always async, defer these to save a bit of time
  10439. // as the hot path ends with doWrite
  10440. state.pendingcb++;
  10441. state.lastBufferedRequest = null;
  10442. if (holder.next) {
  10443. state.corkedRequestsFree = holder.next;
  10444. holder.next = null;
  10445. } else {
  10446. state.corkedRequestsFree = new CorkedRequest(state);
  10447. }
  10448. state.bufferedRequestCount = 0;
  10449. } else {
  10450. // Slow case, write chunks one-by-one
  10451. while (entry) {
  10452. var chunk = entry.chunk;
  10453. var encoding = entry.encoding;
  10454. var cb = entry.callback;
  10455. var len = state.objectMode ? 1 : chunk.length;
  10456. doWrite(stream, state, false, len, chunk, encoding, cb);
  10457. entry = entry.next;
  10458. state.bufferedRequestCount--;
  10459. // if we didn't call the onwrite immediately, then
  10460. // it means that we need to wait until it does.
  10461. // also, that means that the chunk and cb are currently
  10462. // being processed, so move the buffer counter past them.
  10463. if (state.writing) {
  10464. break;
  10465. }
  10466. }
  10467. if (entry === null) state.lastBufferedRequest = null;
  10468. }
  10469. state.bufferedRequest = entry;
  10470. state.bufferProcessing = false;
  10471. }
  10472. Writable.prototype._write = function (chunk, encoding, cb) {
  10473. cb(new Error('_write() is not implemented'));
  10474. };
  10475. Writable.prototype._writev = null;
  10476. Writable.prototype.end = function (chunk, encoding, cb) {
  10477. var state = this._writableState;
  10478. if (typeof chunk === 'function') {
  10479. cb = chunk;
  10480. chunk = null;
  10481. encoding = null;
  10482. } else if (typeof encoding === 'function') {
  10483. cb = encoding;
  10484. encoding = null;
  10485. }
  10486. if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
  10487. // .end() fully uncorks
  10488. if (state.corked) {
  10489. state.corked = 1;
  10490. this.uncork();
  10491. }
  10492. // ignore unnecessary end() calls.
  10493. if (!state.ending && !state.finished) endWritable(this, state, cb);
  10494. };
  10495. function needFinish(state) {
  10496. return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
  10497. }
  10498. function callFinal(stream, state) {
  10499. stream._final(function (err) {
  10500. state.pendingcb--;
  10501. if (err) {
  10502. stream.emit('error', err);
  10503. }
  10504. state.prefinished = true;
  10505. stream.emit('prefinish');
  10506. finishMaybe(stream, state);
  10507. });
  10508. }
  10509. function prefinish(stream, state) {
  10510. if (!state.prefinished && !state.finalCalled) {
  10511. if (typeof stream._final === 'function') {
  10512. state.pendingcb++;
  10513. state.finalCalled = true;
  10514. pna.nextTick(callFinal, stream, state);
  10515. } else {
  10516. state.prefinished = true;
  10517. stream.emit('prefinish');
  10518. }
  10519. }
  10520. }
  10521. function finishMaybe(stream, state) {
  10522. var need = needFinish(state);
  10523. if (need) {
  10524. prefinish(stream, state);
  10525. if (state.pendingcb === 0) {
  10526. state.finished = true;
  10527. stream.emit('finish');
  10528. }
  10529. }
  10530. return need;
  10531. }
  10532. function endWritable(stream, state, cb) {
  10533. state.ending = true;
  10534. finishMaybe(stream, state);
  10535. if (cb) {
  10536. if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
  10537. }
  10538. state.ended = true;
  10539. stream.writable = false;
  10540. }
  10541. function onCorkedFinish(corkReq, state, err) {
  10542. var entry = corkReq.entry;
  10543. corkReq.entry = null;
  10544. while (entry) {
  10545. var cb = entry.callback;
  10546. state.pendingcb--;
  10547. cb(err);
  10548. entry = entry.next;
  10549. }
  10550. if (state.corkedRequestsFree) {
  10551. state.corkedRequestsFree.next = corkReq;
  10552. } else {
  10553. state.corkedRequestsFree = corkReq;
  10554. }
  10555. }
  10556. Object.defineProperty(Writable.prototype, 'destroyed', {
  10557. get: function () {
  10558. if (this._writableState === undefined) {
  10559. return false;
  10560. }
  10561. return this._writableState.destroyed;
  10562. },
  10563. set: function (value) {
  10564. // we ignore the value if the stream
  10565. // has not been initialized yet
  10566. if (!this._writableState) {
  10567. return;
  10568. }
  10569. // backward compatibility, the user is explicitly
  10570. // managing destroyed
  10571. this._writableState.destroyed = value;
  10572. }
  10573. });
  10574. Writable.prototype.destroy = destroyImpl.destroy;
  10575. Writable.prototype._undestroy = destroyImpl.undestroy;
  10576. Writable.prototype._destroy = function (err, cb) {
  10577. this.end();
  10578. cb(err);
  10579. };
  10580. }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
  10581. },{"./_stream_duplex":53,"./internal/streams/destroy":59,"./internal/streams/stream":60,"_process":9,"core-util-is":10,"inherits":29,"process-nextick-args":39,"safe-buffer":40,"timers":66,"util-deprecate":68}],58:[function(require,module,exports){
  10582. 'use strict';
  10583. function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
  10584. var Buffer = require('safe-buffer').Buffer;
  10585. var util = require('util');
  10586. function copyBuffer(src, target, offset) {
  10587. src.copy(target, offset);
  10588. }
  10589. module.exports = function () {
  10590. function BufferList() {
  10591. _classCallCheck(this, BufferList);
  10592. this.head = null;
  10593. this.tail = null;
  10594. this.length = 0;
  10595. }
  10596. BufferList.prototype.push = function push(v) {
  10597. var entry = { data: v, next: null };
  10598. if (this.length > 0) this.tail.next = entry;else this.head = entry;
  10599. this.tail = entry;
  10600. ++this.length;
  10601. };
  10602. BufferList.prototype.unshift = function unshift(v) {
  10603. var entry = { data: v, next: this.head };
  10604. if (this.length === 0) this.tail = entry;
  10605. this.head = entry;
  10606. ++this.length;
  10607. };
  10608. BufferList.prototype.shift = function shift() {
  10609. if (this.length === 0) return;
  10610. var ret = this.head.data;
  10611. if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
  10612. --this.length;
  10613. return ret;
  10614. };
  10615. BufferList.prototype.clear = function clear() {
  10616. this.head = this.tail = null;
  10617. this.length = 0;
  10618. };
  10619. BufferList.prototype.join = function join(s) {
  10620. if (this.length === 0) return '';
  10621. var p = this.head;
  10622. var ret = '' + p.data;
  10623. while (p = p.next) {
  10624. ret += s + p.data;
  10625. }return ret;
  10626. };
  10627. BufferList.prototype.concat = function concat(n) {
  10628. if (this.length === 0) return Buffer.alloc(0);
  10629. if (this.length === 1) return this.head.data;
  10630. var ret = Buffer.allocUnsafe(n >>> 0);
  10631. var p = this.head;
  10632. var i = 0;
  10633. while (p) {
  10634. copyBuffer(p.data, ret, i);
  10635. i += p.data.length;
  10636. p = p.next;
  10637. }
  10638. return ret;
  10639. };
  10640. return BufferList;
  10641. }();
  10642. if (util && util.inspect && util.inspect.custom) {
  10643. module.exports.prototype[util.inspect.custom] = function () {
  10644. var obj = util.inspect({ length: this.length });
  10645. return this.constructor.name + ' ' + obj;
  10646. };
  10647. }
  10648. },{"safe-buffer":40,"util":7}],59:[function(require,module,exports){
  10649. 'use strict';
  10650. /*<replacement>*/
  10651. var pna = require('process-nextick-args');
  10652. /*</replacement>*/
  10653. // undocumented cb() API, needed for core, not for public API
  10654. function destroy(err, cb) {
  10655. var _this = this;
  10656. var readableDestroyed = this._readableState && this._readableState.destroyed;
  10657. var writableDestroyed = this._writableState && this._writableState.destroyed;
  10658. if (readableDestroyed || writableDestroyed) {
  10659. if (cb) {
  10660. cb(err);
  10661. } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
  10662. pna.nextTick(emitErrorNT, this, err);
  10663. }
  10664. return this;
  10665. }
  10666. // we set destroyed to true before firing error callbacks in order
  10667. // to make it re-entrance safe in case destroy() is called within callbacks
  10668. if (this._readableState) {
  10669. this._readableState.destroyed = true;
  10670. }
  10671. // if this is a duplex stream mark the writable part as destroyed as well
  10672. if (this._writableState) {
  10673. this._writableState.destroyed = true;
  10674. }
  10675. this._destroy(err || null, function (err) {
  10676. if (!cb && err) {
  10677. pna.nextTick(emitErrorNT, _this, err);
  10678. if (_this._writableState) {
  10679. _this._writableState.errorEmitted = true;
  10680. }
  10681. } else if (cb) {
  10682. cb(err);
  10683. }
  10684. });
  10685. return this;
  10686. }
  10687. function undestroy() {
  10688. if (this._readableState) {
  10689. this._readableState.destroyed = false;
  10690. this._readableState.reading = false;
  10691. this._readableState.ended = false;
  10692. this._readableState.endEmitted = false;
  10693. }
  10694. if (this._writableState) {
  10695. this._writableState.destroyed = false;
  10696. this._writableState.ended = false;
  10697. this._writableState.ending = false;
  10698. this._writableState.finished = false;
  10699. this._writableState.errorEmitted = false;
  10700. }
  10701. }
  10702. function emitErrorNT(self, err) {
  10703. self.emit('error', err);
  10704. }
  10705. module.exports = {
  10706. destroy: destroy,
  10707. undestroy: undestroy
  10708. };
  10709. },{"process-nextick-args":39}],60:[function(require,module,exports){
  10710. module.exports = require('events').EventEmitter;
  10711. },{"events":11}],61:[function(require,module,exports){
  10712. module.exports = require('./readable').PassThrough
  10713. },{"./readable":62}],62:[function(require,module,exports){
  10714. exports = module.exports = require('./lib/_stream_readable.js');
  10715. exports.Stream = exports;
  10716. exports.Readable = exports;
  10717. exports.Writable = require('./lib/_stream_writable.js');
  10718. exports.Duplex = require('./lib/_stream_duplex.js');
  10719. exports.Transform = require('./lib/_stream_transform.js');
  10720. exports.PassThrough = require('./lib/_stream_passthrough.js');
  10721. },{"./lib/_stream_duplex.js":53,"./lib/_stream_passthrough.js":54,"./lib/_stream_readable.js":55,"./lib/_stream_transform.js":56,"./lib/_stream_writable.js":57}],63:[function(require,module,exports){
  10722. module.exports = require('./readable').Transform
  10723. },{"./readable":62}],64:[function(require,module,exports){
  10724. module.exports = require('./lib/_stream_writable.js');
  10725. },{"./lib/_stream_writable.js":57}],65:[function(require,module,exports){
  10726. // Copyright Joyent, Inc. and other Node contributors.
  10727. //
  10728. // Permission is hereby granted, free of charge, to any person obtaining a
  10729. // copy of this software and associated documentation files (the
  10730. // "Software"), to deal in the Software without restriction, including
  10731. // without limitation the rights to use, copy, modify, merge, publish,
  10732. // distribute, sublicense, and/or sell copies of the Software, and to permit
  10733. // persons to whom the Software is furnished to do so, subject to the
  10734. // following conditions:
  10735. //
  10736. // The above copyright notice and this permission notice shall be included
  10737. // in all copies or substantial portions of the Software.
  10738. //
  10739. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  10740. // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  10741. // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  10742. // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  10743. // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  10744. // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  10745. // USE OR OTHER DEALINGS IN THE SOFTWARE.
  10746. 'use strict';
  10747. /*<replacement>*/
  10748. var Buffer = require('safe-buffer').Buffer;
  10749. /*</replacement>*/
  10750. var isEncoding = Buffer.isEncoding || function (encoding) {
  10751. encoding = '' + encoding;
  10752. switch (encoding && encoding.toLowerCase()) {
  10753. case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
  10754. return true;
  10755. default:
  10756. return false;
  10757. }
  10758. };
  10759. function _normalizeEncoding(enc) {
  10760. if (!enc) return 'utf8';
  10761. var retried;
  10762. while (true) {
  10763. switch (enc) {
  10764. case 'utf8':
  10765. case 'utf-8':
  10766. return 'utf8';
  10767. case 'ucs2':
  10768. case 'ucs-2':
  10769. case 'utf16le':
  10770. case 'utf-16le':
  10771. return 'utf16le';
  10772. case 'latin1':
  10773. case 'binary':
  10774. return 'latin1';
  10775. case 'base64':
  10776. case 'ascii':
  10777. case 'hex':
  10778. return enc;
  10779. default:
  10780. if (retried) return; // undefined
  10781. enc = ('' + enc).toLowerCase();
  10782. retried = true;
  10783. }
  10784. }
  10785. };
  10786. // Do not cache `Buffer.isEncoding` when checking encoding names as some
  10787. // modules monkey-patch it to support additional encodings
  10788. function normalizeEncoding(enc) {
  10789. var nenc = _normalizeEncoding(enc);
  10790. if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
  10791. return nenc || enc;
  10792. }
  10793. // StringDecoder provides an interface for efficiently splitting a series of
  10794. // buffers into a series of JS strings without breaking apart multi-byte
  10795. // characters.
  10796. exports.StringDecoder = StringDecoder;
  10797. function StringDecoder(encoding) {
  10798. this.encoding = normalizeEncoding(encoding);
  10799. var nb;
  10800. switch (this.encoding) {
  10801. case 'utf16le':
  10802. this.text = utf16Text;
  10803. this.end = utf16End;
  10804. nb = 4;
  10805. break;
  10806. case 'utf8':
  10807. this.fillLast = utf8FillLast;
  10808. nb = 4;
  10809. break;
  10810. case 'base64':
  10811. this.text = base64Text;
  10812. this.end = base64End;
  10813. nb = 3;
  10814. break;
  10815. default:
  10816. this.write = simpleWrite;
  10817. this.end = simpleEnd;
  10818. return;
  10819. }
  10820. this.lastNeed = 0;
  10821. this.lastTotal = 0;
  10822. this.lastChar = Buffer.allocUnsafe(nb);
  10823. }
  10824. StringDecoder.prototype.write = function (buf) {
  10825. if (buf.length === 0) return '';
  10826. var r;
  10827. var i;
  10828. if (this.lastNeed) {
  10829. r = this.fillLast(buf);
  10830. if (r === undefined) return '';
  10831. i = this.lastNeed;
  10832. this.lastNeed = 0;
  10833. } else {
  10834. i = 0;
  10835. }
  10836. if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
  10837. return r || '';
  10838. };
  10839. StringDecoder.prototype.end = utf8End;
  10840. // Returns only complete characters in a Buffer
  10841. StringDecoder.prototype.text = utf8Text;
  10842. // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
  10843. StringDecoder.prototype.fillLast = function (buf) {
  10844. if (this.lastNeed <= buf.length) {
  10845. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
  10846. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10847. }
  10848. buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
  10849. this.lastNeed -= buf.length;
  10850. };
  10851. // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
  10852. // continuation byte. If an invalid byte is detected, -2 is returned.
  10853. function utf8CheckByte(byte) {
  10854. if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
  10855. return byte >> 6 === 0x02 ? -1 : -2;
  10856. }
  10857. // Checks at most 3 bytes at the end of a Buffer in order to detect an
  10858. // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
  10859. // needed to complete the UTF-8 character (if applicable) are returned.
  10860. function utf8CheckIncomplete(self, buf, i) {
  10861. var j = buf.length - 1;
  10862. if (j < i) return 0;
  10863. var nb = utf8CheckByte(buf[j]);
  10864. if (nb >= 0) {
  10865. if (nb > 0) self.lastNeed = nb - 1;
  10866. return nb;
  10867. }
  10868. if (--j < i || nb === -2) return 0;
  10869. nb = utf8CheckByte(buf[j]);
  10870. if (nb >= 0) {
  10871. if (nb > 0) self.lastNeed = nb - 2;
  10872. return nb;
  10873. }
  10874. if (--j < i || nb === -2) return 0;
  10875. nb = utf8CheckByte(buf[j]);
  10876. if (nb >= 0) {
  10877. if (nb > 0) {
  10878. if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
  10879. }
  10880. return nb;
  10881. }
  10882. return 0;
  10883. }
  10884. // Validates as many continuation bytes for a multi-byte UTF-8 character as
  10885. // needed or are available. If we see a non-continuation byte where we expect
  10886. // one, we "replace" the validated continuation bytes we've seen so far with
  10887. // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
  10888. // behavior. The continuation byte check is included three times in the case
  10889. // where all of the continuation bytes for a character exist in the same buffer.
  10890. // It is also done this way as a slight performance increase instead of using a
  10891. // loop.
  10892. function utf8CheckExtraBytes(self, buf, p) {
  10893. if ((buf[0] & 0xC0) !== 0x80) {
  10894. self.lastNeed = 0;
  10895. return '\ufffd';
  10896. }
  10897. if (self.lastNeed > 1 && buf.length > 1) {
  10898. if ((buf[1] & 0xC0) !== 0x80) {
  10899. self.lastNeed = 1;
  10900. return '\ufffd';
  10901. }
  10902. if (self.lastNeed > 2 && buf.length > 2) {
  10903. if ((buf[2] & 0xC0) !== 0x80) {
  10904. self.lastNeed = 2;
  10905. return '\ufffd';
  10906. }
  10907. }
  10908. }
  10909. }
  10910. // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
  10911. function utf8FillLast(buf) {
  10912. var p = this.lastTotal - this.lastNeed;
  10913. var r = utf8CheckExtraBytes(this, buf, p);
  10914. if (r !== undefined) return r;
  10915. if (this.lastNeed <= buf.length) {
  10916. buf.copy(this.lastChar, p, 0, this.lastNeed);
  10917. return this.lastChar.toString(this.encoding, 0, this.lastTotal);
  10918. }
  10919. buf.copy(this.lastChar, p, 0, buf.length);
  10920. this.lastNeed -= buf.length;
  10921. }
  10922. // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
  10923. // partial character, the character's bytes are buffered until the required
  10924. // number of bytes are available.
  10925. function utf8Text(buf, i) {
  10926. var total = utf8CheckIncomplete(this, buf, i);
  10927. if (!this.lastNeed) return buf.toString('utf8', i);
  10928. this.lastTotal = total;
  10929. var end = buf.length - (total - this.lastNeed);
  10930. buf.copy(this.lastChar, 0, end);
  10931. return buf.toString('utf8', i, end);
  10932. }
  10933. // For UTF-8, a replacement character is added when ending on a partial
  10934. // character.
  10935. function utf8End(buf) {
  10936. var r = buf && buf.length ? this.write(buf) : '';
  10937. if (this.lastNeed) return r + '\ufffd';
  10938. return r;
  10939. }
  10940. // UTF-16LE typically needs two bytes per character, but even if we have an even
  10941. // number of bytes available, we need to check if we end on a leading/high
  10942. // surrogate. In that case, we need to wait for the next two bytes in order to
  10943. // decode the last character properly.
  10944. function utf16Text(buf, i) {
  10945. if ((buf.length - i) % 2 === 0) {
  10946. var r = buf.toString('utf16le', i);
  10947. if (r) {
  10948. var c = r.charCodeAt(r.length - 1);
  10949. if (c >= 0xD800 && c <= 0xDBFF) {
  10950. this.lastNeed = 2;
  10951. this.lastTotal = 4;
  10952. this.lastChar[0] = buf[buf.length - 2];
  10953. this.lastChar[1] = buf[buf.length - 1];
  10954. return r.slice(0, -1);
  10955. }
  10956. }
  10957. return r;
  10958. }
  10959. this.lastNeed = 1;
  10960. this.lastTotal = 2;
  10961. this.lastChar[0] = buf[buf.length - 1];
  10962. return buf.toString('utf16le', i, buf.length - 1);
  10963. }
  10964. // For UTF-16LE we do not explicitly append special replacement characters if we
  10965. // end on a partial character, we simply let v8 handle that.
  10966. function utf16End(buf) {
  10967. var r = buf && buf.length ? this.write(buf) : '';
  10968. if (this.lastNeed) {
  10969. var end = this.lastTotal - this.lastNeed;
  10970. return r + this.lastChar.toString('utf16le', 0, end);
  10971. }
  10972. return r;
  10973. }
  10974. function base64Text(buf, i) {
  10975. var n = (buf.length - i) % 3;
  10976. if (n === 0) return buf.toString('base64', i);
  10977. this.lastNeed = 3 - n;
  10978. this.lastTotal = 3;
  10979. if (n === 1) {
  10980. this.lastChar[0] = buf[buf.length - 1];
  10981. } else {
  10982. this.lastChar[0] = buf[buf.length - 2];
  10983. this.lastChar[1] = buf[buf.length - 1];
  10984. }
  10985. return buf.toString('base64', i, buf.length - n);
  10986. }
  10987. function base64End(buf) {
  10988. var r = buf && buf.length ? this.write(buf) : '';
  10989. if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
  10990. return r;
  10991. }
  10992. // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
  10993. function simpleWrite(buf) {
  10994. return buf.toString(this.encoding);
  10995. }
  10996. function simpleEnd(buf) {
  10997. return buf && buf.length ? this.write(buf) : '';
  10998. }
  10999. },{"safe-buffer":40}],66:[function(require,module,exports){
  11000. (function (setImmediate,clearImmediate){
  11001. var nextTick = require('process/browser.js').nextTick;
  11002. var apply = Function.prototype.apply;
  11003. var slice = Array.prototype.slice;
  11004. var immediateIds = {};
  11005. var nextImmediateId = 0;
  11006. // DOM APIs, for completeness
  11007. exports.setTimeout = function() {
  11008. return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
  11009. };
  11010. exports.setInterval = function() {
  11011. return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
  11012. };
  11013. exports.clearTimeout =
  11014. exports.clearInterval = function(timeout) { timeout.close(); };
  11015. function Timeout(id, clearFn) {
  11016. this._id = id;
  11017. this._clearFn = clearFn;
  11018. }
  11019. Timeout.prototype.unref = Timeout.prototype.ref = function() {};
  11020. Timeout.prototype.close = function() {
  11021. this._clearFn.call(window, this._id);
  11022. };
  11023. // Does not start the time, just sets up the members needed.
  11024. exports.enroll = function(item, msecs) {
  11025. clearTimeout(item._idleTimeoutId);
  11026. item._idleTimeout = msecs;
  11027. };
  11028. exports.unenroll = function(item) {
  11029. clearTimeout(item._idleTimeoutId);
  11030. item._idleTimeout = -1;
  11031. };
  11032. exports._unrefActive = exports.active = function(item) {
  11033. clearTimeout(item._idleTimeoutId);
  11034. var msecs = item._idleTimeout;
  11035. if (msecs >= 0) {
  11036. item._idleTimeoutId = setTimeout(function onTimeout() {
  11037. if (item._onTimeout)
  11038. item._onTimeout();
  11039. }, msecs);
  11040. }
  11041. };
  11042. // That's not how node.js implements it but the exposed api is the same.
  11043. exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
  11044. var id = nextImmediateId++;
  11045. var args = arguments.length < 2 ? false : slice.call(arguments, 1);
  11046. immediateIds[id] = true;
  11047. nextTick(function onNextTick() {
  11048. if (immediateIds[id]) {
  11049. // fn.call() is faster so we optimize for the common use-case
  11050. // @see http://jsperf.com/call-apply-segu
  11051. if (args) {
  11052. fn.apply(null, args);
  11053. } else {
  11054. fn.call(null);
  11055. }
  11056. // Prevent ids from leaking
  11057. exports.clearImmediate(id);
  11058. }
  11059. });
  11060. return id;
  11061. };
  11062. exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
  11063. delete immediateIds[id];
  11064. };
  11065. }).call(this,require("timers").setImmediate,require("timers").clearImmediate)
  11066. },{"process/browser.js":67,"timers":66}],67:[function(require,module,exports){
  11067. arguments[4][9][0].apply(exports,arguments)
  11068. },{"dup":9}],68:[function(require,module,exports){
  11069. (function (global){
  11070. /**
  11071. * Module exports.
  11072. */
  11073. module.exports = deprecate;
  11074. /**
  11075. * Mark that a method should not be used.
  11076. * Returns a modified function which warns once by default.
  11077. *
  11078. * If `localStorage.noDeprecation = true` is set, then it is a no-op.
  11079. *
  11080. * If `localStorage.throwDeprecation = true` is set, then deprecated functions
  11081. * will throw an Error when invoked.
  11082. *
  11083. * If `localStorage.traceDeprecation = true` is set, then deprecated functions
  11084. * will invoke `console.trace()` instead of `console.error()`.
  11085. *
  11086. * @param {Function} fn - the function to deprecate
  11087. * @param {String} msg - the string to print to the console when `fn` is invoked
  11088. * @returns {Function} a new "deprecated" version of `fn`
  11089. * @api public
  11090. */
  11091. function deprecate (fn, msg) {
  11092. if (config('noDeprecation')) {
  11093. return fn;
  11094. }
  11095. var warned = false;
  11096. function deprecated() {
  11097. if (!warned) {
  11098. if (config('throwDeprecation')) {
  11099. throw new Error(msg);
  11100. } else if (config('traceDeprecation')) {
  11101. console.trace(msg);
  11102. } else {
  11103. console.warn(msg);
  11104. }
  11105. warned = true;
  11106. }
  11107. return fn.apply(this, arguments);
  11108. }
  11109. return deprecated;
  11110. }
  11111. /**
  11112. * Checks `localStorage` for boolean values for the given `name`.
  11113. *
  11114. * @param {String} name
  11115. * @returns {Boolean}
  11116. * @api private
  11117. */
  11118. function config (name) {
  11119. // accessing global.localStorage can trigger a DOMException in sandboxed iframes
  11120. try {
  11121. if (!global.localStorage) return false;
  11122. } catch (_) {
  11123. return false;
  11124. }
  11125. var val = global.localStorage[name];
  11126. if (null == val) return false;
  11127. return String(val).toLowerCase() === 'true';
  11128. }
  11129. }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  11130. },{}]},{},[41])(41)
  11131. });