arnaucube
arnaucube/miksi-appPublic Self-hosted repository
miksi-app/libs/snarkjs.js
libs/snarkjs.jsRaw
    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
    5var objectAssign = require('object-assign');
    6
    7// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
    8// original notice:
    9
   10/*!
   11 * The buffer module from node.js, for the browser.
   12 *
   13 * @author   Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
   14 * @license  MIT
   15 */
   16function compare(a, b) {
   17  if (a === b) {
   18    return 0;
   19  }
   20
   21  var x = a.length;
   22  var y = b.length;
   23
   24  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
   25    if (a[i] !== b[i]) {
   26      x = a[i];
   27      y = b[i];
   28      break;
   29    }
   30  }
   31
   32  if (x < y) {
   33    return -1;
   34  }
   35  if (y < x) {
   36    return 1;
   37  }
   38  return 0;
   39}
   40function isBuffer(b) {
   41  if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
   42    return global.Buffer.isBuffer(b);
   43  }
   44  return !!(b != null && b._isBuffer);
   45}
   46
   47// based on node assert, original notice:
   48// NB: The URL to the CommonJS spec is kept just for tradition.
   49//     node-assert has evolved a lot since then, both in API and behavior.
   50
   51// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
   52//
   53// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
   54//
   55// Originally from narwhal.js (http://narwhaljs.org)
   56// Copyright (c) 2009 Thomas Robinson <280north.com>
   57//
   58// Permission is hereby granted, free of charge, to any person obtaining a copy
   59// of this software and associated documentation files (the 'Software'), to
   60// deal in the Software without restriction, including without limitation the
   61// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
   62// sell copies of the Software, and to permit persons to whom the Software is
   63// furnished to do so, subject to the following conditions:
   64//
   65// The above copyright notice and this permission notice shall be included in
   66// all copies or substantial portions of the Software.
   67//
   68// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   69// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   70// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   71// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
   72// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
   73// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
   74
   75var util = require('util/');
   76var hasOwn = Object.prototype.hasOwnProperty;
   77var pSlice = Array.prototype.slice;
   78var functionsHaveNames = (function () {
   79  return function foo() {}.name === 'foo';
   80}());
   81function pToString (obj) {
   82  return Object.prototype.toString.call(obj);
   83}
   84function isView(arrbuf) {
   85  if (isBuffer(arrbuf)) {
   86    return false;
   87  }
   88  if (typeof global.ArrayBuffer !== 'function') {
   89    return false;
   90  }
   91  if (typeof ArrayBuffer.isView === 'function') {
   92    return ArrayBuffer.isView(arrbuf);
   93  }
   94  if (!arrbuf) {
   95    return false;
   96  }
   97  if (arrbuf instanceof DataView) {
   98    return true;
   99  }
  100  if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
  101    return true;
  102  }
  103  return false;
  104}
  105// 1. The assert module provides functions that throw
  106// AssertionError's when particular conditions are not met. The
  107// assert module must conform to the following interface.
  108
  109var assert = module.exports = ok;
  110
  111// 2. The AssertionError is defined in assert.
  112// new assert.AssertionError({ message: message,
  113//                             actual: actual,
  114//                             expected: expected })
  115
  116var regex = /\s*function\s+([^\(\s]*)\s*/;
  117// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
  118function getName(func) {
  119  if (!util.isFunction(func)) {
  120    return;
  121  }
  122  if (functionsHaveNames) {
  123    return func.name;
  124  }
  125  var str = func.toString();
  126  var match = str.match(regex);
  127  return match && match[1];
  128}
  129assert.AssertionError = function AssertionError(options) {
  130  this.name = 'AssertionError';
  131  this.actual = options.actual;
  132  this.expected = options.expected;
  133  this.operator = options.operator;
  134  if (options.message) {
  135    this.message = options.message;
  136    this.generatedMessage = false;
  137  } else {
  138    this.message = getMessage(this);
  139    this.generatedMessage = true;
  140  }
  141  var stackStartFunction = options.stackStartFunction || fail;
  142  if (Error.captureStackTrace) {
  143    Error.captureStackTrace(this, stackStartFunction);
  144  } else {
  145    // non v8 browsers so we can have a stacktrace
  146    var err = new Error();
  147    if (err.stack) {
  148      var out = err.stack;
  149
  150      // try to strip useless frames
  151      var fn_name = getName(stackStartFunction);
  152      var idx = out.indexOf('\n' + fn_name);
  153      if (idx >= 0) {
  154        // once we have located the function frame
  155        // we need to strip out everything before it (and its line)
  156        var next_line = out.indexOf('\n', idx + 1);
  157        out = out.substring(next_line + 1);
  158      }
  159
  160      this.stack = out;
  161    }
  162  }
  163};
  164
  165// assert.AssertionError instanceof Error
  166util.inherits(assert.AssertionError, Error);
  167
  168function truncate(s, n) {
  169  if (typeof s === 'string') {
  170    return s.length < n ? s : s.slice(0, n);
  171  } else {
  172    return s;
  173  }
  174}
  175function inspect(something) {
  176  if (functionsHaveNames || !util.isFunction(something)) {
  177    return util.inspect(something);
  178  }
  179  var rawname = getName(something);
  180  var name = rawname ? ': ' + rawname : '';
  181  return '[Function' +  name + ']';
  182}
  183function getMessage(self) {
  184  return truncate(inspect(self.actual), 128) + ' ' +
  185         self.operator + ' ' +
  186         truncate(inspect(self.expected), 128);
  187}
  188
  189// At present only the three keys mentioned above are used and
  190// understood by the spec. Implementations or sub modules can pass
  191// other keys to the AssertionError's constructor - they will be
  192// ignored.
  193
  194// 3. All of the following functions must throw an AssertionError
  195// when a corresponding condition is not met, with a message that
  196// may be undefined if not provided.  All assertion methods provide
  197// both the actual and expected values to the assertion error for
  198// display purposes.
  199
  200function fail(actual, expected, message, operator, stackStartFunction) {
  201  throw new assert.AssertionError({
  202    message: message,
  203    actual: actual,
  204    expected: expected,
  205    operator: operator,
  206    stackStartFunction: stackStartFunction
  207  });
  208}
  209
  210// EXTENSION! allows for well behaved errors defined elsewhere.
  211assert.fail = fail;
  212
  213// 4. Pure assertion tests whether a value is truthy, as determined
  214// by !!guard.
  215// assert.ok(guard, message_opt);
  216// This statement is equivalent to assert.equal(true, !!guard,
  217// message_opt);. To test strictly for the value true, use
  218// assert.strictEqual(true, guard, message_opt);.
  219
  220function ok(value, message) {
  221  if (!value) fail(value, true, message, '==', assert.ok);
  222}
  223assert.ok = ok;
  224
  225// 5. The equality assertion tests shallow, coercive equality with
  226// ==.
  227// assert.equal(actual, expected, message_opt);
  228
  229assert.equal = function equal(actual, expected, message) {
  230  if (actual != expected) fail(actual, expected, message, '==', assert.equal);
  231};
  232
  233// 6. The non-equality assertion tests for whether two objects are not equal
  234// with != assert.notEqual(actual, expected, message_opt);
  235
  236assert.notEqual = function notEqual(actual, expected, message) {
  237  if (actual == expected) {
  238    fail(actual, expected, message, '!=', assert.notEqual);
  239  }
  240};
  241
  242// 7. The equivalence assertion tests a deep equality relation.
  243// assert.deepEqual(actual, expected, message_opt);
  244
  245assert.deepEqual = function deepEqual(actual, expected, message) {
  246  if (!_deepEqual(actual, expected, false)) {
  247    fail(actual, expected, message, 'deepEqual', assert.deepEqual);
  248  }
  249};
  250
  251assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
  252  if (!_deepEqual(actual, expected, true)) {
  253    fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
  254  }
  255};
  256
  257function _deepEqual(actual, expected, strict, memos) {
  258  // 7.1. All identical values are equivalent, as determined by ===.
  259  if (actual === expected) {
  260    return true;
  261  } else if (isBuffer(actual) && isBuffer(expected)) {
  262    return compare(actual, expected) === 0;
  263
  264  // 7.2. If the expected value is a Date object, the actual value is
  265  // equivalent if it is also a Date object that refers to the same time.
  266  } else if (util.isDate(actual) && util.isDate(expected)) {
  267    return actual.getTime() === expected.getTime();
  268
  269  // 7.3 If the expected value is a RegExp object, the actual value is
  270  // equivalent if it is also a RegExp object with the same source and
  271  // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
  272  } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
  273    return actual.source === expected.source &&
  274           actual.global === expected.global &&
  275           actual.multiline === expected.multiline &&
  276           actual.lastIndex === expected.lastIndex &&
  277           actual.ignoreCase === expected.ignoreCase;
  278
  279  // 7.4. Other pairs that do not both pass typeof value == 'object',
  280  // equivalence is determined by ==.
  281  } else if ((actual === null || typeof actual !== 'object') &&
  282             (expected === null || typeof expected !== 'object')) {
  283    return strict ? actual === expected : actual == expected;
  284
  285  // If both values are instances of typed arrays, wrap their underlying
  286  // ArrayBuffers in a Buffer each to increase performance
  287  // This optimization requires the arrays to have the same type as checked by
  288  // Object.prototype.toString (aka pToString). Never perform binary
  289  // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
  290  // bit patterns are not identical.
  291  } else if (isView(actual) && isView(expected) &&
  292             pToString(actual) === pToString(expected) &&
  293             !(actual instanceof Float32Array ||
  294               actual instanceof Float64Array)) {
  295    return compare(new Uint8Array(actual.buffer),
  296                   new Uint8Array(expected.buffer)) === 0;
  297
  298  // 7.5 For all other Object pairs, including Array objects, equivalence is
  299  // determined by having the same number of owned properties (as verified
  300  // with Object.prototype.hasOwnProperty.call), the same set of keys
  301  // (although not necessarily the same order), equivalent values for every
  302  // corresponding key, and an identical 'prototype' property. Note: this
  303  // accounts for both named and indexed properties on Arrays.
  304  } else if (isBuffer(actual) !== isBuffer(expected)) {
  305    return false;
  306  } else {
  307    memos = memos || {actual: [], expected: []};
  308
  309    var actualIndex = memos.actual.indexOf(actual);
  310    if (actualIndex !== -1) {
  311      if (actualIndex === memos.expected.indexOf(expected)) {
  312        return true;
  313      }
  314    }
  315
  316    memos.actual.push(actual);
  317    memos.expected.push(expected);
  318
  319    return objEquiv(actual, expected, strict, memos);
  320  }
  321}
  322
  323function isArguments(object) {
  324  return Object.prototype.toString.call(object) == '[object Arguments]';
  325}
  326
  327function objEquiv(a, b, strict, actualVisitedObjects) {
  328  if (a === null || a === undefined || b === null || b === undefined)
  329    return false;
  330  // if one is a primitive, the other must be same
  331  if (util.isPrimitive(a) || util.isPrimitive(b))
  332    return a === b;
  333  if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
  334    return false;
  335  var aIsArgs = isArguments(a);
  336  var bIsArgs = isArguments(b);
  337  if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
  338    return false;
  339  if (aIsArgs) {
  340    a = pSlice.call(a);
  341    b = pSlice.call(b);
  342    return _deepEqual(a, b, strict);
  343  }
  344  var ka = objectKeys(a);
  345  var kb = objectKeys(b);
  346  var key, i;
  347  // having the same number of owned properties (keys incorporates
  348  // hasOwnProperty)
  349  if (ka.length !== kb.length)
  350    return false;
  351  //the same set of keys (although not necessarily the same order),
  352  ka.sort();
  353  kb.sort();
  354  //~~~cheap key test
  355  for (i = ka.length - 1; i >= 0; i--) {
  356    if (ka[i] !== kb[i])
  357      return false;
  358  }
  359  //equivalent values for every corresponding key, and
  360  //~~~possibly expensive deep test
  361  for (i = ka.length - 1; i >= 0; i--) {
  362    key = ka[i];
  363    if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
  364      return false;
  365  }
  366  return true;
  367}
  368
  369// 8. The non-equivalence assertion tests for any deep inequality.
  370// assert.notDeepEqual(actual, expected, message_opt);
  371
  372assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
  373  if (_deepEqual(actual, expected, false)) {
  374    fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
  375  }
  376};
  377
  378assert.notDeepStrictEqual = notDeepStrictEqual;
  379function notDeepStrictEqual(actual, expected, message) {
  380  if (_deepEqual(actual, expected, true)) {
  381    fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
  382  }
  383}
  384
  385
  386// 9. The strict equality assertion tests strict equality, as determined by ===.
  387// assert.strictEqual(actual, expected, message_opt);
  388
  389assert.strictEqual = function strictEqual(actual, expected, message) {
  390  if (actual !== expected) {
  391    fail(actual, expected, message, '===', assert.strictEqual);
  392  }
  393};
  394
  395// 10. The strict non-equality assertion tests for strict inequality, as
  396// determined by !==.  assert.notStrictEqual(actual, expected, message_opt);
  397
  398assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
  399  if (actual === expected) {
  400    fail(actual, expected, message, '!==', assert.notStrictEqual);
  401  }
  402};
  403
  404function expectedException(actual, expected) {
  405  if (!actual || !expected) {
  406    return false;
  407  }
  408
  409  if (Object.prototype.toString.call(expected) == '[object RegExp]') {
  410    return expected.test(actual);
  411  }
  412
  413  try {
  414    if (actual instanceof expected) {
  415      return true;
  416    }
  417  } catch (e) {
  418    // Ignore.  The instanceof check doesn't work for arrow functions.
  419  }
  420
  421  if (Error.isPrototypeOf(expected)) {
  422    return false;
  423  }
  424
  425  return expected.call({}, actual) === true;
  426}
  427
  428function _tryBlock(block) {
  429  var error;
  430  try {
  431    block();
  432  } catch (e) {
  433    error = e;
  434  }
  435  return error;
  436}
  437
  438function _throws(shouldThrow, block, expected, message) {
  439  var actual;
  440
  441  if (typeof block !== 'function') {
  442    throw new TypeError('"block" argument must be a function');
  443  }
  444
  445  if (typeof expected === 'string') {
  446    message = expected;
  447    expected = null;
  448  }
  449
  450  actual = _tryBlock(block);
  451
  452  message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
  453            (message ? ' ' + message : '.');
  454
  455  if (shouldThrow && !actual) {
  456    fail(actual, expected, 'Missing expected exception' + message);
  457  }
  458
  459  var userProvidedMessage = typeof message === 'string';
  460  var isUnwantedException = !shouldThrow && util.isError(actual);
  461  var isUnexpectedException = !shouldThrow && actual && !expected;
  462
  463  if ((isUnwantedException &&
  464      userProvidedMessage &&
  465      expectedException(actual, expected)) ||
  466      isUnexpectedException) {
  467    fail(actual, expected, 'Got unwanted exception' + message);
  468  }
  469
  470  if ((shouldThrow && actual && expected &&
  471      !expectedException(actual, expected)) || (!shouldThrow && actual)) {
  472    throw actual;
  473  }
  474}
  475
  476// 11. Expected to throw an error:
  477// assert.throws(block, Error_opt, message_opt);
  478
  479assert.throws = function(block, /*optional*/error, /*optional*/message) {
  480  _throws(true, block, error, message);
  481};
  482
  483// EXTENSION! This is annoying to write outside this module.
  484assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
  485  _throws(false, block, error, message);
  486};
  487
  488assert.ifError = function(err) { if (err) throw err; };
  489
  490// Expose a strict only variant of assert
  491function strict(value, message) {
  492  if (!value) fail(value, true, message, '==', strict);
  493}
  494assert.strict = objectAssign(strict, assert, {
  495  equal: assert.strictEqual,
  496  deepEqual: assert.deepStrictEqual,
  497  notEqual: assert.notStrictEqual,
  498  notDeepEqual: assert.notDeepStrictEqual
  499});
  500assert.strict.strict = assert.strict;
  501
  502var objectKeys = Object.keys || function (obj) {
  503  var keys = [];
  504  for (var key in obj) {
  505    if (hasOwn.call(obj, key)) keys.push(key);
  506  }
  507  return keys;
  508};
  509
  510}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
  511},{"object-assign":38,"util/":4}],2:[function(require,module,exports){
  512if (typeof Object.create === 'function') {
  513  // implementation from standard node.js 'util' module
  514  module.exports = function inherits(ctor, superCtor) {
  515    ctor.super_ = superCtor
  516    ctor.prototype = Object.create(superCtor.prototype, {
  517      constructor: {
  518        value: ctor,
  519        enumerable: false,
  520        writable: true,
  521        configurable: true
  522      }
  523    });
  524  };
  525} else {
  526  // old school shim for old browsers
  527  module.exports = function inherits(ctor, superCtor) {
  528    ctor.super_ = superCtor
  529    var TempCtor = function () {}
  530    TempCtor.prototype = superCtor.prototype
  531    ctor.prototype = new TempCtor()
  532    ctor.prototype.constructor = ctor
  533  }
  534}
  535
  536},{}],3:[function(require,module,exports){
  537module.exports = function isBuffer(arg) {
  538  return arg && typeof arg === 'object'
  539    && typeof arg.copy === 'function'
  540    && typeof arg.fill === 'function'
  541    && typeof arg.readUInt8 === 'function';
  542}
  543},{}],4:[function(require,module,exports){
  544(function (process,global){
  545// Copyright Joyent, Inc. and other Node contributors.
  546//
  547// Permission is hereby granted, free of charge, to any person obtaining a
  548// copy of this software and associated documentation files (the
  549// "Software"), to deal in the Software without restriction, including
  550// without limitation the rights to use, copy, modify, merge, publish,
  551// distribute, sublicense, and/or sell copies of the Software, and to permit
  552// persons to whom the Software is furnished to do so, subject to the
  553// following conditions:
  554//
  555// The above copyright notice and this permission notice shall be included
  556// in all copies or substantial portions of the Software.
  557//
  558// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
  559// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  560// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
  561// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
  562// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
  563// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
  564// USE OR OTHER DEALINGS IN THE SOFTWARE.
  565
  566var formatRegExp = /%[sdj%]/g;
  567exports.format = function(f) {
  568  if (!isString(f)) {
  569    var objects = [];
  570    for (var i = 0; i < arguments.length; i++) {
  571      objects.push(inspect(arguments[i]));
  572    }
  573    return objects.join(' ');
  574  }
  575
  576  var i = 1;
  577  var args = arguments;
  578  var len = args.length;
  579  var str = String(f).replace(formatRegExp, function(x) {
  580    if (x === '%%') return '%';
  581    if (i >= len) return x;
  582    switch (x) {
  583      case '%s': return String(args[i++]);
  584      case '%d': return Number(args[i++]);
  585      case '%j':
  586        try {
  587          return JSON.stringify(args[i++]);
  588        } catch (_) {
  589          return '[Circular]';
  590        }
  591      default:
  592        return x;
  593    }
  594  });
  595  for (var x = args[i]; i < len; x = args[++i]) {
  596    if (isNull(x) || !isObject(x)) {
  597      str += ' ' + x;
  598    } else {
  599      str += ' ' + inspect(x);
  600    }
  601  }
  602  return str;
  603};
  604
  605
  606// Mark that a method should not be used.
  607// Returns a modified function which warns once by default.
  608// If --no-deprecation is set, then it is a no-op.
  609exports.deprecate = function(fn, msg) {
  610  // Allow for deprecating things in the process of starting up.
  611  if (isUndefined(global.process)) {
  612    return function() {
  613      return exports.deprecate(fn, msg).apply(this, arguments);
  614    };
  615  }
  616
  617  if (process.noDeprecation === true) {
  618    return fn;
  619  }
  620
  621  var warned = false;
  622  function deprecated() {
  623    if (!warned) {
  624      if (process.throwDeprecation) {
  625        throw new Error(msg);
  626      } else if (process.traceDeprecation) {
  627        console.trace(msg);
  628      } else {
  629        console.error(msg);
  630      }
  631      warned = true;
  632    }
  633    return fn.apply(this, arguments);
  634  }
  635
  636  return deprecated;
  637};
  638
  639
  640var debugs = {};
  641var debugEnviron;
  642exports.debuglog = function(set) {
  643  if (isUndefined(debugEnviron))
  644    debugEnviron = process.env.NODE_DEBUG || '';
  645  set = set.toUpperCase();
  646  if (!debugs[set]) {
  647    if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
  648      var pid = process.pid;
  649      debugs[set] = function() {
  650        var msg = exports.format.apply(exports, arguments);
  651        console.error('%s %d: %s', set, pid, msg);
  652      };
  653    } else {
  654      debugs[set] = function() {};
  655    }
  656  }
  657  return debugs[set];
  658};
  659
  660
  661/**
  662 * Echos the value of a value. Trys to print the value out
  663 * in the best way possible given the different types.
  664 *
  665 * @param {Object} obj The object to print out.
  666 * @param {Object} opts Optional options object that alters the output.
  667 */
  668/* legacy: obj, showHidden, depth, colors*/
  669function inspect(obj, opts) {
  670  // default options
  671  var ctx = {
  672    seen: [],
  673    stylize: stylizeNoColor
  674  };
  675  // legacy...
  676  if (arguments.length >= 3) ctx.depth = arguments[2];
  677  if (arguments.length >= 4) ctx.colors = arguments[3];
  678  if (isBoolean(opts)) {
  679    // legacy...
  680    ctx.showHidden = opts;
  681  } else if (opts) {
  682    // got an "options" object
  683    exports._extend(ctx, opts);
  684  }
  685  // set default options
  686  if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
  687  if (isUndefined(ctx.depth)) ctx.depth = 2;
  688  if (isUndefined(ctx.colors)) ctx.colors = false;
  689  if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
  690  if (ctx.colors) ctx.stylize = stylizeWithColor;
  691  return formatValue(ctx, obj, ctx.depth);
  692}
  693exports.inspect = inspect;
  694
  695
  696// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
  697inspect.colors = {
  698  'bold' : [1, 22],
  699  'italic' : [3, 23],
  700  'underline' : [4, 24],
  701  'inverse' : [7, 27],
  702  'white' : [37, 39],
  703  'grey' : [90, 39],
  704  'black' : [30, 39],
  705  'blue' : [34, 39],
  706  'cyan' : [36, 39],
  707  'green' : [32, 39],
  708  'magenta' : [35, 39],
  709  'red' : [31, 39],
  710  'yellow' : [33, 39]
  711};
  712
  713// Don't use 'blue' not visible on cmd.exe
  714inspect.styles = {
  715  'special': 'cyan',
  716  'number': 'yellow',
  717  'boolean': 'yellow',
  718  'undefined': 'grey',
  719  'null': 'bold',
  720  'string': 'green',
  721  'date': 'magenta',
  722  // "name": intentionally not styling
  723  'regexp': 'red'
  724};
  725
  726
  727function stylizeWithColor(str, styleType) {
  728  var style = inspect.styles[styleType];
  729
  730  if (style) {
  731    return '\u001b[' + inspect.colors[style][0] + 'm' + str +
  732           '\u001b[' + inspect.colors[style][1] + 'm';
  733  } else {
  734    return str;
  735  }
  736}
  737
  738
  739function stylizeNoColor(str, styleType) {
  740  return str;
  741}
  742
  743
  744function arrayToHash(array) {
  745  var hash = {};
  746
  747  array.forEach(function(val, idx) {
  748    hash[val] = true;
  749  });
  750
  751  return hash;
  752}
  753
  754
  755function formatValue(ctx, value, recurseTimes) {
  756  // Provide a hook for user-specified inspect functions.
  757  // Check that value is an object with an inspect function on it
  758  if (ctx.customInspect &&
  759      value &&
  760      isFunction(value.inspect) &&
  761      // Filter out the util module, it's inspect function is special
  762      value.inspect !== exports.inspect &&
  763      // Also filter out any prototype objects using the circular check.
  764      !(value.constructor && value.constructor.prototype === value)) {
  765    var ret = value.inspect(recurseTimes, ctx);
  766    if (!isString(ret)) {
  767      ret = formatValue(ctx, ret, recurseTimes);
  768    }
  769    return ret;
  770  }
  771
  772  // Primitive types cannot have properties
  773  var primitive = formatPrimitive(ctx, value);
  774  if (primitive) {
  775    return primitive;
  776  }
  777
  778  // Look up the keys of the object.
  779  var keys = Object.keys(value);
  780  var visibleKeys = arrayToHash(keys);
  781
  782  if (ctx.showHidden) {
  783    keys = Object.getOwnPropertyNames(value);
  784  }
  785
  786  // IE doesn't make error fields non-enumerable
  787  // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
  788  if (isError(value)
  789      && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
  790    return formatError(value);
  791  }
  792
  793  // Some type of object without properties can be shortcutted.
  794  if (keys.length === 0) {
  795    if (isFunction(value)) {
  796      var name = value.name ? ': ' + value.name : '';
  797      return ctx.stylize('[Function' + name + ']', 'special');
  798    }
  799    if (isRegExp(value)) {
  800      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  801    }
  802    if (isDate(value)) {
  803      return ctx.stylize(Date.prototype.toString.call(value), 'date');
  804    }
  805    if (isError(value)) {
  806      return formatError(value);
  807    }
  808  }
  809
  810  var base = '', array = false, braces = ['{', '}'];
  811
  812  // Make Array say that they are Array
  813  if (isArray(value)) {
  814    array = true;
  815    braces = ['[', ']'];
  816  }
  817
  818  // Make functions say that they are functions
  819  if (isFunction(value)) {
  820    var n = value.name ? ': ' + value.name : '';
  821    base = ' [Function' + n + ']';
  822  }
  823
  824  // Make RegExps say that they are RegExps
  825  if (isRegExp(value)) {
  826    base = ' ' + RegExp.prototype.toString.call(value);
  827  }
  828
  829  // Make dates with properties first say the date
  830  if (isDate(value)) {
  831    base = ' ' + Date.prototype.toUTCString.call(value);
  832  }
  833
  834  // Make error with message first say the error
  835  if (isError(value)) {
  836    base = ' ' + formatError(value);
  837  }
  838
  839  if (keys.length === 0 && (!array || value.length == 0)) {
  840    return braces[0] + base + braces[1];
  841  }
  842
  843  if (recurseTimes < 0) {
  844    if (isRegExp(value)) {
  845      return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
  846    } else {
  847      return ctx.stylize('[Object]', 'special');
  848    }
  849  }
  850
  851  ctx.seen.push(value);
  852
  853  var output;
  854  if (array) {
  855    output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
  856  } else {
  857    output = keys.map(function(key) {
  858      return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
  859    });
  860  }
  861
  862  ctx.seen.pop();
  863
  864  return reduceToSingleString(output, base, braces);
  865}
  866
  867
  868function formatPrimitive(ctx, value) {
  869  if (isUndefined(value))
  870    return ctx.stylize('undefined', 'undefined');
  871  if (isString(value)) {
  872    var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
  873                                             .replace(/'/g, "\\'")
  874                                             .replace(/\\"/g, '"') + '\'';
  875    return ctx.stylize(simple, 'string');
  876  }
  877  if (isNumber(value))
  878    return ctx.stylize('' + value, 'number');
  879  if (isBoolean(value))
  880    return ctx.stylize('' + value, 'boolean');
  881  // For some reason typeof null is "object", so special case here.
  882  if (isNull(value))
  883    return ctx.stylize('null', 'null');
  884}
  885
  886
  887function formatError(value) {
  888  return '[' + Error.prototype.toString.call(value) + ']';
  889}
  890
  891
  892function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
  893  var output = [];
  894  for (var i = 0, l = value.length; i < l; ++i) {
  895    if (hasOwnProperty(value, String(i))) {
  896      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  897          String(i), true));
  898    } else {
  899      output.push('');
  900    }
  901  }
  902  keys.forEach(function(key) {
  903    if (!key.match(/^\d+$/)) {
  904      output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
  905          key, true));
  906    }
  907  });
  908  return output;
  909}
  910
  911
  912function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
  913  var name, str, desc;
  914  desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
  915  if (desc.get) {
  916    if (desc.set) {
  917      str = ctx.stylize('[Getter/Setter]', 'special');
  918    } else {
  919      str = ctx.stylize('[Getter]', 'special');
  920    }
  921  } else {
  922    if (desc.set) {
  923      str = ctx.stylize('[Setter]', 'special');
  924    }
  925  }
  926  if (!hasOwnProperty(visibleKeys, key)) {
  927    name = '[' + key + ']';
  928  }
  929  if (!str) {
  930    if (ctx.seen.indexOf(desc.value) < 0) {
  931      if (isNull(recurseTimes)) {
  932        str = formatValue(ctx, desc.value, null);
  933      } else {
  934        str = formatValue(ctx, desc.value, recurseTimes - 1);
  935      }
  936      if (str.indexOf('\n') > -1) {
  937        if (array) {
  938          str = str.split('\n').map(function(line) {
  939            return '  ' + line;
  940          }).join('\n').substr(2);
  941        } else {
  942          str = '\n' + str.split('\n').map(function(line) {
  943            return '   ' + line;
  944          }).join('\n');
  945        }
  946      }
  947    } else {
  948      str = ctx.stylize('[Circular]', 'special');
  949    }
  950  }
  951  if (isUndefined(name)) {
  952    if (array && key.match(/^\d+$/)) {
  953      return str;
  954    }
  955    name = JSON.stringify('' + key);
  956    if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
  957      name = name.substr(1, name.length - 2);
  958      name = ctx.stylize(name, 'name');
  959    } else {
  960      name = name.replace(/'/g, "\\'")
  961                 .replace(/\\"/g, '"')
  962                 .replace(/(^"|"$)/g, "'");
  963      name = ctx.stylize(name, 'string');
  964    }
  965  }
  966
  967  return name + ': ' + str;
  968}
  969
  970
  971function reduceToSingleString(output, base, braces) {
  972  var numLinesEst = 0;
  973  var length = output.reduce(function(prev, cur) {
  974    numLinesEst++;
  975    if (cur.indexOf('\n') >= 0) numLinesEst++;
  976    return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
  977  }, 0);
  978
  979  if (length > 60) {
  980    return braces[0] +
  981           (base === '' ? '' : base + '\n ') +
  982           ' ' +
  983           output.join(',\n  ') +
  984           ' ' +
  985           braces[1];
  986  }
  987
  988  return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
  989}
  990
  991
  992// NOTE: These type checking functions intentionally don't use `instanceof`
  993// because it is fragile and can be easily faked with `Object.create()`.
  994function isArray(ar) {
  995  return Array.isArray(ar);
  996}
  997exports.isArray = isArray;
  998
  999function isBoolean(arg) {
 1000  return typeof arg === 'boolean';
 1001}
 1002exports.isBoolean = isBoolean;
 1003
 1004function isNull(arg) {
 1005  return arg === null;
 1006}
 1007exports.isNull = isNull;
 1008
 1009function isNullOrUndefined(arg) {
 1010  return arg == null;
 1011}
 1012exports.isNullOrUndefined = isNullOrUndefined;
 1013
 1014function isNumber(arg) {
 1015  return typeof arg === 'number';
 1016}
 1017exports.isNumber = isNumber;
 1018
 1019function isString(arg) {
 1020  return typeof arg === 'string';
 1021}
 1022exports.isString = isString;
 1023
 1024function isSymbol(arg) {
 1025  return typeof arg === 'symbol';
 1026}
 1027exports.isSymbol = isSymbol;
 1028
 1029function isUndefined(arg) {
 1030  return arg === void 0;
 1031}
 1032exports.isUndefined = isUndefined;
 1033
 1034function isRegExp(re) {
 1035  return isObject(re) && objectToString(re) === '[object RegExp]';
 1036}
 1037exports.isRegExp = isRegExp;
 1038
 1039function isObject(arg) {
 1040  return typeof arg === 'object' && arg !== null;
 1041}
 1042exports.isObject = isObject;
 1043
 1044function isDate(d) {
 1045  return isObject(d) && objectToString(d) === '[object Date]';
 1046}
 1047exports.isDate = isDate;
 1048
 1049function isError(e) {
 1050  return isObject(e) &&
 1051      (objectToString(e) === '[object Error]' || e instanceof Error);
 1052}
 1053exports.isError = isError;
 1054
 1055function isFunction(arg) {
 1056  return typeof arg === 'function';
 1057}
 1058exports.isFunction = isFunction;
 1059
 1060function isPrimitive(arg) {
 1061  return arg === null ||
 1062         typeof arg === 'boolean' ||
 1063         typeof arg === 'number' ||
 1064         typeof arg === 'string' ||
 1065         typeof arg === 'symbol' ||  // ES6 symbol
 1066         typeof arg === 'undefined';
 1067}
 1068exports.isPrimitive = isPrimitive;
 1069
 1070exports.isBuffer = require('./support/isBuffer');
 1071
 1072function objectToString(o) {
 1073  return Object.prototype.toString.call(o);
 1074}
 1075
 1076
 1077function pad(n) {
 1078  return n < 10 ? '0' + n.toString(10) : n.toString(10);
 1079}
 1080
 1081
 1082var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
 1083              'Oct', 'Nov', 'Dec'];
 1084
 1085// 26 Feb 16:19:34
 1086function timestamp() {
 1087  var d = new Date();
 1088  var time = [pad(d.getHours()),
 1089              pad(d.getMinutes()),
 1090              pad(d.getSeconds())].join(':');
 1091  return [d.getDate(), months[d.getMonth()], time].join(' ');
 1092}
 1093
 1094
 1095// log is just a thin wrapper to console.log that prepends a timestamp
 1096exports.log = function() {
 1097  console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
 1098};
 1099
 1100
 1101/**
 1102 * Inherit the prototype methods from one constructor into another.
 1103 *
 1104 * The Function.prototype.inherits from lang.js rewritten as a standalone
 1105 * function (not on Function.prototype). NOTE: If this file is to be loaded
 1106 * during bootstrapping this function needs to be rewritten using some native
 1107 * functions as prototype setup using normal JavaScript does not work as
 1108 * expected during bootstrapping (see mirror.js in r114903).
 1109 *
 1110 * @param {function} ctor Constructor function which needs to inherit the
 1111 *     prototype.
 1112 * @param {function} superCtor Constructor function to inherit prototype from.
 1113 */
 1114exports.inherits = require('inherits');
 1115
 1116exports._extend = function(origin, add) {
 1117  // Don't do anything if add isn't an object
 1118  if (!add || !isObject(add)) return origin;
 1119
 1120  var keys = Object.keys(add);
 1121  var i = keys.length;
 1122  while (i--) {
 1123    origin[keys[i]] = add[keys[i]];
 1124  }
 1125  return origin;
 1126};
 1127
 1128function hasOwnProperty(obj, prop) {
 1129  return Object.prototype.hasOwnProperty.call(obj, prop);
 1130}
 1131
 1132}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
 1133},{"./support/isBuffer":3,"_process":9,"inherits":2}],5:[function(require,module,exports){
 1134'use strict'
 1135
 1136exports.byteLength = byteLength
 1137exports.toByteArray = toByteArray
 1138exports.fromByteArray = fromByteArray
 1139
 1140var lookup = []
 1141var revLookup = []
 1142var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
 1143
 1144var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
 1145for (var i = 0, len = code.length; i < len; ++i) {
 1146  lookup[i] = code[i]
 1147  revLookup[code.charCodeAt(i)] = i
 1148}
 1149
 1150// Support decoding URL-safe base64 strings, as Node.js does.
 1151// See: https://en.wikipedia.org/wiki/Base64#URL_applications
 1152revLookup['-'.charCodeAt(0)] = 62
 1153revLookup['_'.charCodeAt(0)] = 63
 1154
 1155function getLens (b64) {
 1156  var len = b64.length
 1157
 1158  if (len % 4 > 0) {
 1159    throw new Error('Invalid string. Length must be a multiple of 4')
 1160  }
 1161
 1162  // Trim off extra bytes after placeholder bytes are found
 1163  // See: https://github.com/beatgammit/base64-js/issues/42
 1164  var validLen = b64.indexOf('=')
 1165  if (validLen === -1) validLen = len
 1166
 1167  var placeHoldersLen = validLen === len
 1168    ? 0
 1169    : 4 - (validLen % 4)
 1170
 1171  return [validLen, placeHoldersLen]
 1172}
 1173
 1174// base64 is 4/3 + up to two characters of the original data
 1175function byteLength (b64) {
 1176  var lens = getLens(b64)
 1177  var validLen = lens[0]
 1178  var placeHoldersLen = lens[1]
 1179  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
 1180}
 1181
 1182function _byteLength (b64, validLen, placeHoldersLen) {
 1183  return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
 1184}
 1185
 1186function toByteArray (b64) {
 1187  var tmp
 1188  var lens = getLens(b64)
 1189  var validLen = lens[0]
 1190  var placeHoldersLen = lens[1]
 1191
 1192  var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
 1193
 1194  var curByte = 0
 1195
 1196  // if there are placeholders, only get up to the last complete 4 chars
 1197  var len = placeHoldersLen > 0
 1198    ? validLen - 4
 1199    : validLen
 1200
 1201  var i
 1202  for (i = 0; i < len; i += 4) {
 1203    tmp =
 1204      (revLookup[b64.charCodeAt(i)] << 18) |
 1205      (revLookup[b64.charCodeAt(i + 1)] << 12) |
 1206      (revLookup[b64.charCodeAt(i + 2)] << 6) |
 1207      revLookup[b64.charCodeAt(i + 3)]
 1208    arr[curByte++] = (tmp >> 16) & 0xFF
 1209    arr[curByte++] = (tmp >> 8) & 0xFF
 1210    arr[curByte++] = tmp & 0xFF
 1211  }
 1212
 1213  if (placeHoldersLen === 2) {
 1214    tmp =
 1215      (revLookup[b64.charCodeAt(i)] << 2) |
 1216      (revLookup[b64.charCodeAt(i + 1)] >> 4)
 1217    arr[curByte++] = tmp & 0xFF
 1218  }
 1219
 1220  if (placeHoldersLen === 1) {
 1221    tmp =
 1222      (revLookup[b64.charCodeAt(i)] << 10) |
 1223      (revLookup[b64.charCodeAt(i + 1)] << 4) |
 1224      (revLookup[b64.charCodeAt(i + 2)] >> 2)
 1225    arr[curByte++] = (tmp >> 8) & 0xFF
 1226    arr[curByte++] = tmp & 0xFF
 1227  }
 1228
 1229  return arr
 1230}
 1231
 1232function tripletToBase64 (num) {
 1233  return lookup[num >> 18 & 0x3F] +
 1234    lookup[num >> 12 & 0x3F] +
 1235    lookup[num >> 6 & 0x3F] +
 1236    lookup[num & 0x3F]
 1237}
 1238
 1239function encodeChunk (uint8, start, end) {
 1240  var tmp
 1241  var output = []
 1242  for (var i = start; i < end; i += 3) {
 1243    tmp =
 1244      ((uint8[i] << 16) & 0xFF0000) +
 1245      ((uint8[i + 1] << 8) & 0xFF00) +
 1246      (uint8[i + 2] & 0xFF)
 1247    output.push(tripletToBase64(tmp))
 1248  }
 1249  return output.join('')
 1250}
 1251
 1252function fromByteArray (uint8) {
 1253  var tmp
 1254  var len = uint8.length
 1255  var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
 1256  var parts = []
 1257  var maxChunkLength = 16383 // must be multiple of 3
 1258
 1259  // go through the array every three bytes, we'll deal with trailing stuff later
 1260  for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
 1261    parts.push(encodeChunk(
 1262      uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)
 1263    ))
 1264  }
 1265
 1266  // pad the end with zeros, but make sure to not forget the extra bytes
 1267  if (extraBytes === 1) {
 1268    tmp = uint8[len - 1]
 1269    parts.push(
 1270      lookup[tmp >> 2] +
 1271      lookup[(tmp << 4) & 0x3F] +
 1272      '=='
 1273    )
 1274  } else if (extraBytes === 2) {
 1275    tmp = (uint8[len - 2] << 8) + uint8[len - 1]
 1276    parts.push(
 1277      lookup[tmp >> 10] +
 1278      lookup[(tmp >> 4) & 0x3F] +
 1279      lookup[(tmp << 2) & 0x3F] +
 1280      '='
 1281    )
 1282  }
 1283
 1284  return parts.join('')
 1285}
 1286
 1287},{}],6:[function(require,module,exports){
 1288var bigInt = (function (undefined) {
 1289    "use strict";
 1290
 1291    var BASE = 1e7,
 1292        LOG_BASE = 7,
 1293        MAX_INT = 9007199254740992,
 1294        MAX_INT_ARR = smallToArray(MAX_INT),
 1295        DEFAULT_ALPHABET = "0123456789abcdefghijklmnopqrstuvwxyz";
 1296
 1297    var supportsNativeBigInt = typeof BigInt === "function";
 1298
 1299    function Integer(v, radix, alphabet, caseSensitive) {
 1300        if (typeof v === "undefined") return Integer[0];
 1301        if (typeof radix !== "undefined") return +radix === 10 && !alphabet ? parseValue(v) : parseBase(v, radix, alphabet, caseSensitive);
 1302        return parseValue(v);
 1303    }
 1304
 1305    function BigInteger(value, sign) {
 1306        this.value = value;
 1307        this.sign = sign;
 1308        this.isSmall = false;
 1309    }
 1310    BigInteger.prototype = Object.create(Integer.prototype);
 1311
 1312    function SmallInteger(value) {
 1313        this.value = value;
 1314        this.sign = value < 0;
 1315        this.isSmall = true;
 1316    }
 1317    SmallInteger.prototype = Object.create(Integer.prototype);
 1318
 1319    function NativeBigInt(value) {
 1320        this.value = value;
 1321    }
 1322    NativeBigInt.prototype = Object.create(Integer.prototype);
 1323
 1324    function isPrecise(n) {
 1325        return -MAX_INT < n && n < MAX_INT;
 1326    }
 1327
 1328    function smallToArray(n) { // For performance reasons doesn't reference BASE, need to change this function if BASE changes
 1329        if (n < 1e7)
 1330            return [n];
 1331        if (n < 1e14)
 1332            return [n % 1e7, Math.floor(n / 1e7)];
 1333        return [n % 1e7, Math.floor(n / 1e7) % 1e7, Math.floor(n / 1e14)];
 1334    }
 1335
 1336    function arrayToSmall(arr) { // If BASE changes this function may need to change
 1337        trim(arr);
 1338        var length = arr.length;
 1339        if (length < 4 && compareAbs(arr, MAX_INT_ARR) < 0) {
 1340            switch (length) {
 1341                case 0: return 0;
 1342                case 1: return arr[0];
 1343                case 2: return arr[0] + arr[1] * BASE;
 1344                default: return arr[0] + (arr[1] + arr[2] * BASE) * BASE;
 1345            }
 1346        }
 1347        return arr;
 1348    }
 1349
 1350    function trim(v) {
 1351        var i = v.length;
 1352        while (v[--i] === 0);
 1353        v.length = i + 1;
 1354    }
 1355
 1356    function createArray(length) { // function shamelessly stolen from Yaffle's library https://github.com/Yaffle/BigInteger
 1357        var x = new Array(length);
 1358        var i = -1;
 1359        while (++i < length) {
 1360            x[i] = 0;
 1361        }
 1362        return x;
 1363    }
 1364
 1365    function truncate(n) {
 1366        if (n > 0) return Math.floor(n);
 1367        return Math.ceil(n);
 1368    }
 1369
 1370    function add(a, b) { // assumes a and b are arrays with a.length >= b.length
 1371        var l_a = a.length,
 1372            l_b = b.length,
 1373            r = new Array(l_a),
 1374            carry = 0,
 1375            base = BASE,
 1376            sum, i;
 1377        for (i = 0; i < l_b; i++) {
 1378            sum = a[i] + b[i] + carry;
 1379            carry = sum >= base ? 1 : 0;
 1380            r[i] = sum - carry * base;
 1381        }
 1382        while (i < l_a) {
 1383            sum = a[i] + carry;
 1384            carry = sum === base ? 1 : 0;
 1385            r[i++] = sum - carry * base;
 1386        }
 1387        if (carry > 0) r.push(carry);
 1388        return r;
 1389    }
 1390
 1391    function addAny(a, b) {
 1392        if (a.length >= b.length) return add(a, b);
 1393        return add(b, a);
 1394    }
 1395
 1396    function addSmall(a, carry) { // assumes a is array, carry is number with 0 <= carry < MAX_INT
 1397        var l = a.length,
 1398            r = new Array(l),
 1399            base = BASE,
 1400            sum, i;
 1401        for (i = 0; i < l; i++) {
 1402            sum = a[i] - base + carry;
 1403            carry = Math.floor(sum / base);
 1404            r[i] = sum - carry * base;
 1405            carry += 1;
 1406        }
 1407        while (carry > 0) {
 1408            r[i++] = carry % base;
 1409            carry = Math.floor(carry / base);
 1410        }
 1411        return r;
 1412    }
 1413
 1414    BigInteger.prototype.add = function (v) {
 1415        var n = parseValue(v);
 1416        if (this.sign !== n.sign) {
 1417            return this.subtract(n.negate());
 1418        }
 1419        var a = this.value, b = n.value;
 1420        if (n.isSmall) {
 1421            return new BigInteger(addSmall(a, Math.abs(b)), this.sign);
 1422        }
 1423        return new BigInteger(addAny(a, b), this.sign);
 1424    };
 1425    BigInteger.prototype.plus = BigInteger.prototype.add;
 1426
 1427    SmallInteger.prototype.add = function (v) {
 1428        var n = parseValue(v);
 1429        var a = this.value;
 1430        if (a < 0 !== n.sign) {
 1431            return this.subtract(n.negate());
 1432        }
 1433        var b = n.value;
 1434        if (n.isSmall) {
 1435            if (isPrecise(a + b)) return new SmallInteger(a + b);
 1436            b = smallToArray(Math.abs(b));
 1437        }
 1438        return new BigInteger(addSmall(b, Math.abs(a)), a < 0);
 1439    };
 1440    SmallInteger.prototype.plus = SmallInteger.prototype.add;
 1441
 1442    NativeBigInt.prototype.add = function (v) {
 1443        return new NativeBigInt(this.value + parseValue(v).value);
 1444    }
 1445    NativeBigInt.prototype.plus = NativeBigInt.prototype.add;
 1446
 1447    function subtract(a, b) { // assumes a and b are arrays with a >= b
 1448        var a_l = a.length,
 1449            b_l = b.length,
 1450            r = new Array(a_l),
 1451            borrow = 0,
 1452            base = BASE,
 1453            i, difference;
 1454        for (i = 0; i < b_l; i++) {
 1455            difference = a[i] - borrow - b[i];
 1456            if (difference < 0) {
 1457                difference += base;
 1458                borrow = 1;
 1459            } else borrow = 0;
 1460            r[i] = difference;
 1461        }
 1462        for (i = b_l; i < a_l; i++) {
 1463            difference = a[i] - borrow;
 1464            if (difference < 0) difference += base;
 1465            else {
 1466                r[i++] = difference;
 1467                break;
 1468            }
 1469            r[i] = difference;
 1470        }
 1471        for (; i < a_l; i++) {
 1472            r[i] = a[i];
 1473        }
 1474        trim(r);
 1475        return r;
 1476    }
 1477
 1478    function subtractAny(a, b, sign) {
 1479        var value;
 1480        if (compareAbs(a, b) >= 0) {
 1481            value = subtract(a, b);
 1482        } else {
 1483            value = subtract(b, a);
 1484            sign = !sign;
 1485        }
 1486        value = arrayToSmall(value);
 1487        if (typeof value === "number") {
 1488            if (sign) value = -value;
 1489            return new SmallInteger(value);
 1490        }
 1491        return new BigInteger(value, sign);
 1492    }
 1493
 1494    function subtractSmall(a, b, sign) { // assumes a is array, b is number with 0 <= b < MAX_INT
 1495        var l = a.length,
 1496            r = new Array(l),
 1497            carry = -b,
 1498            base = BASE,
 1499            i, difference;
 1500        for (i = 0; i < l; i++) {
 1501            difference = a[i] + carry;
 1502            carry = Math.floor(difference / base);
 1503            difference %= base;
 1504            r[i] = difference < 0 ? difference + base : difference;
 1505        }
 1506        r = arrayToSmall(r);
 1507        if (typeof r === "number") {
 1508            if (sign) r = -r;
 1509            return new SmallInteger(r);
 1510        } return new BigInteger(r, sign);
 1511    }
 1512
 1513    BigInteger.prototype.subtract = function (v) {
 1514        var n = parseValue(v);
 1515        if (this.sign !== n.sign) {
 1516            return this.add(n.negate());
 1517        }
 1518        var a = this.value, b = n.value;
 1519        if (n.isSmall)
 1520            return subtractSmall(a, Math.abs(b), this.sign);
 1521        return subtractAny(a, b, this.sign);
 1522    };
 1523    BigInteger.prototype.minus = BigInteger.prototype.subtract;
 1524
 1525    SmallInteger.prototype.subtract = function (v) {
 1526        var n = parseValue(v);
 1527        var a = this.value;
 1528        if (a < 0 !== n.sign) {
 1529            return this.add(n.negate());
 1530        }
 1531        var b = n.value;
 1532        if (n.isSmall) {
 1533            return new SmallInteger(a - b);
 1534        }
 1535        return subtractSmall(b, Math.abs(a), a >= 0);
 1536    };
 1537    SmallInteger.prototype.minus = SmallInteger.prototype.subtract;
 1538
 1539    NativeBigInt.prototype.subtract = function (v) {
 1540        return new NativeBigInt(this.value - parseValue(v).value);
 1541    }
 1542    NativeBigInt.prototype.minus = NativeBigInt.prototype.subtract;
 1543
 1544    BigInteger.prototype.negate = function () {
 1545        return new BigInteger(this.value, !this.sign);
 1546    };
 1547    SmallInteger.prototype.negate = function () {
 1548        var sign = this.sign;
 1549        var small = new SmallInteger(-this.value);
 1550        small.sign = !sign;
 1551        return small;
 1552    };
 1553    NativeBigInt.prototype.negate = function () {
 1554        return new NativeBigInt(-this.value);
 1555    }
 1556
 1557    BigInteger.prototype.abs = function () {
 1558        return new BigInteger(this.value, false);
 1559    };
 1560    SmallInteger.prototype.abs = function () {
 1561        return new SmallInteger(Math.abs(this.value));
 1562    };
 1563    NativeBigInt.prototype.abs = function () {
 1564        return new NativeBigInt(this.value >= 0 ? this.value : -this.value);
 1565    }
 1566
 1567
 1568    function multiplyLong(a, b) {
 1569        var a_l = a.length,
 1570            b_l = b.length,
 1571            l = a_l + b_l,
 1572            r = createArray(l),
 1573            base = BASE,
 1574            product, carry, i, a_i, b_j;
 1575        for (i = 0; i < a_l; ++i) {
 1576            a_i = a[i];
 1577            for (var j = 0; j < b_l; ++j) {
 1578                b_j = b[j];
 1579                product = a_i * b_j + r[i + j];
 1580                carry = Math.floor(product / base);
 1581                r[i + j] = product - carry * base;
 1582                r[i + j + 1] += carry;
 1583            }
 1584        }
 1585        trim(r);
 1586        return r;
 1587    }
 1588
 1589    function multiplySmall(a, b) { // assumes a is array, b is number with |b| < BASE
 1590        var l = a.length,
 1591            r = new Array(l),
 1592            base = BASE,
 1593            carry = 0,
 1594            product, i;
 1595        for (i = 0; i < l; i++) {
 1596            product = a[i] * b + carry;
 1597            carry = Math.floor(product / base);
 1598            r[i] = product - carry * base;
 1599        }
 1600        while (carry > 0) {
 1601            r[i++] = carry % base;
 1602            carry = Math.floor(carry / base);
 1603        }
 1604        return r;
 1605    }
 1606
 1607    function shiftLeft(x, n) {
 1608        var r = [];
 1609        while (n-- > 0) r.push(0);
 1610        return r.concat(x);
 1611    }
 1612
 1613    function multiplyKaratsuba(x, y) {
 1614        var n = Math.max(x.length, y.length);
 1615
 1616        if (n <= 30) return multiplyLong(x, y);
 1617        n = Math.ceil(n / 2);
 1618
 1619        var b = x.slice(n),
 1620            a = x.slice(0, n),
 1621            d = y.slice(n),
 1622            c = y.slice(0, n);
 1623
 1624        var ac = multiplyKaratsuba(a, c),
 1625            bd = multiplyKaratsuba(b, d),
 1626            abcd = multiplyKaratsuba(addAny(a, b), addAny(c, d));
 1627
 1628        var product = addAny(addAny(ac, shiftLeft(subtract(subtract(abcd, ac), bd), n)), shiftLeft(bd, 2 * n));
 1629        trim(product);
 1630        return product;
 1631    }
 1632
 1633    // The following function is derived from a surface fit of a graph plotting the performance difference
 1634    // between long multiplication and karatsuba multiplication versus the lengths of the two arrays.
 1635    function useKaratsuba(l1, l2) {
 1636        return -0.012 * l1 - 0.012 * l2 + 0.000015 * l1 * l2 > 0;
 1637    }
 1638
 1639    BigInteger.prototype.multiply = function (v) {
 1640        var n = parseValue(v),
 1641            a = this.value, b = n.value,
 1642            sign = this.sign !== n.sign,
 1643            abs;
 1644        if (n.isSmall) {
 1645            if (b === 0) return Integer[0];
 1646            if (b === 1) return this;
 1647            if (b === -1) return this.negate();
 1648            abs = Math.abs(b);
 1649            if (abs < BASE) {
 1650                return new BigInteger(multiplySmall(a, abs), sign);
 1651            }
 1652            b = smallToArray(abs);
 1653        }
 1654        if (useKaratsuba(a.length, b.length)) // Karatsuba is only faster for certain array sizes
 1655            return new BigInteger(multiplyKaratsuba(a, b), sign);
 1656        return new BigInteger(multiplyLong(a, b), sign);
 1657    };
 1658
 1659    BigInteger.prototype.times = BigInteger.prototype.multiply;
 1660
 1661    function multiplySmallAndArray(a, b, sign) { // a >= 0
 1662        if (a < BASE) {
 1663            return new BigInteger(multiplySmall(b, a), sign);
 1664        }
 1665        return new BigInteger(multiplyLong(b, smallToArray(a)), sign);
 1666    }
 1667    SmallInteger.prototype._multiplyBySmall = function (a) {
 1668        if (isPrecise(a.value * this.value)) {
 1669            return new SmallInteger(a.value * this.value);
 1670        }
 1671        return multiplySmallAndArray(Math.abs(a.value), smallToArray(Math.abs(this.value)), this.sign !== a.sign);
 1672    };
 1673    BigInteger.prototype._multiplyBySmall = function (a) {
 1674        if (a.value === 0) return Integer[0];
 1675        if (a.value === 1) return this;
 1676        if (a.value === -1) return this.negate();
 1677        return multiplySmallAndArray(Math.abs(a.value), this.value, this.sign !== a.sign);
 1678    };
 1679    SmallInteger.prototype.multiply = function (v) {
 1680        return parseValue(v)._multiplyBySmall(this);
 1681    };
 1682    SmallInteger.prototype.times = SmallInteger.prototype.multiply;
 1683
 1684    NativeBigInt.prototype.multiply = function (v) {
 1685        return new NativeBigInt(this.value * parseValue(v).value);
 1686    }
 1687    NativeBigInt.prototype.times = NativeBigInt.prototype.multiply;
 1688
 1689    function square(a) {
 1690        //console.assert(2 * BASE * BASE < MAX_INT);
 1691        var l = a.length,
 1692            r = createArray(l + l),
 1693            base = BASE,
 1694            product, carry, i, a_i, a_j;
 1695        for (i = 0; i < l; i++) {
 1696            a_i = a[i];
 1697            carry = 0 - a_i * a_i;
 1698            for (var j = i; j < l; j++) {
 1699                a_j = a[j];
 1700                product = 2 * (a_i * a_j) + r[i + j] + carry;
 1701                carry = Math.floor(product / base);
 1702                r[i + j] = product - carry * base;
 1703            }
 1704            r[i + l] = carry;
 1705        }
 1706        trim(r);
 1707        return r;
 1708    }
 1709
 1710    BigInteger.prototype.square = function () {
 1711        return new BigInteger(square(this.value), false);
 1712    };
 1713
 1714    SmallInteger.prototype.square = function () {
 1715        var value = this.value * this.value;
 1716        if (isPrecise(value)) return new SmallInteger(value);
 1717        return new BigInteger(square(smallToArray(Math.abs(this.value))), false);
 1718    };
 1719
 1720    NativeBigInt.prototype.square = function (v) {
 1721        return new NativeBigInt(this.value * this.value);
 1722    }
 1723
 1724    function divMod1(a, b) { // Left over from previous version. Performs faster than divMod2 on smaller input sizes.
 1725        var a_l = a.length,
 1726            b_l = b.length,
 1727            base = BASE,
 1728            result = createArray(b.length),
 1729            divisorMostSignificantDigit = b[b_l - 1],
 1730            // normalization
 1731            lambda = Math.ceil(base / (2 * divisorMostSignificantDigit)),
 1732            remainder = multiplySmall(a, lambda),
 1733            divisor = multiplySmall(b, lambda),
 1734            quotientDigit, shift, carry, borrow, i, l, q;
 1735        if (remainder.length <= a_l) remainder.push(0);
 1736        divisor.push(0);
 1737        divisorMostSignificantDigit = divisor[b_l - 1];
 1738        for (shift = a_l - b_l; shift >= 0; shift--) {
 1739            quotientDigit = base - 1;
 1740            if (remainder[shift + b_l] !== divisorMostSignificantDigit) {
 1741                quotientDigit = Math.floor((remainder[shift + b_l] * base + remainder[shift + b_l - 1]) / divisorMostSignificantDigit);
 1742            }
 1743            // quotientDigit <= base - 1
 1744            carry = 0;
 1745            borrow = 0;
 1746            l = divisor.length;
 1747            for (i = 0; i < l; i++) {
 1748                carry += quotientDigit * divisor[i];
 1749                q = Math.floor(carry / base);
 1750                borrow += remainder[shift + i] - (carry - q * base);
 1751                carry = q;
 1752                if (borrow < 0) {
 1753                    remainder[shift + i] = borrow + base;
 1754                    borrow = -1;
 1755                } else {
 1756                    remainder[shift + i] = borrow;
 1757                    borrow = 0;
 1758                }
 1759            }
 1760            while (borrow !== 0) {
 1761                quotientDigit -= 1;
 1762                carry = 0;
 1763                for (i = 0; i < l; i++) {
 1764                    carry += remainder[shift + i] - base + divisor[i];
 1765                    if (carry < 0) {
 1766                        remainder[shift + i] = carry + base;
 1767                        carry = 0;
 1768                    } else {
 1769                        remainder[shift + i] = carry;
 1770                        carry = 1;
 1771                    }
 1772                }
 1773                borrow += carry;
 1774            }
 1775            result[shift] = quotientDigit;
 1776        }
 1777        // denormalization
 1778        remainder = divModSmall(remainder, lambda)[0];
 1779        return [arrayToSmall(result), arrayToSmall(remainder)];
 1780    }
 1781
 1782    function divMod2(a, b) { // Implementation idea shamelessly stolen from Silent Matt's library http://silentmatt.com/biginteger/
 1783        // Performs faster than divMod1 on larger input sizes.
 1784        var a_l = a.length,
 1785            b_l = b.length,
 1786            result = [],
 1787            part = [],
 1788            base = BASE,
 1789            guess, xlen, highx, highy, check;
 1790        while (a_l) {
 1791            part.unshift(a[--a_l]);
 1792            trim(part);
 1793            if (compareAbs(part, b) < 0) {
 1794                result.push(0);
 1795                continue;
 1796            }
 1797            xlen = part.length;
 1798            highx = part[xlen - 1] * base + part[xlen - 2];
 1799            highy = b[b_l - 1] * base + b[b_l - 2];
 1800            if (xlen > b_l) {
 1801                highx = (highx + 1) * base;
 1802            }
 1803            guess = Math.ceil(highx / highy);
 1804            do {
 1805                check = multiplySmall(b, guess);
 1806                if (compareAbs(check, part) <= 0) break;
 1807                guess--;
 1808            } while (guess);
 1809            result.push(guess);
 1810            part = subtract(part, check);
 1811        }
 1812        result.reverse();
 1813        return [arrayToSmall(result), arrayToSmall(part)];
 1814    }
 1815
 1816    function divModSmall(value, lambda) {
 1817        var length = value.length,
 1818            quotient = createArray(length),
 1819            base = BASE,
 1820            i, q, remainder, divisor;
 1821        remainder = 0;
 1822        for (i = length - 1; i >= 0; --i) {
 1823            divisor = remainder * base + value[i];
 1824            q = truncate(divisor / lambda);
 1825            remainder = divisor - q * lambda;
 1826            quotient[i] = q | 0;
 1827        }
 1828        return [quotient, remainder | 0];
 1829    }
 1830
 1831    function divModAny(self, v) {
 1832        var value, n = parseValue(v);
 1833        if (supportsNativeBigInt) {
 1834            return [new NativeBigInt(self.value / n.value), new NativeBigInt(self.value % n.value)];
 1835        }
 1836        var a = self.value, b = n.value;
 1837        var quotient;
 1838        if (b === 0) throw new Error("Cannot divide by zero");
 1839        if (self.isSmall) {
 1840            if (n.isSmall) {
 1841                return [new SmallInteger(truncate(a / b)), new SmallInteger(a % b)];
 1842            }
 1843            return [Integer[0], self];
 1844        }
 1845        if (n.isSmall) {
 1846            if (b === 1) return [self, Integer[0]];
 1847            if (b == -1) return [self.negate(), Integer[0]];
 1848            var abs = Math.abs(b);
 1849            if (abs < BASE) {
 1850                value = divModSmall(a, abs);
 1851                quotient = arrayToSmall(value[0]);
 1852                var remainder = value[1];
 1853                if (self.sign) remainder = -remainder;
 1854                if (typeof quotient === "number") {
 1855                    if (self.sign !== n.sign) quotient = -quotient;
 1856                    return [new SmallInteger(quotient), new SmallInteger(remainder)];
 1857                }
 1858                return [new BigInteger(quotient, self.sign !== n.sign), new SmallInteger(remainder)];
 1859            }
 1860            b = smallToArray(abs);
 1861        }
 1862        var comparison = compareAbs(a, b);
 1863        if (comparison === -1) return [Integer[0], self];
 1864        if (comparison === 0) return [Integer[self.sign === n.sign ? 1 : -1], Integer[0]];
 1865
 1866        // divMod1 is faster on smaller input sizes
 1867        if (a.length + b.length <= 200)
 1868            value = divMod1(a, b);
 1869        else value = divMod2(a, b);
 1870
 1871        quotient = value[0];
 1872        var qSign = self.sign !== n.sign,
 1873            mod = value[1],
 1874            mSign = self.sign;
 1875        if (typeof quotient === "number") {
 1876            if (qSign) quotient = -quotient;
 1877            quotient = new SmallInteger(quotient);
 1878        } else quotient = new BigInteger(quotient, qSign);
 1879        if (typeof mod === "number") {
 1880            if (mSign) mod = -mod;
 1881            mod = new SmallInteger(mod);
 1882        } else mod = new BigInteger(mod, mSign);
 1883        return [quotient, mod];
 1884    }
 1885
 1886    BigInteger.prototype.divmod = function (v) {
 1887        var result = divModAny(this, v);
 1888        return {
 1889            quotient: result[0],
 1890            remainder: result[1]
 1891        };
 1892    };
 1893    NativeBigInt.prototype.divmod = SmallInteger.prototype.divmod = BigInteger.prototype.divmod;
 1894
 1895
 1896    BigInteger.prototype.divide = function (v) {
 1897        return divModAny(this, v)[0];
 1898    };
 1899    NativeBigInt.prototype.over = NativeBigInt.prototype.divide = function (v) {
 1900        return new NativeBigInt(this.value / parseValue(v).value);
 1901    };
 1902    SmallInteger.prototype.over = SmallInteger.prototype.divide = BigInteger.prototype.over = BigInteger.prototype.divide;
 1903
 1904    BigInteger.prototype.mod = function (v) {
 1905        return divModAny(this, v)[1];
 1906    };
 1907    NativeBigInt.prototype.mod = NativeBigInt.prototype.remainder = function (v) {
 1908        return new NativeBigInt(this.value % parseValue(v).value);
 1909    };
 1910    SmallInteger.prototype.remainder = SmallInteger.prototype.mod = BigInteger.prototype.remainder = BigInteger.prototype.mod;
 1911
 1912    BigInteger.prototype.pow = function (v) {
 1913        var n = parseValue(v),
 1914            a = this.value,
 1915            b = n.value,
 1916            value, x, y;
 1917        if (b === 0) return Integer[1];
 1918        if (a === 0) return Integer[0];
 1919        if (a === 1) return Integer[1];
 1920        if (a === -1) return n.isEven() ? Integer[1] : Integer[-1];
 1921        if (n.sign) {
 1922            return Integer[0];
 1923        }
 1924        if (!n.isSmall) throw new Error("The exponent " + n.toString() + " is too large.");
 1925        if (this.isSmall) {
 1926            if (isPrecise(value = Math.pow(a, b)))
 1927                return new SmallInteger(truncate(value));
 1928        }
 1929        x = this;
 1930        y = Integer[1];
 1931        while (true) {
 1932            if (b & 1 === 1) {
 1933                y = y.times(x);
 1934                --b;
 1935            }
 1936            if (b === 0) break;
 1937            b /= 2;
 1938            x = x.square();
 1939        }
 1940        return y;
 1941    };
 1942    SmallInteger.prototype.pow = BigInteger.prototype.pow;
 1943
 1944    NativeBigInt.prototype.pow = function (v) {
 1945        var n = parseValue(v);
 1946        var a = this.value, b = n.value;
 1947        var _0 = BigInt(0), _1 = BigInt(1), _2 = BigInt(2);
 1948        if (b === _0) return Integer[1];
 1949        if (a === _0) return Integer[0];
 1950        if (a === _1) return Integer[1];
 1951        if (a === BigInt(-1)) return n.isEven() ? Integer[1] : Integer[-1];
 1952        if (n.isNegative()) return new NativeBigInt(_0);
 1953        var x = this;
 1954        var y = Integer[1];
 1955        while (true) {
 1956            if ((b & _1) === _1) {
 1957                y = y.times(x);
 1958                --b;
 1959            }
 1960            if (b === _0) break;
 1961            b /= _2;
 1962            x = x.square();
 1963        }
 1964        return y;
 1965    }
 1966
 1967    BigInteger.prototype.modPow = function (exp, mod) {
 1968        exp = parseValue(exp);
 1969        mod = parseValue(mod);
 1970        if (mod.isZero()) throw new Error("Cannot take modPow with modulus 0");
 1971        var r = Integer[1],
 1972            base = this.mod(mod);
 1973        if (exp.isNegative()) {
 1974            exp = exp.multiply(Integer[-1]);
 1975            base = base.modInv(mod);
 1976        }
 1977        while (exp.isPositive()) {
 1978            if (base.isZero()) return Integer[0];
 1979            if (exp.isOdd()) r = r.multiply(base).mod(mod);
 1980            exp = exp.divide(2);
 1981            base = base.square().mod(mod);
 1982        }
 1983        return r;
 1984    };
 1985    NativeBigInt.prototype.modPow = SmallInteger.prototype.modPow = BigInteger.prototype.modPow;
 1986
 1987    function compareAbs(a, b) {
 1988        if (a.length !== b.length) {
 1989            return a.length > b.length ? 1 : -1;
 1990        }
 1991        for (var i = a.length - 1; i >= 0; i--) {
 1992            if (a[i] !== b[i]) return a[i] > b[i] ? 1 : -1;
 1993        }
 1994        return 0;
 1995    }
 1996
 1997    BigInteger.prototype.compareAbs = function (v) {
 1998        var n = parseValue(v),
 1999            a = this.value,
 2000            b = n.value;
 2001        if (n.isSmall) return 1;
 2002        return compareAbs(a, b);
 2003    };
 2004    SmallInteger.prototype.compareAbs = function (v) {
 2005        var n = parseValue(v),
 2006            a = Math.abs(this.value),
 2007            b = n.value;
 2008        if (n.isSmall) {
 2009            b = Math.abs(b);
 2010            return a === b ? 0 : a > b ? 1 : -1;
 2011        }
 2012        return -1;
 2013    };
 2014    NativeBigInt.prototype.compareAbs = function (v) {
 2015        var a = this.value;
 2016        var b = parseValue(v).value;
 2017        a = a >= 0 ? a : -a;
 2018        b = b >= 0 ? b : -b;
 2019        return a === b ? 0 : a > b ? 1 : -1;
 2020    }
 2021
 2022    BigInteger.prototype.compare = function (v) {
 2023        // See discussion about comparison with Infinity:
 2024        // https://github.com/peterolson/BigInteger.js/issues/61
 2025        if (v === Infinity) {
 2026            return -1;
 2027        }
 2028        if (v === -Infinity) {
 2029            return 1;
 2030        }
 2031
 2032        var n = parseValue(v),
 2033            a = this.value,
 2034            b = n.value;
 2035        if (this.sign !== n.sign) {
 2036            return n.sign ? 1 : -1;
 2037        }
 2038        if (n.isSmall) {
 2039            return this.sign ? -1 : 1;
 2040        }
 2041        return compareAbs(a, b) * (this.sign ? -1 : 1);
 2042    };
 2043    BigInteger.prototype.compareTo = BigInteger.prototype.compare;
 2044
 2045    SmallInteger.prototype.compare = function (v) {
 2046        if (v === Infinity) {
 2047            return -1;
 2048        }
 2049        if (v === -Infinity) {
 2050            return 1;
 2051        }
 2052
 2053        var n = parseValue(v),
 2054            a = this.value,
 2055            b = n.value;
 2056        if (n.isSmall) {
 2057            return a == b ? 0 : a > b ? 1 : -1;
 2058        }
 2059        if (a < 0 !== n.sign) {
 2060            return a < 0 ? -1 : 1;
 2061        }
 2062        return a < 0 ? 1 : -1;
 2063    };
 2064    SmallInteger.prototype.compareTo = SmallInteger.prototype.compare;
 2065
 2066    NativeBigInt.prototype.compare = function (v) {
 2067        if (v === Infinity) {
 2068            return -1;
 2069        }
 2070        if (v === -Infinity) {
 2071            return 1;
 2072        }
 2073        var a = this.value;
 2074        var b = parseValue(v).value;
 2075        return a === b ? 0 : a > b ? 1 : -1;
 2076    }
 2077    NativeBigInt.prototype.compareTo = NativeBigInt.prototype.compare;
 2078
 2079    BigInteger.prototype.equals = function (v) {
 2080        return this.compare(v) === 0;
 2081    };
 2082    NativeBigInt.prototype.eq = NativeBigInt.prototype.equals = SmallInteger.prototype.eq = SmallInteger.prototype.equals = BigInteger.prototype.eq = BigInteger.prototype.equals;
 2083
 2084    BigInteger.prototype.notEquals = function (v) {
 2085        return this.compare(v) !== 0;
 2086    };
 2087    NativeBigInt.prototype.neq = NativeBigInt.prototype.notEquals = SmallInteger.prototype.neq = SmallInteger.prototype.notEquals = BigInteger.prototype.neq = BigInteger.prototype.notEquals;
 2088
 2089    BigInteger.prototype.greater = function (v) {
 2090        return this.compare(v) > 0;
 2091    };
 2092    NativeBigInt.prototype.gt = NativeBigInt.prototype.greater = SmallInteger.prototype.gt = SmallInteger.prototype.greater = BigInteger.prototype.gt = BigInteger.prototype.greater;
 2093
 2094    BigInteger.prototype.lesser = function (v) {
 2095        return this.compare(v) < 0;
 2096    };
 2097    NativeBigInt.prototype.lt = NativeBigInt.prototype.lesser = SmallInteger.prototype.lt = SmallInteger.prototype.lesser = BigInteger.prototype.lt = BigInteger.prototype.lesser;
 2098
 2099    BigInteger.prototype.greaterOrEquals = function (v) {
 2100        return this.compare(v) >= 0;
 2101    };
 2102    NativeBigInt.prototype.geq = NativeBigInt.prototype.greaterOrEquals = SmallInteger.prototype.geq = SmallInteger.prototype.greaterOrEquals = BigInteger.prototype.geq = BigInteger.prototype.greaterOrEquals;
 2103
 2104    BigInteger.prototype.lesserOrEquals = function (v) {
 2105        return this.compare(v) <= 0;
 2106    };
 2107    NativeBigInt.prototype.leq = NativeBigInt.prototype.lesserOrEquals = SmallInteger.prototype.leq = SmallInteger.prototype.lesserOrEquals = BigInteger.prototype.leq = BigInteger.prototype.lesserOrEquals;
 2108
 2109    BigInteger.prototype.isEven = function () {
 2110        return (this.value[0] & 1) === 0;
 2111    };
 2112    SmallInteger.prototype.isEven = function () {
 2113        return (this.value & 1) === 0;
 2114    };
 2115    NativeBigInt.prototype.isEven = function () {
 2116        return (this.value & BigInt(1)) === BigInt(0);
 2117    }
 2118
 2119    BigInteger.prototype.isOdd = function () {
 2120        return (this.value[0] & 1) === 1;
 2121    };
 2122    SmallInteger.prototype.isOdd = function () {
 2123        return (this.value & 1) === 1;
 2124    };
 2125    NativeBigInt.prototype.isOdd = function () {
 2126        return (this.value & BigInt(1)) === BigInt(1);
 2127    }
 2128
 2129    BigInteger.prototype.isPositive = function () {
 2130        return !this.sign;
 2131    };
 2132    SmallInteger.prototype.isPositive = function () {
 2133        return this.value > 0;
 2134    };
 2135    NativeBigInt.prototype.isPositive = SmallInteger.prototype.isPositive;
 2136
 2137    BigInteger.prototype.isNegative = function () {
 2138        return this.sign;
 2139    };
 2140    SmallInteger.prototype.isNegative = function () {
 2141        return this.value < 0;
 2142    };
 2143    NativeBigInt.prototype.isNegative = SmallInteger.prototype.isNegative;
 2144
 2145    BigInteger.prototype.isUnit = function () {
 2146        return false;
 2147    };
 2148    SmallInteger.prototype.isUnit = function () {
 2149        return Math.abs(this.value) === 1;
 2150    };
 2151    NativeBigInt.prototype.isUnit = function () {
 2152        return this.abs().value === BigInt(1);
 2153    }
 2154
 2155    BigInteger.prototype.isZero = function () {
 2156        return false;
 2157    };
 2158    SmallInteger.prototype.isZero = function () {
 2159        return this.value === 0;
 2160    };
 2161    NativeBigInt.prototype.isZero = function () {
 2162        return this.value === BigInt(0);
 2163    }
 2164
 2165    BigInteger.prototype.isDivisibleBy = function (v) {
 2166        var n = parseValue(v);
 2167        if (n.isZero()) return false;
 2168        if (n.isUnit()) return true;
 2169        if (n.compareAbs(2) === 0) return this.isEven();
 2170        return this.mod(n).isZero();
 2171    };
 2172    NativeBigInt.prototype.isDivisibleBy = SmallInteger.prototype.isDivisibleBy = BigInteger.prototype.isDivisibleBy;
 2173
 2174    function isBasicPrime(v) {
 2175        var n = v.abs();
 2176        if (n.isUnit()) return false;
 2177        if (n.equals(2) || n.equals(3) || n.equals(5)) return true;
 2178        if (n.isEven() || n.isDivisibleBy(3) || n.isDivisibleBy(5)) return false;
 2179        if (n.lesser(49)) return true;
 2180        // we don't know if it's prime: let the other functions figure it out
 2181    }
 2182
 2183    function millerRabinTest(n, a) {
 2184        var nPrev = n.prev(),
 2185            b = nPrev,
 2186            r = 0,
 2187            d, t, i, x;
 2188        while (b.isEven()) b = b.divide(2), r++;
 2189        next: for (i = 0; i < a.length; i++) {
 2190            if (n.lesser(a[i])) continue;
 2191            x = bigInt(a[i]).modPow(b, n);
 2192            if (x.isUnit() || x.equals(nPrev)) continue;
 2193            for (d = r - 1; d != 0; d--) {
 2194                x = x.square().mod(n);
 2195                if (x.isUnit()) return false;
 2196                if (x.equals(nPrev)) continue next;
 2197            }
 2198            return false;
 2199        }
 2200        return true;
 2201    }
 2202
 2203    // Set "strict" to true to force GRH-supported lower bound of 2*log(N)^2
 2204    BigInteger.prototype.isPrime = function (strict) {
 2205        var isPrime = isBasicPrime(this);
 2206        if (isPrime !== undefined) return isPrime;
 2207        var n = this.abs();
 2208        var bits = n.bitLength();
 2209        if (bits <= 64)
 2210            return millerRabinTest(n, [2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37]);
 2211        var logN = Math.log(2) * bits.toJSNumber();
 2212        var t = Math.ceil((strict === true) ? (2 * Math.pow(logN, 2)) : logN);
 2213        for (var a = [], i = 0; i < t; i++) {
 2214            a.push(bigInt(i + 2));
 2215        }
 2216        return millerRabinTest(n, a);
 2217    };
 2218    NativeBigInt.prototype.isPrime = SmallInteger.prototype.isPrime = BigInteger.prototype.isPrime;
 2219
 2220    BigInteger.prototype.isProbablePrime = function (iterations, rng) {
 2221        var isPrime = isBasicPrime(this);
 2222        if (isPrime !== undefined) return isPrime;
 2223        var n = this.abs();
 2224        var t = iterations === undefined ? 5 : iterations;
 2225        for (var a = [], i = 0; i < t; i++) {
 2226            a.push(bigInt.randBetween(2, n.minus(2), rng));
 2227        }
 2228        return millerRabinTest(n, a);
 2229    };
 2230    NativeBigInt.prototype.isProbablePrime = SmallInteger.prototype.isProbablePrime = BigInteger.prototype.isProbablePrime;
 2231
 2232    BigInteger.prototype.modInv = function (n) {
 2233        var t = bigInt.zero, newT = bigInt.one, r = parseValue(n), newR = this.abs(), q, lastT, lastR;
 2234        while (!newR.isZero()) {
 2235            q = r.divide(newR);
 2236            lastT = t;
 2237            lastR = r;
 2238            t = newT;
 2239            r = newR;
 2240            newT = lastT.subtract(q.multiply(newT));
 2241            newR = lastR.subtract(q.multiply(newR));
 2242        }
 2243        if (!r.isUnit()) throw new Error(this.toString() + " and " + n.toString() + " are not co-prime");
 2244        if (t.compare(0) === -1) {
 2245            t = t.add(n);
 2246        }
 2247        if (this.isNegative()) {
 2248            return t.negate();
 2249        }
 2250        return t;
 2251    };
 2252
 2253    NativeBigInt.prototype.modInv = SmallInteger.prototype.modInv = BigInteger.prototype.modInv;
 2254
 2255    BigInteger.prototype.next = function () {
 2256        var value = this.value;
 2257        if (this.sign) {
 2258            return subtractSmall(value, 1, this.sign);
 2259        }
 2260        return new BigInteger(addSmall(value, 1), this.sign);
 2261    };
 2262    SmallInteger.prototype.next = function () {
 2263        var value = this.value;
 2264        if (value + 1 < MAX_INT) return new SmallInteger(value + 1);
 2265        return new BigInteger(MAX_INT_ARR, false);
 2266    };
 2267    NativeBigInt.prototype.next = function () {
 2268        return new NativeBigInt(this.value + BigInt(1));
 2269    }
 2270
 2271    BigInteger.prototype.prev = function () {
 2272        var value = this.value;
 2273        if (this.sign) {
 2274            return new BigInteger(addSmall(value, 1), true);
 2275        }
 2276        return subtractSmall(value, 1, this.sign);
 2277    };
 2278    SmallInteger.prototype.prev = function () {
 2279        var value = this.value;
 2280        if (value - 1 > -MAX_INT) return new SmallInteger(value - 1);
 2281        return new BigInteger(MAX_INT_ARR, true);
 2282    };
 2283    NativeBigInt.prototype.prev = function () {
 2284        return new NativeBigInt(this.value - BigInt(1));
 2285    }
 2286
 2287    var powersOfTwo = [1];
 2288    while (2 * powersOfTwo[powersOfTwo.length - 1] <= BASE) powersOfTwo.push(2 * powersOfTwo[powersOfTwo.length - 1]);
 2289    var powers2Length = powersOfTwo.length, highestPower2 = powersOfTwo[powers2Length - 1];
 2290
 2291    function shift_isSmall(n) {
 2292        return Math.abs(n) <= BASE;
 2293    }
 2294
 2295    BigInteger.prototype.shiftLeft = function (v) {
 2296        var n = parseValue(v).toJSNumber();
 2297        if (!shift_isSmall(n)) {
 2298            throw new Error(String(n) + " is too large for shifting.");
 2299        }
 2300        if (n < 0) return this.shiftRight(-n);
 2301        var result = this;
 2302        if (result.isZero()) return result;
 2303        while (n >= powers2Length) {
 2304            result = result.multiply(highestPower2);
 2305            n -= powers2Length - 1;
 2306        }
 2307        return result.multiply(powersOfTwo[n]);
 2308    };
 2309    NativeBigInt.prototype.shiftLeft = SmallInteger.prototype.shiftLeft = BigInteger.prototype.shiftLeft;
 2310
 2311    BigInteger.prototype.shiftRight = function (v) {
 2312        var remQuo;
 2313        var n = parseValue(v).toJSNumber();
 2314        if (!shift_isSmall(n)) {
 2315            throw new Error(String(n) + " is too large for shifting.");
 2316        }
 2317        if (n < 0) return this.shiftLeft(-n);
 2318        var result = this;
 2319        while (n >= powers2Length) {
 2320            if (result.isZero() || (result.isNegative() && result.isUnit())) return result;
 2321            remQuo = divModAny(result, highestPower2);
 2322            result = remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
 2323            n -= powers2Length - 1;
 2324        }
 2325        remQuo = divModAny(result, powersOfTwo[n]);
 2326        return remQuo[1].isNegative() ? remQuo[0].prev() : remQuo[0];
 2327    };
 2328    NativeBigInt.prototype.shiftRight = SmallInteger.prototype.shiftRight = BigInteger.prototype.shiftRight;
 2329
 2330    function bitwise(x, y, fn) {
 2331        y = parseValue(y);
 2332        var xSign = x.isNegative(), ySign = y.isNegative();
 2333        var xRem = xSign ? x.not() : x,
 2334            yRem = ySign ? y.not() : y;
 2335        var xDigit = 0, yDigit = 0;
 2336        var xDivMod = null, yDivMod = null;
 2337        var result = [];
 2338        while (!xRem.isZero() || !yRem.isZero()) {
 2339            xDivMod = divModAny(xRem, highestPower2);
 2340            xDigit = xDivMod[1].toJSNumber();
 2341            if (xSign) {
 2342                xDigit = highestPower2 - 1 - xDigit; // two's complement for negative numbers
 2343            }
 2344
 2345            yDivMod = divModAny(yRem, highestPower2);
 2346            yDigit = yDivMod[1].toJSNumber();
 2347            if (ySign) {
 2348                yDigit = highestPower2 - 1 - yDigit; // two's complement for negative numbers
 2349            }
 2350
 2351            xRem = xDivMod[0];
 2352            yRem = yDivMod[0];
 2353            result.push(fn(xDigit, yDigit));
 2354        }
 2355        var sum = fn(xSign ? 1 : 0, ySign ? 1 : 0) !== 0 ? bigInt(-1) : bigInt(0);
 2356        for (var i = result.length - 1; i >= 0; i -= 1) {
 2357            sum = sum.multiply(highestPower2).add(bigInt(result[i]));
 2358        }
 2359        return sum;
 2360    }
 2361
 2362    BigInteger.prototype.not = function () {
 2363        return this.negate().prev();
 2364    };
 2365    NativeBigInt.prototype.not = SmallInteger.prototype.not = BigInteger.prototype.not;
 2366
 2367    BigInteger.prototype.and = function (n) {
 2368        return bitwise(this, n, function (a, b) { return a & b; });
 2369    };
 2370    NativeBigInt.prototype.and = SmallInteger.prototype.and = BigInteger.prototype.and;
 2371
 2372    BigInteger.prototype.or = function (n) {
 2373        return bitwise(this, n, function (a, b) { return a | b; });
 2374    };
 2375    NativeBigInt.prototype.or = SmallInteger.prototype.or = BigInteger.prototype.or;
 2376
 2377    BigInteger.prototype.xor = function (n) {
 2378        return bitwise(this, n, function (a, b) { return a ^ b; });
 2379    };
 2380    NativeBigInt.prototype.xor = SmallInteger.prototype.xor = BigInteger.prototype.xor;
 2381
 2382    var LOBMASK_I = 1 << 30, LOBMASK_BI = (BASE & -BASE) * (BASE & -BASE) | LOBMASK_I;
 2383    function roughLOB(n) { // get lowestOneBit (rough)
 2384        // SmallInteger: return Min(lowestOneBit(n), 1 << 30)
 2385        // BigInteger: return Min(lowestOneBit(n), 1 << 14) [BASE=1e7]
 2386        var v = n.value,
 2387            x = typeof v === "number" ? v | LOBMASK_I :
 2388                typeof v === "bigint" ? v | BigInt(LOBMASK_I) :
 2389                    v[0] + v[1] * BASE | LOBMASK_BI;
 2390        return x & -x;
 2391    }
 2392
 2393    function integerLogarithm(value, base) {
 2394        if (base.compareTo(value) <= 0) {
 2395            var tmp = integerLogarithm(value, base.square(base));
 2396            var p = tmp.p;
 2397            var e = tmp.e;
 2398            var t = p.multiply(base);
 2399            return t.compareTo(value) <= 0 ? { p: t, e: e * 2 + 1 } : { p: p, e: e * 2 };
 2400        }
 2401        return { p: bigInt(1), e: 0 };
 2402    }
 2403
 2404    BigInteger.prototype.bitLength = function () {
 2405        var n = this;
 2406        if (n.compareTo(bigInt(0)) < 0) {
 2407            n = n.negate().subtract(bigInt(1));
 2408        }
 2409        if (n.compareTo(bigInt(0)) === 0) {
 2410            return bigInt(0);
 2411        }
 2412        return bigInt(integerLogarithm(n, bigInt(2)).e).add(bigInt(1));
 2413    }
 2414    NativeBigInt.prototype.bitLength = SmallInteger.prototype.bitLength = BigInteger.prototype.bitLength;
 2415
 2416    function max(a, b) {
 2417        a = parseValue(a);
 2418        b = parseValue(b);
 2419        return a.greater(b) ? a : b;
 2420    }
 2421    function min(a, b) {
 2422        a = parseValue(a);
 2423        b = parseValue(b);
 2424        return a.lesser(b) ? a : b;
 2425    }
 2426    function gcd(a, b) {
 2427        a = parseValue(a).abs();
 2428        b = parseValue(b).abs();
 2429        if (a.equals(b)) return a;
 2430        if (a.isZero()) return b;
 2431        if (b.isZero()) return a;
 2432        var c = Integer[1], d, t;
 2433        while (a.isEven() && b.isEven()) {
 2434            d = min(roughLOB(a), roughLOB(b));
 2435            a = a.divide(d);
 2436            b = b.divide(d);
 2437            c = c.multiply(d);
 2438        }
 2439        while (a.isEven()) {
 2440            a = a.divide(roughLOB(a));
 2441        }
 2442        do {
 2443            while (b.isEven()) {
 2444                b = b.divide(roughLOB(b));
 2445            }
 2446            if (a.greater(b)) {
 2447                t = b; b = a; a = t;
 2448            }
 2449            b = b.subtract(a);
 2450        } while (!b.isZero());
 2451        return c.isUnit() ? a : a.multiply(c);
 2452    }
 2453    function lcm(a, b) {
 2454        a = parseValue(a).abs();
 2455        b = parseValue(b).abs();
 2456        return a.divide(gcd(a, b)).multiply(b);
 2457    }
 2458    function randBetween(a, b, rng) {
 2459        a = parseValue(a);
 2460        b = parseValue(b);
 2461        var usedRNG = rng || Math.random;
 2462        var low = min(a, b), high = max(a, b);
 2463        var range = high.subtract(low).add(1);
 2464        if (range.isSmall) return low.add(Math.floor(usedRNG() * range));
 2465        var digits = toBase(range, BASE).value;
 2466        var result = [], restricted = true;
 2467        for (var i = 0; i < digits.length; i++) {
 2468            var top = restricted ? digits[i] : BASE;
 2469            var digit = truncate(usedRNG() * top);
 2470            result.push(digit);
 2471            if (digit < top) restricted = false;
 2472        }
 2473        return low.add(Integer.fromArray(result, BASE, false));
 2474    }
 2475
 2476    var parseBase = function (text, base, alphabet, caseSensitive) {
 2477        alphabet = alphabet || DEFAULT_ALPHABET;
 2478        text = String(text);
 2479        if (!caseSensitive) {
 2480            text = text.toLowerCase();
 2481            alphabet = alphabet.toLowerCase();
 2482        }
 2483        var length = text.length;
 2484        var i;
 2485        var absBase = Math.abs(base);
 2486        var alphabetValues = {};
 2487        for (i = 0; i < alphabet.length; i++) {
 2488            alphabetValues[alphabet[i]] = i;
 2489        }
 2490        for (i = 0; i < length; i++) {
 2491            var c = text[i];
 2492            if (c === "-") continue;
 2493            if (c in alphabetValues) {
 2494                if (alphabetValues[c] >= absBase) {
 2495                    if (c === "1" && absBase === 1) continue;
 2496                    throw new Error(c + " is not a valid digit in base " + base + ".");
 2497                }
 2498            }
 2499        }
 2500        base = parseValue(base);
 2501        var digits = [];
 2502        var isNegative = text[0] === "-";
 2503        for (i = isNegative ? 1 : 0; i < text.length; i++) {
 2504            var c = text[i];
 2505            if (c in alphabetValues) digits.push(parseValue(alphabetValues[c]));
 2506            else if (c === "<") {
 2507                var start = i;
 2508                do { i++; } while (text[i] !== ">" && i < text.length);
 2509                digits.push(parseValue(text.slice(start + 1, i)));
 2510            }
 2511            else throw new Error(c + " is not a valid character");
 2512        }
 2513        return parseBaseFromArray(digits, base, isNegative);
 2514    };
 2515
 2516    function parseBaseFromArray(digits, base, isNegative) {
 2517        var val = Integer[0], pow = Integer[1], i;
 2518        for (i = digits.length - 1; i >= 0; i--) {
 2519            val = val.add(digits[i].times(pow));
 2520            pow = pow.times(base);
 2521        }
 2522        return isNegative ? val.negate() : val;
 2523    }
 2524
 2525    function stringify(digit, alphabet) {
 2526        alphabet = alphabet || DEFAULT_ALPHABET;
 2527        if (digit < alphabet.length) {
 2528            return alphabet[digit];
 2529        }
 2530        return "<" + digit + ">";
 2531    }
 2532
 2533    function toBase(n, base) {
 2534        base = bigInt(base);
 2535        if (base.isZero()) {
 2536            if (n.isZero()) return { value: [0], isNegative: false };
 2537            throw new Error("Cannot convert nonzero numbers to base 0.");
 2538        }
 2539        if (base.equals(-1)) {
 2540            if (n.isZero()) return { value: [0], isNegative: false };
 2541            if (n.isNegative())
 2542                return {
 2543                    value: [].concat.apply([], Array.apply(null, Array(-n.toJSNumber()))
 2544                        .map(Array.prototype.valueOf, [1, 0])
 2545                    ),
 2546                    isNegative: false
 2547                };
 2548
 2549            var arr = Array.apply(null, Array(n.toJSNumber() - 1))
 2550                .map(Array.prototype.valueOf, [0, 1]);
 2551            arr.unshift([1]);
 2552            return {
 2553                value: [].concat.apply([], arr),
 2554                isNegative: false
 2555            };
 2556        }
 2557
 2558        var neg = false;
 2559        if (n.isNegative() && base.isPositive()) {
 2560            neg = true;
 2561            n = n.abs();
 2562        }
 2563        if (base.isUnit()) {
 2564            if (n.isZero()) return { value: [0], isNegative: false };
 2565
 2566            return {
 2567                value: Array.apply(null, Array(n.toJSNumber()))
 2568                    .map(Number.prototype.valueOf, 1),
 2569                isNegative: neg
 2570            };
 2571        }
 2572        var out = [];
 2573        var left = n, divmod;
 2574        while (left.isNegative() || left.compareAbs(base) >= 0) {
 2575            divmod = left.divmod(base);
 2576            left = divmod.quotient;
 2577            var digit = divmod.remainder;
 2578            if (digit.isNegative()) {
 2579                digit = base.minus(digit).abs();
 2580                left = left.next();
 2581            }
 2582            out.push(digit.toJSNumber());
 2583        }
 2584        out.push(left.toJSNumber());
 2585        return { value: out.reverse(), isNegative: neg };
 2586    }
 2587
 2588    function toBaseString(n, base, alphabet) {
 2589        var arr = toBase(n, base);
 2590        return (arr.isNegative ? "-" : "") + arr.value.map(function (x) {
 2591            return stringify(x, alphabet);
 2592        }).join('');
 2593    }
 2594
 2595    BigInteger.prototype.toArray = function (radix) {
 2596        return toBase(this, radix);
 2597    };
 2598
 2599    SmallInteger.prototype.toArray = function (radix) {
 2600        return toBase(this, radix);
 2601    };
 2602
 2603    NativeBigInt.prototype.toArray = function (radix) {
 2604        return toBase(this, radix);
 2605    };
 2606
 2607    BigInteger.prototype.toString = function (radix, alphabet) {
 2608        if (radix === undefined) radix = 10;
 2609        if (radix !== 10) return toBaseString(this, radix, alphabet);
 2610        var v = this.value, l = v.length, str = String(v[--l]), zeros = "0000000", digit;
 2611        while (--l >= 0) {
 2612            digit = String(v[l]);
 2613            str += zeros.slice(digit.length) + digit;
 2614        }
 2615        var sign = this.sign ? "-" : "";
 2616        return sign + str;
 2617    };
 2618
 2619    SmallInteger.prototype.toString = function (radix, alphabet) {
 2620        if (radix === undefined) radix = 10;
 2621        if (radix != 10) return toBaseString(this, radix, alphabet);
 2622        return String(this.value);
 2623    };
 2624
 2625    NativeBigInt.prototype.toString = SmallInteger.prototype.toString;
 2626
 2627    NativeBigInt.prototype.toJSON = BigInteger.prototype.toJSON = SmallInteger.prototype.toJSON = function () { return this.toString(); }
 2628
 2629    BigInteger.prototype.valueOf = function () {
 2630        return parseInt(this.toString(), 10);
 2631    };
 2632    BigInteger.prototype.toJSNumber = BigInteger.prototype.valueOf;
 2633
 2634    SmallInteger.prototype.valueOf = function () {
 2635        return this.value;
 2636    };
 2637    SmallInteger.prototype.toJSNumber = SmallInteger.prototype.valueOf;
 2638    NativeBigInt.prototype.valueOf = NativeBigInt.prototype.toJSNumber = function () {
 2639        return parseInt(this.toString(), 10);
 2640    }
 2641
 2642    function parseStringValue(v) {
 2643        if (isPrecise(+v)) {
 2644            var x = +v;
 2645            if (x === truncate(x))
 2646                return supportsNativeBigInt ? new NativeBigInt(BigInt(x)) : new SmallInteger(x);
 2647            throw new Error("Invalid integer: " + v);
 2648        }
 2649        var sign = v[0] === "-";
 2650        if (sign) v = v.slice(1);
 2651        var split = v.split(/e/i);
 2652        if (split.length > 2) throw new Error("Invalid integer: " + split.join("e"));
 2653        if (split.length === 2) {
 2654            var exp = split[1];
 2655            if (exp[0] === "+") exp = exp.slice(1);
 2656            exp = +exp;
 2657            if (exp !== truncate(exp) || !isPrecise(exp)) throw new Error("Invalid integer: " + exp + " is not a valid exponent.");
 2658            var text = split[0];
 2659            var decimalPlace = text.indexOf(".");
 2660            if (decimalPlace >= 0) {
 2661                exp -= text.length - decimalPlace - 1;
 2662                text = text.slice(0, decimalPlace) + text.slice(decimalPlace + 1);
 2663            }
 2664            if (exp < 0) throw new Error("Cannot include negative exponent part for integers");
 2665            text += (new Array(exp + 1)).join("0");
 2666            v = text;
 2667        }
 2668        var isValid = /^([0-9][0-9]*)$/.test(v);
 2669        if (!isValid) throw new Error("Invalid integer: " + v);
 2670        if (supportsNativeBigInt) {
 2671            return new NativeBigInt(BigInt(sign ? "-" + v : v));
 2672        }
 2673        var r = [], max = v.length, l = LOG_BASE, min = max - l;
 2674        while (max > 0) {
 2675            r.push(+v.slice(min, max));
 2676            min -= l;
 2677            if (min < 0) min = 0;
 2678            max -= l;
 2679        }
 2680        trim(r);
 2681        return new BigInteger(r, sign);
 2682    }
 2683
 2684    function parseNumberValue(v) {
 2685        if (supportsNativeBigInt) {
 2686            return new NativeBigInt(BigInt(v));
 2687        }
 2688        if (isPrecise(v)) {
 2689            if (v !== truncate(v)) throw new Error(v + " is not an integer.");
 2690            return new SmallInteger(v);
 2691        }
 2692        return parseStringValue(v.toString());
 2693    }
 2694
 2695    function parseValue(v) {
 2696        if (typeof v === "number") {
 2697            return parseNumberValue(v);
 2698        }
 2699        if (typeof v === "string") {
 2700            return parseStringValue(v);
 2701        }
 2702        if (typeof v === "bigint") {
 2703            return new NativeBigInt(v);
 2704        }
 2705        return v;
 2706    }
 2707    // Pre-define numbers in range [-999,999]
 2708    for (var i = 0; i < 1000; i++) {
 2709        Integer[i] = parseValue(i);
 2710        if (i > 0) Integer[-i] = parseValue(-i);
 2711    }
 2712    // Backwards compatibility
 2713    Integer.one = Integer[1];
 2714    Integer.zero = Integer[0];
 2715    Integer.minusOne = Integer[-1];
 2716    Integer.max = max;
 2717    Integer.min = min;
 2718    Integer.gcd = gcd;
 2719    Integer.lcm = lcm;
 2720    Integer.isInstance = function (x) { return x instanceof BigInteger || x instanceof SmallInteger || x instanceof NativeBigInt; };
 2721    Integer.randBetween = randBetween;
 2722
 2723    Integer.fromArray = function (digits, base, isNegative) {
 2724        return parseBaseFromArray(digits.map(parseValue), parseValue(base || 10), isNegative);
 2725    };
 2726
 2727    return Integer;
 2728})();
 2729
 2730// Node.js check
 2731if (typeof module !== "undefined" && module.hasOwnProperty("exports")) {
 2732    module.exports = bigInt;
 2733}
 2734
 2735//amd check
 2736if (typeof define === "function" && define.amd) {
 2737    define( function () {
 2738        return bigInt;
 2739    });
 2740}
 2741
 2742},{}],7:[function(require,module,exports){
 2743
 2744},{}],8:[function(require,module,exports){
 2745(function (Buffer){
 2746/*!
 2747 * The buffer module from node.js, for the browser.
 2748 *
 2749 * @author   Feross Aboukhadijeh <https://feross.org>
 2750 * @license  MIT
 2751 */
 2752/* eslint-disable no-proto */
 2753
 2754'use strict'
 2755
 2756var base64 = require('base64-js')
 2757var ieee754 = require('ieee754')
 2758
 2759exports.Buffer = Buffer
 2760exports.SlowBuffer = SlowBuffer
 2761exports.INSPECT_MAX_BYTES = 50
 2762
 2763var K_MAX_LENGTH = 0x7fffffff
 2764exports.kMaxLength = K_MAX_LENGTH
 2765
 2766/**
 2767 * If `Buffer.TYPED_ARRAY_SUPPORT`:
 2768 *   === true    Use Uint8Array implementation (fastest)
 2769 *   === false   Print warning and recommend using `buffer` v4.x which has an Object
 2770 *               implementation (most compatible, even IE6)
 2771 *
 2772 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
 2773 * Opera 11.6+, iOS 4.2+.
 2774 *
 2775 * We report that the browser does not support typed arrays if the are not subclassable
 2776 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
 2777 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
 2778 * for __proto__ and has a buggy typed array implementation.
 2779 */
 2780Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
 2781
 2782if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
 2783    typeof console.error === 'function') {
 2784  console.error(
 2785    'This browser lacks typed array (Uint8Array) support which is required by ' +
 2786    '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
 2787  )
 2788}
 2789
 2790function typedArraySupport () {
 2791  // Can typed array instances can be augmented?
 2792  try {
 2793    var arr = new Uint8Array(1)
 2794    arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
 2795    return arr.foo() === 42
 2796  } catch (e) {
 2797    return false
 2798  }
 2799}
 2800
 2801Object.defineProperty(Buffer.prototype, 'parent', {
 2802  enumerable: true,
 2803  get: function () {
 2804    if (!Buffer.isBuffer(this)) return undefined
 2805    return this.buffer
 2806  }
 2807})
 2808
 2809Object.defineProperty(Buffer.prototype, 'offset', {
 2810  enumerable: true,
 2811  get: function () {
 2812    if (!Buffer.isBuffer(this)) return undefined
 2813    return this.byteOffset
 2814  }
 2815})
 2816
 2817function createBuffer (length) {
 2818  if (length > K_MAX_LENGTH) {
 2819    throw new RangeError('The value "' + length + '" is invalid for option "size"')
 2820  }
 2821  // Return an augmented `Uint8Array` instance
 2822  var buf = new Uint8Array(length)
 2823  buf.__proto__ = Buffer.prototype
 2824  return buf
 2825}
 2826
 2827/**
 2828 * The Buffer constructor returns instances of `Uint8Array` that have their
 2829 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
 2830 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
 2831 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
 2832 * returns a single octet.
 2833 *
 2834 * The `Uint8Array` prototype remains unmodified.
 2835 */
 2836
 2837function Buffer (arg, encodingOrOffset, length) {
 2838  // Common case.
 2839  if (typeof arg === 'number') {
 2840    if (typeof encodingOrOffset === 'string') {
 2841      throw new TypeError(
 2842        'The "string" argument must be of type string. Received type number'
 2843      )
 2844    }
 2845    return allocUnsafe(arg)
 2846  }
 2847  return from(arg, encodingOrOffset, length)
 2848}
 2849
 2850// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
 2851if (typeof Symbol !== 'undefined' && Symbol.species != null &&
 2852    Buffer[Symbol.species] === Buffer) {
 2853  Object.defineProperty(Buffer, Symbol.species, {
 2854    value: null,
 2855    configurable: true,
 2856    enumerable: false,
 2857    writable: false
 2858  })
 2859}
 2860
 2861Buffer.poolSize = 8192 // not used by this implementation
 2862
 2863function from (value, encodingOrOffset, length) {
 2864  if (typeof value === 'string') {
 2865    return fromString(value, encodingOrOffset)
 2866  }
 2867
 2868  if (ArrayBuffer.isView(value)) {
 2869    return fromArrayLike(value)
 2870  }
 2871
 2872  if (value == null) {
 2873    throw TypeError(
 2874      'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
 2875      'or Array-like Object. Received type ' + (typeof value)
 2876    )
 2877  }
 2878
 2879  if (isInstance(value, ArrayBuffer) ||
 2880      (value && isInstance(value.buffer, ArrayBuffer))) {
 2881    return fromArrayBuffer(value, encodingOrOffset, length)
 2882  }
 2883
 2884  if (typeof value === 'number') {
 2885    throw new TypeError(
 2886      'The "value" argument must not be of type number. Received type number'
 2887    )
 2888  }
 2889
 2890  var valueOf = value.valueOf && value.valueOf()
 2891  if (valueOf != null && valueOf !== value) {
 2892    return Buffer.from(valueOf, encodingOrOffset, length)
 2893  }
 2894
 2895  var b = fromObject(value)
 2896  if (b) return b
 2897
 2898  if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
 2899      typeof value[Symbol.toPrimitive] === 'function') {
 2900    return Buffer.from(
 2901      value[Symbol.toPrimitive]('string'), encodingOrOffset, length
 2902    )
 2903  }
 2904
 2905  throw new TypeError(
 2906    'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
 2907    'or Array-like Object. Received type ' + (typeof value)
 2908  )
 2909}
 2910
 2911/**
 2912 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
 2913 * if value is a number.
 2914 * Buffer.from(str[, encoding])
 2915 * Buffer.from(array)
 2916 * Buffer.from(buffer)
 2917 * Buffer.from(arrayBuffer[, byteOffset[, length]])
 2918 **/
 2919Buffer.from = function (value, encodingOrOffset, length) {
 2920  return from(value, encodingOrOffset, length)
 2921}
 2922
 2923// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
 2924// https://github.com/feross/buffer/pull/148
 2925Buffer.prototype.__proto__ = Uint8Array.prototype
 2926Buffer.__proto__ = Uint8Array
 2927
 2928function assertSize (size) {
 2929  if (typeof size !== 'number') {
 2930    throw new TypeError('"size" argument must be of type number')
 2931  } else if (size < 0) {
 2932    throw new RangeError('The value "' + size + '" is invalid for option "size"')
 2933  }
 2934}
 2935
 2936function alloc (size, fill, encoding) {
 2937  assertSize(size)
 2938  if (size <= 0) {
 2939    return createBuffer(size)
 2940  }
 2941  if (fill !== undefined) {
 2942    // Only pay attention to encoding if it's a string. This
 2943    // prevents accidentally sending in a number that would
 2944    // be interpretted as a start offset.
 2945    return typeof encoding === 'string'
 2946      ? createBuffer(size).fill(fill, encoding)
 2947      : createBuffer(size).fill(fill)
 2948  }
 2949  return createBuffer(size)
 2950}
 2951
 2952/**
 2953 * Creates a new filled Buffer instance.
 2954 * alloc(size[, fill[, encoding]])
 2955 **/
 2956Buffer.alloc = function (size, fill, encoding) {
 2957  return alloc(size, fill, encoding)
 2958}
 2959
 2960function allocUnsafe (size) {
 2961  assertSize(size)
 2962  return createBuffer(size < 0 ? 0 : checked(size) | 0)
 2963}
 2964
 2965/**
 2966 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
 2967 * */
 2968Buffer.allocUnsafe = function (size) {
 2969  return allocUnsafe(size)
 2970}
 2971/**
 2972 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
 2973 */
 2974Buffer.allocUnsafeSlow = function (size) {
 2975  return allocUnsafe(size)
 2976}
 2977
 2978function fromString (string, encoding) {
 2979  if (typeof encoding !== 'string' || encoding === '') {
 2980    encoding = 'utf8'
 2981  }
 2982
 2983  if (!Buffer.isEncoding(encoding)) {
 2984    throw new TypeError('Unknown encoding: ' + encoding)
 2985  }
 2986
 2987  var length = byteLength(string, encoding) | 0
 2988  var buf = createBuffer(length)
 2989
 2990  var actual = buf.write(string, encoding)
 2991
 2992  if (actual !== length) {
 2993    // Writing a hex string, for example, that contains invalid characters will
 2994    // cause everything after the first invalid character to be ignored. (e.g.
 2995    // 'abxxcd' will be treated as 'ab')
 2996    buf = buf.slice(0, actual)
 2997  }
 2998
 2999  return buf
 3000}
 3001
 3002function fromArrayLike (array) {
 3003  var length = array.length < 0 ? 0 : checked(array.length) | 0
 3004  var buf = createBuffer(length)
 3005  for (var i = 0; i < length; i += 1) {
 3006    buf[i] = array[i] & 255
 3007  }
 3008  return buf
 3009}
 3010
 3011function fromArrayBuffer (array, byteOffset, length) {
 3012  if (byteOffset < 0 || array.byteLength < byteOffset) {
 3013    throw new RangeError('"offset" is outside of buffer bounds')
 3014  }
 3015
 3016  if (array.byteLength < byteOffset + (length || 0)) {
 3017    throw new RangeError('"length" is outside of buffer bounds')
 3018  }
 3019
 3020  var buf
 3021  if (byteOffset === undefined && length === undefined) {
 3022    buf = new Uint8Array(array)
 3023  } else if (length === undefined) {
 3024    buf = new Uint8Array(array, byteOffset)
 3025  } else {
 3026    buf = new Uint8Array(array, byteOffset, length)
 3027  }
 3028
 3029  // Return an augmented `Uint8Array` instance
 3030  buf.__proto__ = Buffer.prototype
 3031  return buf
 3032}
 3033
 3034function fromObject (obj) {
 3035  if (Buffer.isBuffer(obj)) {
 3036    var len = checked(obj.length) | 0
 3037    var buf = createBuffer(len)
 3038
 3039    if (buf.length === 0) {
 3040      return buf
 3041    }
 3042
 3043    obj.copy(buf, 0, 0, len)
 3044    return buf
 3045  }
 3046
 3047  if (obj.length !== undefined) {
 3048    if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
 3049      return createBuffer(0)
 3050    }
 3051    return fromArrayLike(obj)
 3052  }
 3053
 3054  if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
 3055    return fromArrayLike(obj.data)
 3056  }
 3057}
 3058
 3059function checked (length) {
 3060  // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
 3061  // length is NaN (which is otherwise coerced to zero.)
 3062  if (length >= K_MAX_LENGTH) {
 3063    throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
 3064                         'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
 3065  }
 3066  return length | 0
 3067}
 3068
 3069function SlowBuffer (length) {
 3070  if (+length != length) { // eslint-disable-line eqeqeq
 3071    length = 0
 3072  }
 3073  return Buffer.alloc(+length)
 3074}
 3075
 3076Buffer.isBuffer = function isBuffer (b) {
 3077  return b != null && b._isBuffer === true &&
 3078    b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
 3079}
 3080
 3081Buffer.compare = function compare (a, b) {
 3082  if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
 3083  if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
 3084  if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
 3085    throw new TypeError(
 3086      'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
 3087    )
 3088  }
 3089
 3090  if (a === b) return 0
 3091
 3092  var x = a.length
 3093  var y = b.length
 3094
 3095  for (var i = 0, len = Math.min(x, y); i < len; ++i) {
 3096    if (a[i] !== b[i]) {
 3097      x = a[i]
 3098      y = b[i]
 3099      break
 3100    }
 3101  }
 3102
 3103  if (x < y) return -1
 3104  if (y < x) return 1
 3105  return 0
 3106}
 3107
 3108Buffer.isEncoding = function isEncoding (encoding) {
 3109  switch (String(encoding).toLowerCase()) {
 3110    case 'hex':
 3111    case 'utf8':
 3112    case 'utf-8':
 3113    case 'ascii':
 3114    case 'latin1':
 3115    case 'binary':
 3116    case 'base64':
 3117    case 'ucs2':
 3118    case 'ucs-2':
 3119    case 'utf16le':
 3120    case 'utf-16le':
 3121      return true
 3122    default:
 3123      return false
 3124  }
 3125}
 3126
 3127Buffer.concat = function concat (list, length) {
 3128  if (!Array.isArray(list)) {
 3129    throw new TypeError('"list" argument must be an Array of Buffers')
 3130  }
 3131
 3132  if (list.length === 0) {
 3133    return Buffer.alloc(0)
 3134  }
 3135
 3136  var i
 3137  if (length === undefined) {
 3138    length = 0
 3139    for (i = 0; i < list.length; ++i) {
 3140      length += list[i].length
 3141    }
 3142  }
 3143
 3144  var buffer = Buffer.allocUnsafe(length)
 3145  var pos = 0
 3146  for (i = 0; i < list.length; ++i) {
 3147    var buf = list[i]
 3148    if (isInstance(buf, Uint8Array)) {
 3149      buf = Buffer.from(buf)
 3150    }
 3151    if (!Buffer.isBuffer(buf)) {
 3152      throw new TypeError('"list" argument must be an Array of Buffers')
 3153    }
 3154    buf.copy(buffer, pos)
 3155    pos += buf.length
 3156  }
 3157  return buffer
 3158}
 3159
 3160function byteLength (string, encoding) {
 3161  if (Buffer.isBuffer(string)) {
 3162    return string.length
 3163  }
 3164  if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
 3165    return string.byteLength
 3166  }
 3167  if (typeof string !== 'string') {
 3168    throw new TypeError(
 3169      'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
 3170      'Received type ' + typeof string
 3171    )
 3172  }
 3173
 3174  var len = string.length
 3175  var mustMatch = (arguments.length > 2 && arguments[2] === true)
 3176  if (!mustMatch && len === 0) return 0
 3177
 3178  // Use a for loop to avoid recursion
 3179  var loweredCase = false
 3180  for (;;) {
 3181    switch (encoding) {
 3182      case 'ascii':
 3183      case 'latin1':
 3184      case 'binary':
 3185        return len
 3186      case 'utf8':
 3187      case 'utf-8':
 3188        return utf8ToBytes(string).length
 3189      case 'ucs2':
 3190      case 'ucs-2':
 3191      case 'utf16le':
 3192      case 'utf-16le':
 3193        return len * 2
 3194      case 'hex':
 3195        return len >>> 1
 3196      case 'base64':
 3197        return base64ToBytes(string).length
 3198      default:
 3199        if (loweredCase) {
 3200          return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
 3201        }
 3202        encoding = ('' + encoding).toLowerCase()
 3203        loweredCase = true
 3204    }
 3205  }
 3206}
 3207Buffer.byteLength = byteLength
 3208
 3209function slowToString (encoding, start, end) {
 3210  var loweredCase = false
 3211
 3212  // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
 3213  // property of a typed array.
 3214
 3215  // This behaves neither like String nor Uint8Array in that we set start/end
 3216  // to their upper/lower bounds if the value passed is out of range.
 3217  // undefined is handled specially as per ECMA-262 6th Edition,
 3218  // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
 3219  if (start === undefined || start < 0) {
 3220    start = 0
 3221  }
 3222  // Return early if start > this.length. Done here to prevent potential uint32
 3223  // coercion fail below.
 3224  if (start > this.length) {
 3225    return ''
 3226  }
 3227
 3228  if (end === undefined || end > this.length) {
 3229    end = this.length
 3230  }
 3231
 3232  if (end <= 0) {
 3233    return ''
 3234  }
 3235
 3236  // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
 3237  end >>>= 0
 3238  start >>>= 0
 3239
 3240  if (end <= start) {
 3241    return ''
 3242  }
 3243
 3244  if (!encoding) encoding = 'utf8'
 3245
 3246  while (true) {
 3247    switch (encoding) {
 3248      case 'hex':
 3249        return hexSlice(this, start, end)
 3250
 3251      case 'utf8':
 3252      case 'utf-8':
 3253        return utf8Slice(this, start, end)
 3254
 3255      case 'ascii':
 3256        return asciiSlice(this, start, end)
 3257
 3258      case 'latin1':
 3259      case 'binary':
 3260        return latin1Slice(this, start, end)
 3261
 3262      case 'base64':
 3263        return base64Slice(this, start, end)
 3264
 3265      case 'ucs2':
 3266      case 'ucs-2':
 3267      case 'utf16le':
 3268      case 'utf-16le':
 3269        return utf16leSlice(this, start, end)
 3270
 3271      default:
 3272        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
 3273        encoding = (encoding + '').toLowerCase()
 3274        loweredCase = true
 3275    }
 3276  }
 3277}
 3278
 3279// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
 3280// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
 3281// reliably in a browserify context because there could be multiple different
 3282// copies of the 'buffer' package in use. This method works even for Buffer
 3283// instances that were created from another copy of the `buffer` package.
 3284// See: https://github.com/feross/buffer/issues/154
 3285Buffer.prototype._isBuffer = true
 3286
 3287function swap (b, n, m) {
 3288  var i = b[n]
 3289  b[n] = b[m]
 3290  b[m] = i
 3291}
 3292
 3293Buffer.prototype.swap16 = function swap16 () {
 3294  var len = this.length
 3295  if (len % 2 !== 0) {
 3296    throw new RangeError('Buffer size must be a multiple of 16-bits')
 3297  }
 3298  for (var i = 0; i < len; i += 2) {
 3299    swap(this, i, i + 1)
 3300  }
 3301  return this
 3302}
 3303
 3304Buffer.prototype.swap32 = function swap32 () {
 3305  var len = this.length
 3306  if (len % 4 !== 0) {
 3307    throw new RangeError('Buffer size must be a multiple of 32-bits')
 3308  }
 3309  for (var i = 0; i < len; i += 4) {
 3310    swap(this, i, i + 3)
 3311    swap(this, i + 1, i + 2)
 3312  }
 3313  return this
 3314}
 3315
 3316Buffer.prototype.swap64 = function swap64 () {
 3317  var len = this.length
 3318  if (len % 8 !== 0) {
 3319    throw new RangeError('Buffer size must be a multiple of 64-bits')
 3320  }
 3321  for (var i = 0; i < len; i += 8) {
 3322    swap(this, i, i + 7)
 3323    swap(this, i + 1, i + 6)
 3324    swap(this, i + 2, i + 5)
 3325    swap(this, i + 3, i + 4)
 3326  }
 3327  return this
 3328}
 3329
 3330Buffer.prototype.toString = function toString () {
 3331  var length = this.length
 3332  if (length === 0) return ''
 3333  if (arguments.length === 0) return utf8Slice(this, 0, length)
 3334  return slowToString.apply(this, arguments)
 3335}
 3336
 3337Buffer.prototype.toLocaleString = Buffer.prototype.toString
 3338
 3339Buffer.prototype.equals = function equals (b) {
 3340  if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
 3341  if (this === b) return true
 3342  return Buffer.compare(this, b) === 0
 3343}
 3344
 3345Buffer.prototype.inspect = function inspect () {
 3346  var str = ''
 3347  var max = exports.INSPECT_MAX_BYTES
 3348  str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
 3349  if (this.length > max) str += ' ... '
 3350  return '<Buffer ' + str + '>'
 3351}
 3352
 3353Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
 3354  if (isInstance(target, Uint8Array)) {
 3355    target = Buffer.from(target, target.offset, target.byteLength)
 3356  }
 3357  if (!Buffer.isBuffer(target)) {
 3358    throw new TypeError(
 3359      'The "target" argument must be one of type Buffer or Uint8Array. ' +
 3360      'Received type ' + (typeof target)
 3361    )
 3362  }
 3363
 3364  if (start === undefined) {
 3365    start = 0
 3366  }
 3367  if (end === undefined) {
 3368    end = target ? target.length : 0
 3369  }
 3370  if (thisStart === undefined) {
 3371    thisStart = 0
 3372  }
 3373  if (thisEnd === undefined) {
 3374    thisEnd = this.length
 3375  }
 3376
 3377  if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
 3378    throw new RangeError('out of range index')
 3379  }
 3380
 3381  if (thisStart >= thisEnd && start >= end) {
 3382    return 0
 3383  }
 3384  if (thisStart >= thisEnd) {
 3385    return -1
 3386  }
 3387  if (start >= end) {
 3388    return 1
 3389  }
 3390
 3391  start >>>= 0
 3392  end >>>= 0
 3393  thisStart >>>= 0
 3394  thisEnd >>>= 0
 3395
 3396  if (this === target) return 0
 3397
 3398  var x = thisEnd - thisStart
 3399  var y = end - start
 3400  var len = Math.min(x, y)
 3401
 3402  var thisCopy = this.slice(thisStart, thisEnd)
 3403  var targetCopy = target.slice(start, end)
 3404
 3405  for (var i = 0; i < len; ++i) {
 3406    if (thisCopy[i] !== targetCopy[i]) {
 3407      x = thisCopy[i]
 3408      y = targetCopy[i]
 3409      break
 3410    }
 3411  }
 3412
 3413  if (x < y) return -1
 3414  if (y < x) return 1
 3415  return 0
 3416}
 3417
 3418// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
 3419// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
 3420//
 3421// Arguments:
 3422// - buffer - a Buffer to search
 3423// - val - a string, Buffer, or number
 3424// - byteOffset - an index into `buffer`; will be clamped to an int32
 3425// - encoding - an optional encoding, relevant is val is a string
 3426// - dir - true for indexOf, false for lastIndexOf
 3427function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
 3428  // Empty buffer means no match
 3429  if (buffer.length === 0) return -1
 3430
 3431  // Normalize byteOffset
 3432  if (typeof byteOffset === 'string') {
 3433    encoding = byteOffset
 3434    byteOffset = 0
 3435  } else if (byteOffset > 0x7fffffff) {
 3436    byteOffset = 0x7fffffff
 3437  } else if (byteOffset < -0x80000000) {
 3438    byteOffset = -0x80000000
 3439  }
 3440  byteOffset = +byteOffset // Coerce to Number.
 3441  if (numberIsNaN(byteOffset)) {
 3442    // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
 3443    byteOffset = dir ? 0 : (buffer.length - 1)
 3444  }
 3445
 3446  // Normalize byteOffset: negative offsets start from the end of the buffer
 3447  if (byteOffset < 0) byteOffset = buffer.length + byteOffset
 3448  if (byteOffset >= buffer.length) {
 3449    if (dir) return -1
 3450    else byteOffset = buffer.length - 1
 3451  } else if (byteOffset < 0) {
 3452    if (dir) byteOffset = 0
 3453    else return -1
 3454  }
 3455
 3456  // Normalize val
 3457  if (typeof val === 'string') {
 3458    val = Buffer.from(val, encoding)
 3459  }
 3460
 3461  // Finally, search either indexOf (if dir is true) or lastIndexOf
 3462  if (Buffer.isBuffer(val)) {
 3463    // Special case: looking for empty string/buffer always fails
 3464    if (val.length === 0) {
 3465      return -1
 3466    }
 3467    return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
 3468  } else if (typeof val === 'number') {
 3469    val = val & 0xFF // Search for a byte value [0-255]
 3470    if (typeof Uint8Array.prototype.indexOf === 'function') {
 3471      if (dir) {
 3472        return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
 3473      } else {
 3474        return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
 3475      }
 3476    }
 3477    return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
 3478  }
 3479
 3480  throw new TypeError('val must be string, number or Buffer')
 3481}
 3482
 3483function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
 3484  var indexSize = 1
 3485  var arrLength = arr.length
 3486  var valLength = val.length
 3487
 3488  if (encoding !== undefined) {
 3489    encoding = String(encoding).toLowerCase()
 3490    if (encoding === 'ucs2' || encoding === 'ucs-2' ||
 3491        encoding === 'utf16le' || encoding === 'utf-16le') {
 3492      if (arr.length < 2 || val.length < 2) {
 3493        return -1
 3494      }
 3495      indexSize = 2
 3496      arrLength /= 2
 3497      valLength /= 2
 3498      byteOffset /= 2
 3499    }
 3500  }
 3501
 3502  function read (buf, i) {
 3503    if (indexSize === 1) {
 3504      return buf[i]
 3505    } else {
 3506      return buf.readUInt16BE(i * indexSize)
 3507    }
 3508  }
 3509
 3510  var i
 3511  if (dir) {
 3512    var foundIndex = -1
 3513    for (i = byteOffset; i < arrLength; i++) {
 3514      if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
 3515        if (foundIndex === -1) foundIndex = i
 3516        if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
 3517      } else {
 3518        if (foundIndex !== -1) i -= i - foundIndex
 3519        foundIndex = -1
 3520      }
 3521    }
 3522  } else {
 3523    if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
 3524    for (i = byteOffset; i >= 0; i--) {
 3525      var found = true
 3526      for (var j = 0; j < valLength; j++) {
 3527        if (read(arr, i + j) !== read(val, j)) {
 3528          found = false
 3529          break
 3530        }
 3531      }
 3532      if (found) return i
 3533    }
 3534  }
 3535
 3536  return -1
 3537}
 3538
 3539Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
 3540  return this.indexOf(val, byteOffset, encoding) !== -1
 3541}
 3542
 3543Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
 3544  return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
 3545}
 3546
 3547Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
 3548  return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
 3549}
 3550
 3551function hexWrite (buf, string, offset, length) {
 3552  offset = Number(offset) || 0
 3553  var remaining = buf.length - offset
 3554  if (!length) {
 3555    length = remaining
 3556  } else {
 3557    length = Number(length)
 3558    if (length > remaining) {
 3559      length = remaining
 3560    }
 3561  }
 3562
 3563  var strLen = string.length
 3564
 3565  if (length > strLen / 2) {
 3566    length = strLen / 2
 3567  }
 3568  for (var i = 0; i < length; ++i) {
 3569    var parsed = parseInt(string.substr(i * 2, 2), 16)
 3570    if (numberIsNaN(parsed)) return i
 3571    buf[offset + i] = parsed
 3572  }
 3573  return i
 3574}
 3575
 3576function utf8Write (buf, string, offset, length) {
 3577  return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
 3578}
 3579
 3580function asciiWrite (buf, string, offset, length) {
 3581  return blitBuffer(asciiToBytes(string), buf, offset, length)
 3582}
 3583
 3584function latin1Write (buf, string, offset, length) {
 3585  return asciiWrite(buf, string, offset, length)
 3586}
 3587
 3588function base64Write (buf, string, offset, length) {
 3589  return blitBuffer(base64ToBytes(string), buf, offset, length)
 3590}
 3591
 3592function ucs2Write (buf, string, offset, length) {
 3593  return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
 3594}
 3595
 3596Buffer.prototype.write = function write (string, offset, length, encoding) {
 3597  // Buffer#write(string)
 3598  if (offset === undefined) {
 3599    encoding = 'utf8'
 3600    length = this.length
 3601    offset = 0
 3602  // Buffer#write(string, encoding)
 3603  } else if (length === undefined && typeof offset === 'string') {
 3604    encoding = offset
 3605    length = this.length
 3606    offset = 0
 3607  // Buffer#write(string, offset[, length][, encoding])
 3608  } else if (isFinite(offset)) {
 3609    offset = offset >>> 0
 3610    if (isFinite(length)) {
 3611      length = length >>> 0
 3612      if (encoding === undefined) encoding = 'utf8'
 3613    } else {
 3614      encoding = length
 3615      length = undefined
 3616    }
 3617  } else {
 3618    throw new Error(
 3619      'Buffer.write(string, encoding, offset[, length]) is no longer supported'
 3620    )
 3621  }
 3622
 3623  var remaining = this.length - offset
 3624  if (length === undefined || length > remaining) length = remaining
 3625
 3626  if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
 3627    throw new RangeError('Attempt to write outside buffer bounds')
 3628  }
 3629
 3630  if (!encoding) encoding = 'utf8'
 3631
 3632  var loweredCase = false
 3633  for (;;) {
 3634    switch (encoding) {
 3635      case 'hex':
 3636        return hexWrite(this, string, offset, length)
 3637
 3638      case 'utf8':
 3639      case 'utf-8':
 3640        return utf8Write(this, string, offset, length)
 3641
 3642      case 'ascii':
 3643        return asciiWrite(this, string, offset, length)
 3644
 3645      case 'latin1':
 3646      case 'binary':
 3647        return latin1Write(this, string, offset, length)
 3648
 3649      case 'base64':
 3650        // Warning: maxLength not taken into account in base64Write
 3651        return base64Write(this, string, offset, length)
 3652
 3653      case 'ucs2':
 3654      case 'ucs-2':
 3655      case 'utf16le':
 3656      case 'utf-16le':
 3657        return ucs2Write(this, string, offset, length)
 3658
 3659      default:
 3660        if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
 3661        encoding = ('' + encoding).toLowerCase()
 3662        loweredCase = true
 3663    }
 3664  }
 3665}
 3666
 3667Buffer.prototype.toJSON = function toJSON () {
 3668  return {
 3669    type: 'Buffer',
 3670    data: Array.prototype.slice.call(this._arr || this, 0)
 3671  }
 3672}
 3673
 3674function base64Slice (buf, start, end) {
 3675  if (start === 0 && end === buf.length) {
 3676    return base64.fromByteArray(buf)
 3677  } else {
 3678    return base64.fromByteArray(buf.slice(start, end))
 3679  }
 3680}
 3681
 3682function utf8Slice (buf, start, end) {
 3683  end = Math.min(buf.length, end)
 3684  var res = []
 3685
 3686  var i = start
 3687  while (i < end) {
 3688    var firstByte = buf[i]
 3689    var codePoint = null
 3690    var bytesPerSequence = (firstByte > 0xEF) ? 4
 3691      : (firstByte > 0xDF) ? 3
 3692        : (firstByte > 0xBF) ? 2
 3693          : 1
 3694
 3695    if (i + bytesPerSequence <= end) {
 3696      var secondByte, thirdByte, fourthByte, tempCodePoint
 3697
 3698      switch (bytesPerSequence) {
 3699        case 1:
 3700          if (firstByte < 0x80) {
 3701            codePoint = firstByte
 3702          }
 3703          break
 3704        case 2:
 3705          secondByte = buf[i + 1]
 3706          if ((secondByte & 0xC0) === 0x80) {
 3707            tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
 3708            if (tempCodePoint > 0x7F) {
 3709              codePoint = tempCodePoint
 3710            }
 3711          }
 3712          break
 3713        case 3:
 3714          secondByte = buf[i + 1]
 3715          thirdByte = buf[i + 2]
 3716          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
 3717            tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
 3718            if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
 3719              codePoint = tempCodePoint
 3720            }
 3721          }
 3722          break
 3723        case 4:
 3724          secondByte = buf[i + 1]
 3725          thirdByte = buf[i + 2]
 3726          fourthByte = buf[i + 3]
 3727          if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
 3728            tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
 3729            if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
 3730              codePoint = tempCodePoint
 3731            }
 3732          }
 3733      }
 3734    }
 3735
 3736    if (codePoint === null) {
 3737      // we did not generate a valid codePoint so insert a
 3738      // replacement char (U+FFFD) and advance only 1 byte
 3739      codePoint = 0xFFFD
 3740      bytesPerSequence = 1
 3741    } else if (codePoint > 0xFFFF) {
 3742      // encode to utf16 (surrogate pair dance)
 3743      codePoint -= 0x10000
 3744      res.push(codePoint >>> 10 & 0x3FF | 0xD800)
 3745      codePoint = 0xDC00 | codePoint & 0x3FF
 3746    }
 3747
 3748    res.push(codePoint)
 3749    i += bytesPerSequence
 3750  }
 3751
 3752  return decodeCodePointsArray(res)
 3753}
 3754
 3755// Based on http://stackoverflow.com/a/22747272/680742, the browser with
 3756// the lowest limit is Chrome, with 0x10000 args.
 3757// We go 1 magnitude less, for safety
 3758var MAX_ARGUMENTS_LENGTH = 0x1000
 3759
 3760function decodeCodePointsArray (codePoints) {
 3761  var len = codePoints.length
 3762  if (len <= MAX_ARGUMENTS_LENGTH) {
 3763    return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
 3764  }
 3765
 3766  // Decode in chunks to avoid "call stack size exceeded".
 3767  var res = ''
 3768  var i = 0
 3769  while (i < len) {
 3770    res += String.fromCharCode.apply(
 3771      String,
 3772      codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
 3773    )
 3774  }
 3775  return res
 3776}
 3777
 3778function asciiSlice (buf, start, end) {
 3779  var ret = ''
 3780  end = Math.min(buf.length, end)
 3781
 3782  for (var i = start; i < end; ++i) {
 3783    ret += String.fromCharCode(buf[i] & 0x7F)
 3784  }
 3785  return ret
 3786}
 3787
 3788function latin1Slice (buf, start, end) {
 3789  var ret = ''
 3790  end = Math.min(buf.length, end)
 3791
 3792  for (var i = start; i < end; ++i) {
 3793    ret += String.fromCharCode(buf[i])
 3794  }
 3795  return ret
 3796}
 3797
 3798function hexSlice (buf, start, end) {
 3799  var len = buf.length
 3800
 3801  if (!start || start < 0) start = 0
 3802  if (!end || end < 0 || end > len) end = len
 3803
 3804  var out = ''
 3805  for (var i = start; i < end; ++i) {
 3806    out += toHex(buf[i])
 3807  }
 3808  return out
 3809}
 3810
 3811function utf16leSlice (buf, start, end) {
 3812  var bytes = buf.slice(start, end)
 3813  var res = ''
 3814  for (var i = 0; i < bytes.length; i += 2) {
 3815    res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
 3816  }
 3817  return res
 3818}
 3819
 3820Buffer.prototype.slice = function slice (start, end) {
 3821  var len = this.length
 3822  start = ~~start
 3823  end = end === undefined ? len : ~~end
 3824
 3825  if (start < 0) {
 3826    start += len
 3827    if (start < 0) start = 0
 3828  } else if (start > len) {
 3829    start = len
 3830  }
 3831
 3832  if (end < 0) {
 3833    end += len
 3834    if (end < 0) end = 0
 3835  } else if (end > len) {
 3836    end = len
 3837  }
 3838
 3839  if (end < start) end = start
 3840
 3841  var newBuf = this.subarray(start, end)
 3842  // Return an augmented `Uint8Array` instance
 3843  newBuf.__proto__ = Buffer.prototype
 3844  return newBuf
 3845}
 3846
 3847/*
 3848 * Need to make sure that buffer isn't trying to write out of bounds.
 3849 */
 3850function checkOffset (offset, ext, length) {
 3851  if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
 3852  if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
 3853}
 3854
 3855Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
 3856  offset = offset >>> 0
 3857  byteLength = byteLength >>> 0
 3858  if (!noAssert) checkOffset(offset, byteLength, this.length)
 3859
 3860  var val = this[offset]
 3861  var mul = 1
 3862  var i = 0
 3863  while (++i < byteLength && (mul *= 0x100)) {
 3864    val += this[offset + i] * mul
 3865  }
 3866
 3867  return val
 3868}
 3869
 3870Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
 3871  offset = offset >>> 0
 3872  byteLength = byteLength >>> 0
 3873  if (!noAssert) {
 3874    checkOffset(offset, byteLength, this.length)
 3875  }
 3876
 3877  var val = this[offset + --byteLength]
 3878  var mul = 1
 3879  while (byteLength > 0 && (mul *= 0x100)) {
 3880    val += this[offset + --byteLength] * mul
 3881  }
 3882
 3883  return val
 3884}
 3885
 3886Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
 3887  offset = offset >>> 0
 3888  if (!noAssert) checkOffset(offset, 1, this.length)
 3889  return this[offset]
 3890}
 3891
 3892Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
 3893  offset = offset >>> 0
 3894  if (!noAssert) checkOffset(offset, 2, this.length)
 3895  return this[offset] | (this[offset + 1] << 8)
 3896}
 3897
 3898Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
 3899  offset = offset >>> 0
 3900  if (!noAssert) checkOffset(offset, 2, this.length)
 3901  return (this[offset] << 8) | this[offset + 1]
 3902}
 3903
 3904Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
 3905  offset = offset >>> 0
 3906  if (!noAssert) checkOffset(offset, 4, this.length)
 3907
 3908  return ((this[offset]) |
 3909      (this[offset + 1] << 8) |
 3910      (this[offset + 2] << 16)) +
 3911      (this[offset + 3] * 0x1000000)
 3912}
 3913
 3914Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
 3915  offset = offset >>> 0
 3916  if (!noAssert) checkOffset(offset, 4, this.length)
 3917
 3918  return (this[offset] * 0x1000000) +
 3919    ((this[offset + 1] << 16) |
 3920    (this[offset + 2] << 8) |
 3921    this[offset + 3])
 3922}
 3923
 3924Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
 3925  offset = offset >>> 0
 3926  byteLength = byteLength >>> 0
 3927  if (!noAssert) checkOffset(offset, byteLength, this.length)
 3928
 3929  var val = this[offset]
 3930  var mul = 1
 3931  var i = 0
 3932  while (++i < byteLength && (mul *= 0x100)) {
 3933    val += this[offset + i] * mul
 3934  }
 3935  mul *= 0x80
 3936
 3937  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
 3938
 3939  return val
 3940}
 3941
 3942Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
 3943  offset = offset >>> 0
 3944  byteLength = byteLength >>> 0
 3945  if (!noAssert) checkOffset(offset, byteLength, this.length)
 3946
 3947  var i = byteLength
 3948  var mul = 1
 3949  var val = this[offset + --i]
 3950  while (i > 0 && (mul *= 0x100)) {
 3951    val += this[offset + --i] * mul
 3952  }
 3953  mul *= 0x80
 3954
 3955  if (val >= mul) val -= Math.pow(2, 8 * byteLength)
 3956
 3957  return val
 3958}
 3959
 3960Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
 3961  offset = offset >>> 0
 3962  if (!noAssert) checkOffset(offset, 1, this.length)
 3963  if (!(this[offset] & 0x80)) return (this[offset])
 3964  return ((0xff - this[offset] + 1) * -1)
 3965}
 3966
 3967Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
 3968  offset = offset >>> 0
 3969  if (!noAssert) checkOffset(offset, 2, this.length)
 3970  var val = this[offset] | (this[offset + 1] << 8)
 3971  return (val & 0x8000) ? val | 0xFFFF0000 : val
 3972}
 3973
 3974Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
 3975  offset = offset >>> 0
 3976  if (!noAssert) checkOffset(offset, 2, this.length)
 3977  var val = this[offset + 1] | (this[offset] << 8)
 3978  return (val & 0x8000) ? val | 0xFFFF0000 : val
 3979}
 3980
 3981Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
 3982  offset = offset >>> 0
 3983  if (!noAssert) checkOffset(offset, 4, this.length)
 3984
 3985  return (this[offset]) |
 3986    (this[offset + 1] << 8) |
 3987    (this[offset + 2] << 16) |
 3988    (this[offset + 3] << 24)
 3989}
 3990
 3991Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
 3992  offset = offset >>> 0
 3993  if (!noAssert) checkOffset(offset, 4, this.length)
 3994
 3995  return (this[offset] << 24) |
 3996    (this[offset + 1] << 16) |
 3997    (this[offset + 2] << 8) |
 3998    (this[offset + 3])
 3999}
 4000
 4001Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
 4002  offset = offset >>> 0
 4003  if (!noAssert) checkOffset(offset, 4, this.length)
 4004  return ieee754.read(this, offset, true, 23, 4)
 4005}
 4006
 4007Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
 4008  offset = offset >>> 0
 4009  if (!noAssert) checkOffset(offset, 4, this.length)
 4010  return ieee754.read(this, offset, false, 23, 4)
 4011}
 4012
 4013Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
 4014  offset = offset >>> 0
 4015  if (!noAssert) checkOffset(offset, 8, this.length)
 4016  return ieee754.read(this, offset, true, 52, 8)
 4017}
 4018
 4019Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
 4020  offset = offset >>> 0
 4021  if (!noAssert) checkOffset(offset, 8, this.length)
 4022  return ieee754.read(this, offset, false, 52, 8)
 4023}
 4024
 4025function checkInt (buf, value, offset, ext, max, min) {
 4026  if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
 4027  if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
 4028  if (offset + ext > buf.length) throw new RangeError('Index out of range')
 4029}
 4030
 4031Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
 4032  value = +value
 4033  offset = offset >>> 0
 4034  byteLength = byteLength >>> 0
 4035  if (!noAssert) {
 4036    var maxBytes = Math.pow(2, 8 * byteLength) - 1
 4037    checkInt(this, value, offset, byteLength, maxBytes, 0)
 4038  }
 4039
 4040  var mul = 1
 4041  var i = 0
 4042  this[offset] = value & 0xFF
 4043  while (++i < byteLength && (mul *= 0x100)) {
 4044    this[offset + i] = (value / mul) & 0xFF
 4045  }
 4046
 4047  return offset + byteLength
 4048}
 4049
 4050Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
 4051  value = +value
 4052  offset = offset >>> 0
 4053  byteLength = byteLength >>> 0
 4054  if (!noAssert) {
 4055    var maxBytes = Math.pow(2, 8 * byteLength) - 1
 4056    checkInt(this, value, offset, byteLength, maxBytes, 0)
 4057  }
 4058
 4059  var i = byteLength - 1
 4060  var mul = 1
 4061  this[offset + i] = value & 0xFF
 4062  while (--i >= 0 && (mul *= 0x100)) {
 4063    this[offset + i] = (value / mul) & 0xFF
 4064  }
 4065
 4066  return offset + byteLength
 4067}
 4068
 4069Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
 4070  value = +value
 4071  offset = offset >>> 0
 4072  if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
 4073  this[offset] = (value & 0xff)
 4074  return offset + 1
 4075}
 4076
 4077Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
 4078  value = +value
 4079  offset = offset >>> 0
 4080  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
 4081  this[offset] = (value & 0xff)
 4082  this[offset + 1] = (value >>> 8)
 4083  return offset + 2
 4084}
 4085
 4086Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
 4087  value = +value
 4088  offset = offset >>> 0
 4089  if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
 4090  this[offset] = (value >>> 8)
 4091  this[offset + 1] = (value & 0xff)
 4092  return offset + 2
 4093}
 4094
 4095Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
 4096  value = +value
 4097  offset = offset >>> 0
 4098  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
 4099  this[offset + 3] = (value >>> 24)
 4100  this[offset + 2] = (value >>> 16)
 4101  this[offset + 1] = (value >>> 8)
 4102  this[offset] = (value & 0xff)
 4103  return offset + 4
 4104}
 4105
 4106Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
 4107  value = +value
 4108  offset = offset >>> 0
 4109  if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
 4110  this[offset] = (value >>> 24)
 4111  this[offset + 1] = (value >>> 16)
 4112  this[offset + 2] = (value >>> 8)
 4113  this[offset + 3] = (value & 0xff)
 4114  return offset + 4
 4115}
 4116
 4117Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
 4118  value = +value
 4119  offset = offset >>> 0
 4120  if (!noAssert) {
 4121    var limit = Math.pow(2, (8 * byteLength) - 1)
 4122
 4123    checkInt(this, value, offset, byteLength, limit - 1, -limit)
 4124  }
 4125
 4126  var i = 0
 4127  var mul = 1
 4128  var sub = 0
 4129  this[offset] = value & 0xFF
 4130  while (++i < byteLength && (mul *= 0x100)) {
 4131    if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
 4132      sub = 1
 4133    }
 4134    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
 4135  }
 4136
 4137  return offset + byteLength
 4138}
 4139
 4140Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
 4141  value = +value
 4142  offset = offset >>> 0
 4143  if (!noAssert) {
 4144    var limit = Math.pow(2, (8 * byteLength) - 1)
 4145
 4146    checkInt(this, value, offset, byteLength, limit - 1, -limit)
 4147  }
 4148
 4149  var i = byteLength - 1
 4150  var mul = 1
 4151  var sub = 0
 4152  this[offset + i] = value & 0xFF
 4153  while (--i >= 0 && (mul *= 0x100)) {
 4154    if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
 4155      sub = 1
 4156    }
 4157    this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
 4158  }
 4159
 4160  return offset + byteLength
 4161}
 4162
 4163Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
 4164  value = +value
 4165  offset = offset >>> 0
 4166  if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
 4167  if (value < 0) value = 0xff + value + 1
 4168  this[offset] = (value & 0xff)
 4169  return offset + 1
 4170}
 4171
 4172Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
 4173  value = +value
 4174  offset = offset >>> 0
 4175  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
 4176  this[offset] = (value & 0xff)
 4177  this[offset + 1] = (value >>> 8)
 4178  return offset + 2
 4179}
 4180
 4181Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
 4182  value = +value
 4183  offset = offset >>> 0
 4184  if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
 4185  this[offset] = (value >>> 8)
 4186  this[offset + 1] = (value & 0xff)
 4187  return offset + 2
 4188}
 4189
 4190Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
 4191  value = +value
 4192  offset = offset >>> 0
 4193  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
 4194  this[offset] = (value & 0xff)
 4195  this[offset + 1] = (value >>> 8)
 4196  this[offset + 2] = (value >>> 16)
 4197  this[offset + 3] = (value >>> 24)
 4198  return offset + 4
 4199}
 4200
 4201Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
 4202  value = +value
 4203  offset = offset >>> 0
 4204  if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
 4205  if (value < 0) value = 0xffffffff + value + 1
 4206  this[offset] = (value >>> 24)
 4207  this[offset + 1] = (value >>> 16)
 4208  this[offset + 2] = (value >>> 8)
 4209  this[offset + 3] = (value & 0xff)
 4210  return offset + 4
 4211}
 4212
 4213function checkIEEE754 (buf, value, offset, ext, max, min) {
 4214  if (offset + ext > buf.length) throw new RangeError('Index out of range')
 4215  if (offset < 0) throw new RangeError('Index out of range')
 4216}
 4217
 4218function writeFloat (buf, value, offset, littleEndian, noAssert) {
 4219  value = +value
 4220  offset = offset >>> 0
 4221  if (!noAssert) {
 4222    checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
 4223  }
 4224  ieee754.write(buf, value, offset, littleEndian, 23, 4)
 4225  return offset + 4
 4226}
 4227
 4228Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
 4229  return writeFloat(this, value, offset, true, noAssert)
 4230}
 4231
 4232Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
 4233  return writeFloat(this, value, offset, false, noAssert)
 4234}
 4235
 4236function writeDouble (buf, value, offset, littleEndian, noAssert) {
 4237  value = +value
 4238  offset = offset >>> 0
 4239  if (!noAssert) {
 4240    checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
 4241  }
 4242  ieee754.write(buf, value, offset, littleEndian, 52, 8)
 4243  return offset + 8
 4244}
 4245
 4246Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
 4247  return writeDouble(this, value, offset, true, noAssert)
 4248}
 4249
 4250Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
 4251  return writeDouble(this, value, offset, false, noAssert)
 4252}
 4253
 4254// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
 4255Buffer.prototype.copy = function copy (target, targetStart, start, end) {
 4256  if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
 4257  if (!start) start = 0
 4258  if (!end && end !== 0) end = this.length
 4259  if (targetStart >= target.length) targetStart = target.length
 4260  if (!targetStart) targetStart = 0
 4261  if (end > 0 && end < start) end = start
 4262
 4263  // Copy 0 bytes; we're done
 4264  if (end === start) return 0
 4265  if (target.length === 0 || this.length === 0) return 0
 4266
 4267  // Fatal error conditions
 4268  if (targetStart < 0) {
 4269    throw new RangeError('targetStart out of bounds')
 4270  }
 4271  if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
 4272  if (end < 0) throw new RangeError('sourceEnd out of bounds')
 4273
 4274  // Are we oob?
 4275  if (end > this.length) end = this.length
 4276  if (target.length - targetStart < end - start) {
 4277    end = target.length - targetStart + start
 4278  }
 4279
 4280  var len = end - start
 4281
 4282  if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
 4283    // Use built-in when available, missing from IE11
 4284    this.copyWithin(targetStart, start, end)
 4285  } else if (this === target && start < targetStart && targetStart < end) {
 4286    // descending copy from end
 4287    for (var i = len - 1; i >= 0; --i) {
 4288      target[i + targetStart] = this[i + start]
 4289    }
 4290  } else {
 4291    Uint8Array.prototype.set.call(
 4292      target,
 4293      this.subarray(start, end),
 4294      targetStart
 4295    )
 4296  }
 4297
 4298  return len
 4299}
 4300
 4301// Usage:
 4302//    buffer.fill(number[, offset[, end]])
 4303//    buffer.fill(buffer[, offset[, end]])
 4304//    buffer.fill(string[, offset[, end]][, encoding])
 4305Buffer.prototype.fill = function fill (val, start, end, encoding) {
 4306  // Handle string cases:
 4307  if (typeof val === 'string') {
 4308    if (typeof start === 'string') {
 4309      encoding = start
 4310      start = 0
 4311      end = this.length
 4312    } else if (typeof end === 'string') {
 4313      encoding = end
 4314      end = this.length
 4315    }
 4316    if (encoding !== undefined && typeof encoding !== 'string') {
 4317      throw new TypeError('encoding must be a string')
 4318    }
 4319    if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
 4320      throw new TypeError('Unknown encoding: ' + encoding)
 4321    }
 4322    if (val.length === 1) {
 4323      var code = val.charCodeAt(0)
 4324      if ((encoding === 'utf8' && code < 128) ||
 4325          encoding === 'latin1') {
 4326        // Fast path: If `val` fits into a single byte, use that numeric value.
 4327        val = code
 4328      }
 4329    }
 4330  } else if (typeof val === 'number') {
 4331    val = val & 255
 4332  }
 4333
 4334  // Invalid ranges are not set to a default, so can range check early.
 4335  if (start < 0 || this.length < start || this.length < end) {
 4336    throw new RangeError('Out of range index')
 4337  }
 4338
 4339  if (end <= start) {
 4340    return this
 4341  }
 4342
 4343  start = start >>> 0
 4344  end = end === undefined ? this.length : end >>> 0
 4345
 4346  if (!val) val = 0
 4347
 4348  var i
 4349  if (typeof val === 'number') {
 4350    for (i = start; i < end; ++i) {
 4351      this[i] = val
 4352    }
 4353  } else {
 4354    var bytes = Buffer.isBuffer(val)
 4355      ? val
 4356      : Buffer.from(val, encoding)
 4357    var len = bytes.length
 4358    if (len === 0) {
 4359      throw new TypeError('The value "' + val +
 4360        '" is invalid for argument "value"')
 4361    }
 4362    for (i = 0; i < end - start; ++i) {
 4363      this[i + start] = bytes[i % len]
 4364    }
 4365  }
 4366
 4367  return this
 4368}
 4369
 4370// HELPER FUNCTIONS
 4371// ================
 4372
 4373var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
 4374
 4375function base64clean (str) {
 4376  // Node takes equal signs as end of the Base64 encoding
 4377  str = str.split('=')[0]
 4378  // Node strips out invalid characters like \n and \t from the string, base64-js does not
 4379  str = str.trim().replace(INVALID_BASE64_RE, '')
 4380  // Node converts strings with length < 2 to ''
 4381  if (str.length < 2) return ''
 4382  // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
 4383  while (str.length % 4 !== 0) {
 4384    str = str + '='
 4385  }
 4386  return str
 4387}
 4388
 4389function toHex (n) {
 4390  if (n < 16) return '0' + n.toString(16)
 4391  return n.toString(16)
 4392}
 4393
 4394function utf8ToBytes (string, units) {
 4395  units = units || Infinity
 4396  var codePoint
 4397  var length = string.length
 4398  var leadSurrogate = null
 4399  var bytes = []
 4400
 4401  for (var i = 0; i < length; ++i) {
 4402    codePoint = string.charCodeAt(i)
 4403
 4404    // is surrogate component
 4405    if (codePoint > 0xD7FF && codePoint < 0xE000) {
 4406      // last char was a lead
 4407      if (!leadSurrogate) {
 4408        // no lead yet
 4409        if (codePoint > 0xDBFF) {
 4410          // unexpected trail
 4411          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
 4412          continue
 4413        } else if (i + 1 === length) {
 4414          // unpaired lead
 4415          if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
 4416          continue
 4417        }
 4418
 4419        // valid lead
 4420        leadSurrogate = codePoint
 4421
 4422        continue
 4423      }
 4424
 4425      // 2 leads in a row
 4426      if (codePoint < 0xDC00) {
 4427        if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
 4428        leadSurrogate = codePoint
 4429        continue
 4430      }
 4431
 4432      // valid surrogate pair
 4433      codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
 4434    } else if (leadSurrogate) {
 4435      // valid bmp char, but last char was a lead
 4436      if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
 4437    }
 4438
 4439    leadSurrogate = null
 4440
 4441    // encode utf8
 4442    if (codePoint < 0x80) {
 4443      if ((units -= 1) < 0) break
 4444      bytes.push(codePoint)
 4445    } else if (codePoint < 0x800) {
 4446      if ((units -= 2) < 0) break
 4447      bytes.push(
 4448        codePoint >> 0x6 | 0xC0,
 4449        codePoint & 0x3F | 0x80
 4450      )
 4451    } else if (codePoint < 0x10000) {
 4452      if ((units -= 3) < 0) break
 4453      bytes.push(
 4454        codePoint >> 0xC | 0xE0,
 4455        codePoint >> 0x6 & 0x3F | 0x80,
 4456        codePoint & 0x3F | 0x80
 4457      )
 4458    } else if (codePoint < 0x110000) {
 4459      if ((units -= 4) < 0) break
 4460      bytes.push(
 4461        codePoint >> 0x12 | 0xF0,
 4462        codePoint >> 0xC & 0x3F | 0x80,
 4463        codePoint >> 0x6 & 0x3F | 0x80,
 4464        codePoint & 0x3F | 0x80
 4465      )
 4466    } else {
 4467      throw new Error('Invalid code point')
 4468    }
 4469  }
 4470
 4471  return bytes
 4472}
 4473
 4474function asciiToBytes (str) {
 4475  var byteArray = []
 4476  for (var i = 0; i < str.length; ++i) {
 4477    // Node's code seems to be doing this and not & 0x7F..
 4478    byteArray.push(str.charCodeAt(i) & 0xFF)
 4479  }
 4480  return byteArray
 4481}
 4482
 4483function utf16leToBytes (str, units) {
 4484  var c, hi, lo
 4485  var byteArray = []
 4486  for (var i = 0; i < str.length; ++i) {
 4487    if ((units -= 2) < 0) break
 4488
 4489    c = str.charCodeAt(i)
 4490    hi = c >> 8
 4491    lo = c % 256
 4492    byteArray.push(lo)
 4493    byteArray.push(hi)
 4494  }
 4495
 4496  return byteArray
 4497}
 4498
 4499function base64ToBytes (str) {
 4500  return base64.toByteArray(base64clean(str))
 4501}
 4502
 4503function blitBuffer (src, dst, offset, length) {
 4504  for (var i = 0; i < length; ++i) {
 4505    if ((i + offset >= dst.length) || (i >= src.length)) break
 4506    dst[i + offset] = src[i]
 4507  }
 4508  return i
 4509}
 4510
 4511// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
 4512// the `instanceof` check but they should be treated as of that type.
 4513// See: https://github.com/feross/buffer/issues/166
 4514function isInstance (obj, type) {
 4515  return obj instanceof type ||
 4516    (obj != null && obj.constructor != null && obj.constructor.name != null &&
 4517      obj.constructor.name === type.name)
 4518}
 4519function numberIsNaN (obj) {
 4520  // For IE11 support
 4521  return obj !== obj // eslint-disable-line no-self-compare
 4522}
 4523
 4524}).call(this,require("buffer").Buffer)
 4525},{"base64-js":5,"buffer":8,"ieee754":28}],9:[function(require,module,exports){
 4526// shim for using process in browser
 4527var process = module.exports = {};
 4528
 4529// cached from whatever global is present so that test runners that stub it
 4530// don't break things.  But we need to wrap it in a try catch in case it is
 4531// wrapped in strict mode code which doesn't define any globals.  It's inside a
 4532// function because try/catches deoptimize in certain engines.
 4533
 4534var cachedSetTimeout;
 4535var cachedClearTimeout;
 4536
 4537function defaultSetTimout() {
 4538    throw new Error('setTimeout has not been defined');
 4539}
 4540function defaultClearTimeout () {
 4541    throw new Error('clearTimeout has not been defined');
 4542}
 4543(function () {
 4544    try {
 4545        if (typeof setTimeout === 'function') {
 4546            cachedSetTimeout = setTimeout;
 4547        } else {
 4548            cachedSetTimeout = defaultSetTimout;
 4549        }
 4550    } catch (e) {
 4551        cachedSetTimeout = defaultSetTimout;
 4552    }
 4553    try {
 4554        if (typeof clearTimeout === 'function') {
 4555            cachedClearTimeout = clearTimeout;
 4556        } else {
 4557            cachedClearTimeout = defaultClearTimeout;
 4558        }
 4559    } catch (e) {
 4560        cachedClearTimeout = defaultClearTimeout;
 4561    }
 4562} ())
 4563function runTimeout(fun) {
 4564    if (cachedSetTimeout === setTimeout) {
 4565        //normal enviroments in sane situations
 4566        return setTimeout(fun, 0);
 4567    }
 4568    // if setTimeout wasn't available but was latter defined
 4569    if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
 4570        cachedSetTimeout = setTimeout;
 4571        return setTimeout(fun, 0);
 4572    }
 4573    try {
 4574        // when when somebody has screwed with setTimeout but no I.E. maddness
 4575        return cachedSetTimeout(fun, 0);
 4576    } catch(e){
 4577        try {
 4578            // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
 4579            return cachedSetTimeout.call(null, fun, 0);
 4580        } catch(e){
 4581            // 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
 4582            return cachedSetTimeout.call(this, fun, 0);
 4583        }
 4584    }
 4585
 4586
 4587}
 4588function runClearTimeout(marker) {
 4589    if (cachedClearTimeout === clearTimeout) {
 4590        //normal enviroments in sane situations
 4591        return clearTimeout(marker);
 4592    }
 4593    // if clearTimeout wasn't available but was latter defined
 4594    if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
 4595        cachedClearTimeout = clearTimeout;
 4596        return clearTimeout(marker);
 4597    }
 4598    try {
 4599        // when when somebody has screwed with setTimeout but no I.E. maddness
 4600        return cachedClearTimeout(marker);
 4601    } catch (e){
 4602        try {
 4603            // When we are in I.E. but the script has been evaled so I.E. doesn't  trust the global object when called normally
 4604            return cachedClearTimeout.call(null, marker);
 4605        } catch (e){
 4606            // 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.
 4607            // Some versions of I.E. have different rules for clearTimeout vs setTimeout
 4608            return cachedClearTimeout.call(this, marker);
 4609        }
 4610    }
 4611
 4612
 4613
 4614}
 4615var queue = [];
 4616var draining = false;
 4617var currentQueue;
 4618var queueIndex = -1;
 4619
 4620function cleanUpNextTick() {
 4621    if (!draining || !currentQueue) {
 4622        return;
 4623    }
 4624    draining = false;
 4625    if (currentQueue.length) {
 4626        queue = currentQueue.concat(queue);
 4627    } else {
 4628        queueIndex = -1;
 4629    }
 4630    if (queue.length) {
 4631        drainQueue();
 4632    }
 4633}
 4634
 4635function drainQueue() {
 4636    if (draining) {
 4637        return;
 4638    }
 4639    var timeout = runTimeout(cleanUpNextTick);
 4640    draining = true;
 4641
 4642    var len = queue.length;
 4643    while(len) {
 4644        currentQueue = queue;
 4645        queue = [];
 4646        while (++queueIndex < len) {
 4647            if (currentQueue) {
 4648                currentQueue[queueIndex].run();
 4649            }
 4650        }
 4651        queueIndex = -1;
 4652        len = queue.length;
 4653    }
 4654    currentQueue = null;
 4655    draining = false;
 4656    runClearTimeout(timeout);
 4657}
 4658
 4659process.nextTick = function (fun) {
 4660    var args = new Array(arguments.length - 1);
 4661    if (arguments.length > 1) {
 4662        for (var i = 1; i < arguments.length; i++) {
 4663            args[i - 1] = arguments[i];
 4664        }
 4665    }
 4666    queue.push(new Item(fun, args));
 4667    if (queue.length === 1 && !draining) {
 4668        runTimeout(drainQueue);
 4669    }
 4670};
 4671
 4672// v8 likes predictible objects
 4673function Item(fun, array) {
 4674    this.fun = fun;
 4675    this.array = array;
 4676}
 4677Item.prototype.run = function () {
 4678    this.fun.apply(null, this.array);
 4679};
 4680process.title = 'browser';
 4681process.browser = true;
 4682process.env = {};
 4683process.argv = [];
 4684process.version = ''; // empty string to avoid regexp issues
 4685process.versions = {};
 4686
 4687function noop() {}
 4688
 4689process.on = noop;
 4690process.addListener = noop;
 4691process.once = noop;
 4692process.off = noop;
 4693process.removeListener = noop;
 4694process.removeAllListeners = noop;
 4695process.emit = noop;
 4696process.prependListener = noop;
 4697process.prependOnceListener = noop;
 4698
 4699process.listeners = function (name) { return [] }
 4700
 4701process.binding = function (name) {
 4702    throw new Error('process.binding is not supported');
 4703};
 4704
 4705process.cwd = function () { return '/' };
 4706process.chdir = function (dir) {
 4707    throw new Error('process.chdir is not supported');
 4708};
 4709process.umask = function() { return 0; };
 4710
 4711},{}],10:[function(require,module,exports){
 4712(function (Buffer){
 4713// Copyright Joyent, Inc. and other Node contributors.
 4714//
 4715// Permission is hereby granted, free of charge, to any person obtaining a
 4716// copy of this software and associated documentation files (the
 4717// "Software"), to deal in the Software without restriction, including
 4718// without limitation the rights to use, copy, modify, merge, publish,
 4719// distribute, sublicense, and/or sell copies of the Software, and to permit
 4720// persons to whom the Software is furnished to do so, subject to the
 4721// following conditions:
 4722//
 4723// The above copyright notice and this permission notice shall be included
 4724// in all copies or substantial portions of the Software.
 4725//
 4726// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 4727// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 4728// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 4729// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 4730// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 4731// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 4732// USE OR OTHER DEALINGS IN THE SOFTWARE.
 4733
 4734// NOTE: These type checking functions intentionally don't use `instanceof`
 4735// because it is fragile and can be easily faked with `Object.create()`.
 4736
 4737function isArray(arg) {
 4738  if (Array.isArray) {
 4739    return Array.isArray(arg);
 4740  }
 4741  return objectToString(arg) === '[object Array]';
 4742}
 4743exports.isArray = isArray;
 4744
 4745function isBoolean(arg) {
 4746  return typeof arg === 'boolean';
 4747}
 4748exports.isBoolean = isBoolean;
 4749
 4750function isNull(arg) {
 4751  return arg === null;
 4752}
 4753exports.isNull = isNull;
 4754
 4755function isNullOrUndefined(arg) {
 4756  return arg == null;
 4757}
 4758exports.isNullOrUndefined = isNullOrUndefined;
 4759
 4760function isNumber(arg) {
 4761  return typeof arg === 'number';
 4762}
 4763exports.isNumber = isNumber;
 4764
 4765function isString(arg) {
 4766  return typeof arg === 'string';
 4767}
 4768exports.isString = isString;
 4769
 4770function isSymbol(arg) {
 4771  return typeof arg === 'symbol';
 4772}
 4773exports.isSymbol = isSymbol;
 4774
 4775function isUndefined(arg) {
 4776  return arg === void 0;
 4777}
 4778exports.isUndefined = isUndefined;
 4779
 4780function isRegExp(re) {
 4781  return objectToString(re) === '[object RegExp]';
 4782}
 4783exports.isRegExp = isRegExp;
 4784
 4785function isObject(arg) {
 4786  return typeof arg === 'object' && arg !== null;
 4787}
 4788exports.isObject = isObject;
 4789
 4790function isDate(d) {
 4791  return objectToString(d) === '[object Date]';
 4792}
 4793exports.isDate = isDate;
 4794
 4795function isError(e) {
 4796  return (objectToString(e) === '[object Error]' || e instanceof Error);
 4797}
 4798exports.isError = isError;
 4799
 4800function isFunction(arg) {
 4801  return typeof arg === 'function';
 4802}
 4803exports.isFunction = isFunction;
 4804
 4805function isPrimitive(arg) {
 4806  return arg === null ||
 4807         typeof arg === 'boolean' ||
 4808         typeof arg === 'number' ||
 4809         typeof arg === 'string' ||
 4810         typeof arg === 'symbol' ||  // ES6 symbol
 4811         typeof arg === 'undefined';
 4812}
 4813exports.isPrimitive = isPrimitive;
 4814
 4815exports.isBuffer = Buffer.isBuffer;
 4816
 4817function objectToString(o) {
 4818  return Object.prototype.toString.call(o);
 4819}
 4820
 4821}).call(this,{"isBuffer":require("../../insert-module-globals/node_modules/is-buffer/index.js")})
 4822},{"../../insert-module-globals/node_modules/is-buffer/index.js":30}],11:[function(require,module,exports){
 4823// Copyright Joyent, Inc. and other Node contributors.
 4824//
 4825// Permission is hereby granted, free of charge, to any person obtaining a
 4826// copy of this software and associated documentation files (the
 4827// "Software"), to deal in the Software without restriction, including
 4828// without limitation the rights to use, copy, modify, merge, publish,
 4829// distribute, sublicense, and/or sell copies of the Software, and to permit
 4830// persons to whom the Software is furnished to do so, subject to the
 4831// following conditions:
 4832//
 4833// The above copyright notice and this permission notice shall be included
 4834// in all copies or substantial portions of the Software.
 4835//
 4836// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
 4837// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 4838// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
 4839// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 4840// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 4841// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 4842// USE OR OTHER DEALINGS IN THE SOFTWARE.
 4843
 4844var objectCreate = Object.create || objectCreatePolyfill
 4845var objectKeys = Object.keys || objectKeysPolyfill
 4846var bind = Function.prototype.bind || functionBindPolyfill
 4847
 4848function EventEmitter() {
 4849  if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
 4850    this._events = objectCreate(null);
 4851    this._eventsCount = 0;
 4852  }
 4853
 4854  this._maxListeners = this._maxListeners || undefined;
 4855}
 4856module.exports = EventEmitter;
 4857
 4858// Backwards-compat with node 0.10.x
 4859EventEmitter.EventEmitter = EventEmitter;
 4860
 4861EventEmitter.prototype._events = undefined;
 4862EventEmitter.prototype._maxListeners = undefined;
 4863
 4864// By default EventEmitters will print a warning if more than 10 listeners are
 4865// added to it. This is a useful default which helps finding memory leaks.
 4866var defaultMaxListeners = 10;
 4867
 4868var hasDefineProperty;
 4869try {
 4870  var o = {};
 4871  if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
 4872  hasDefineProperty = o.x === 0;
 4873} catch (err) { hasDefineProperty = false }
 4874if (hasDefineProperty) {
 4875  Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
 4876    enumerable: true,
 4877    get: function() {
 4878      return defaultMaxListeners;
 4879    },
 4880    set: function(arg) {
 4881      // check whether the input is a positive number (whose value is zero or
 4882      // greater and not a NaN).
 4883      if (typeof arg !== 'number' || arg < 0 || arg !== arg)
 4884        throw new TypeError('"defaultMaxListeners" must be a positive number');
 4885      defaultMaxListeners = arg;
 4886    }
 4887  });
 4888} else {
 4889  EventEmitter.defaultMaxListeners = defaultMaxListeners;
 4890}
 4891
 4892// Obviously not all Emitters should be limited to 10. This function allows
 4893// that to be increased. Set to zero for unlimited.
 4894EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
 4895  if (typeof n !== 'number' || n < 0 || isNaN(n))
 4896    throw new TypeError('"n" argument must be a positive number');
 4897  this._maxListeners = n;
 4898  return this;
 4899};
 4900
 4901function $getMaxListeners(that) {
 4902  if (that._maxListeners === undefined)
 4903    return EventEmitter.defaultMaxListeners;
 4904  return that._maxListeners;
 4905}
 4906
 4907EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
 4908  return $getMaxListeners(this);
 4909};
 4910
 4911// These standalone emit* functions are used to optimize calling of event
 4912// handlers for fast cases because emit() itself often has a variable number of
 4913// arguments and can be deoptimized because of that. These functions always have
 4914// the same number of arguments and thus do not get deoptimized, so the code
 4915// inside them can execute faster.
 4916function emitNone(handler, isFn, self) {
 4917  if (isFn)
 4918    handler.call(self);
 4919  else {
 4920    var len = handler.length;
 4921    var listeners = arrayClone(handler, len);
 4922    for (var i = 0; i < len; ++i)
 4923      listeners[i].call(self);
 4924  }
 4925}
 4926function emitOne(handler, isFn, self, arg1) {
 4927  if (isFn)
 4928    handler.call(self, arg1);
 4929  else {
 4930    var len = handler.length;
 4931    var listeners = arrayClone(handler, len);
 4932    for (var i = 0; i < len; ++i)
 4933      listeners[i].call(self, arg1);
 4934  }
 4935}
 4936function emitTwo(handler, isFn, self, arg1, arg2) {
 4937  if (isFn)
 4938    handler.call(self, arg1, arg2);
 4939  else {
 4940    var len = handler.length;
 4941    var listeners = arrayClone(handler, len);
 4942    for (var i = 0; i < len; ++i)
 4943      listeners[i].call(self, arg1, arg2);
 4944  }
 4945}
 4946function emitThree(handler, isFn, self, arg1, arg2, arg3) {
 4947  if (isFn)
 4948    handler.call(self, arg1, arg2, arg3);
 4949  else {
 4950    var len = handler.length;
 4951    var listeners = arrayClone(handler, len);
 4952    for (var i = 0; i < len; ++i)
 4953      listeners[i].call(self, arg1, arg2, arg3);
 4954  }
 4955}
 4956
 4957function emitMany(handler, isFn, self, args) {
 4958  if (isFn)
 4959    handler.apply(self, args);
 4960  else {
 4961    var len = handler.length;
 4962    var listeners = arrayClone(handler, len);
 4963    for (var i = 0; i < len; ++i)
 4964      listeners[i].apply(self, args);
 4965  }
 4966}
 4967
 4968EventEmitter.prototype.emit = function emit(type) {
 4969  var er, handler, len, args, i, events;
 4970  var doError = (type === 'error');
 4971
 4972  events = this._events;
 4973  if (events)
 4974    doError = (doError && events.error == null);
 4975  else if (!doError)
 4976    return false;
 4977
 4978  // If there is no 'error' event listener then throw.
 4979  if (doError) {
 4980    if (arguments.length > 1)
 4981      er = arguments[1];
 4982    if (er instanceof Error) {
 4983      throw er; // Unhandled 'error' event
 4984    } else {
 4985      // At least give some kind of context to the user
 4986      var err = new Error('Unhandled "error" event. (' + er + ')');
 4987      err.context = er;
 4988      throw err;
 4989    }
 4990    return false;
 4991  }
 4992
 4993  handler = events[type];
 4994
 4995  if (!handler)
 4996    return false;
 4997
 4998  var isFn = typeof handler === 'function';
 4999  len = arguments.length;
 5000  switch (len) {
 5001      // fast cases
 5002    case 1:
 5003      emitNone(handler, isFn, this);
 5004      break;
 5005    case 2:
 5006      emitOne(handler, isFn, this, arguments[1]);
 5007      break;
 5008    case 3:
 5009      emitTwo(handler, isFn, this, arguments[1], arguments[2]);
 5010      break;
 5011    case 4:
 5012      emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
 5013      break;
 5014      // slower
 5015    default:
 5016      args = new Array(len - 1);
 5017      for (i = 1; i < len; i++)
 5018        args[i - 1] = arguments[i];
 5019      emitMany(handler, isFn, this, args);
 5020  }
 5021
 5022  return true;
 5023};
 5024
 5025function _addListener(target, type, listener, prepend) {
 5026  var m;
 5027  var events;
 5028  var existing;
 5029
 5030  if (typeof listener !== 'function')
 5031    throw new TypeError('"listener" argument must be a function');
 5032
 5033  events = target._events;
 5034  if (!events) {
 5035    events = target._events = objectCreate(null);
 5036    target._eventsCount = 0;
 5037  } else {
 5038    // To avoid recursion in the case that type === "newListener"! Before
 5039    // adding it to the listeners, first emit "newListener".
 5040    if (events.newListener) {
 5041      target.emit('newListener', type,
 5042          listener.listener ? listener.listener : listener);
 5043
 5044      // Re-assign `events` because a newListener handler could have caused the
 5045      // this._events to be assigned to a new object
 5046      events = target._events;
 5047    }
 5048    existing = events[type];
 5049  }
 5050
 5051  if (!existing) {
 5052    // Optimize the case of one listener. Don't need the extra array object.
 5053    existing = events[type] = listener;
 5054    ++target._eventsCount;
 5055  } else {
 5056    if (typeof existing === 'function') {
 5057      // Adding the second element, need to change to array.
 5058      existing = events[type] =
 5059          prepend ? [listener, existing] : [existing, listener];
 5060    } else {
 5061      // If we've already got an array, just append.
 5062      if (prepend) {
 5063        existing.unshift(listener);
 5064      } else {
 5065        existing.push(listener);
 5066      }
 5067    }
 5068
 5069    // Check for listener leak
 5070    if (!existing.warned) {
 5071      m = $getMaxListeners(target);
 5072      if (m && m > 0 && existing.length > m) {
 5073        existing.warned = true;
 5074        var w = new Error('Possible EventEmitter memory leak detected. ' +
 5075            existing.length + ' "' + String(type) + '" listeners ' +
 5076            'added. Use emitter.setMaxListeners() to ' +
 5077            'increase limit.');
 5078        w.name = 'MaxListenersExceededWarning';
 5079        w.emitter = target;
 5080        w.type = type;
 5081        w.count = existing.length;
 5082        if (typeof console === 'object' && console.warn) {
 5083          console.warn('%s: %s', w.name, w.message);
 5084        }
 5085      }
 5086    }
 5087  }
 5088
 5089  return target;
 5090}
 5091
 5092EventEmitter.prototype.addListener = function addListener(type, listener) {
 5093  return _addListener(this, type, listener, false);
 5094};
 5095
 5096EventEmitter.prototype.on = EventEmitter.prototype.addListener;
 5097
 5098EventEmitter.prototype.prependListener =
 5099    function prependListener(type, listener) {
 5100      return _addListener(this, type, listener, true);
 5101    };
 5102
 5103function onceWrapper() {
 5104  if (!this.fired) {
 5105    this.target.removeListener(this.type, this.wrapFn);
 5106    this.fired = true;
 5107    switch (arguments.length) {
 5108      case 0:
 5109        return this.listener.call(this.target);
 5110      case 1:
 5111        return this.listener.call(this.target, arguments[0]);
 5112      case 2:
 5113        return this.listener.call(this.target, arguments[0], arguments[1]);
 5114      case 3:
 5115        return this.listener.call(this.target, arguments[0], arguments[1],
 5116            arguments[2]);
 5117      default:
 5118        var args = new Array(arguments.length);
 5119        for (var i = 0; i < args.length; ++i)
 5120          args[i] = arguments[i];
 5121        this.listener.apply(this.target, args);
 5122    }
 5123  }
 5124}
 5125
 5126function _onceWrap(target, type, listener) {
 5127  var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
 5128  var wrapped = bind.call(onceWrapper, state);
 5129  wrapped.listener = listener;
 5130  state.wrapFn = wrapped;
 5131  return wrapped;
 5132}
 5133
 5134EventEmitter.prototype.once = function once(type, listener) {
 5135  if (typeof listener !== 'function')
 5136    throw new TypeError('"listener" argument must be a function');
 5137  this.on(type, _onceWrap(this, type, listener));
 5138  return this;
 5139};
 5140
 5141EventEmitter.prototype.prependOnceListener =
 5142    function prependOnceListener(type, listener) {
 5143      if (typeof listener !== 'function')
 5144        throw new TypeError('"listener" argument must be a function');
 5145      this.prependListener(type, _onceWrap(this, type, listener));
 5146      return this;
 5147    };
 5148
 5149// Emits a 'removeListener' event if and only if the listener was removed.
 5150EventEmitter.prototype.removeListener =
 5151    function removeListener(type, listener) {
 5152      var list, events, position, i, originalListener;
 5153
 5154      if (typeof listener !== 'function')
 5155        throw new TypeError('"listener" argument must be a function');
 5156
 5157      events = this._events;
 5158      if (!events)
 5159        return this;
 5160
 5161      list = events[type];
 5162      if (!list)
 5163        return this;
 5164
 5165      if (list === listener || list.listener === listener) {
 5166        if (--this._eventsCount === 0)
 5167          this._events = objectCreate(null);
 5168        else {
 5169          delete events[type];
 5170          if (events.removeListener)
 5171            this.emit('removeListener', type, list.listener || listener);
 5172        }
 5173      } else if (typeof list !== 'function') {
 5174        position = -1;
 5175
 5176        for (i = list.length - 1; i >= 0; i--) {
 5177          if (list[i] === listener || list[i].listener === listener) {
 5178            originalListener = list[i].listener;
 5179            position = i;
 5180            break;
 5181          }
 5182        }
 5183
 5184        if (position < 0)
 5185          return this;
 5186
 5187        if (position === 0)
 5188          list.shift();
 5189        else
 5190          spliceOne(list, position);
 5191
 5192        if (list.length === 1)
 5193          events[type] = list[0];
 5194
 5195        if (events.removeListener)
 5196          this.emit('removeListener', type, originalListener || listener);
 5197      }
 5198
 5199      return this;
 5200    };
 5201
 5202EventEmitter.prototype.removeAllListeners =
 5203    function removeAllListeners(type) {
 5204      var listeners, events, i;
 5205
 5206      events = this._events;
 5207      if (!events)
 5208        return this;
 5209
 5210      // not listening for removeListener, no need to emit
 5211      if (!events.removeListener) {
 5212        if (arguments.length === 0) {
 5213          this._events = objectCreate(null);
 5214          this._eventsCount = 0;
 5215        } else if (events[type]) {
 5216          if (--this._eventsCount === 0)
 5217            this._events = objectCreate(null);
 5218          else
 5219            delete events[type];
 5220        }
 5221        return this;
 5222      }
 5223
 5224      // emit removeListener for all listeners on all events
 5225      if (arguments.length === 0) {
 5226        var keys = objectKeys(events);
 5227        var key;
 5228        for (i = 0; i < keys.length; ++i) {
 5229          key = keys[i];
 5230          if (key === 'removeListener') continue;
 5231          this.removeAllListeners(key);
 5232        }
 5233        this.removeAllListeners('removeListener');
 5234        this._events = objectCreate(null);
 5235        this._eventsCount = 0;
 5236        return this;
 5237      }
 5238
 5239      listeners = events[type];
 5240
 5241      if (typeof listeners === 'function') {
 5242        this.removeListener(type, listeners);
 5243      } else if (listeners) {
 5244        // LIFO order
 5245        for (i = listeners.length - 1; i >= 0; i--) {
 5246          this.removeListener(type, listeners[i]);
 5247        }
 5248      }
 5249
 5250      return this;
 5251    };
 5252
 5253function _listeners(target, type, unwrap) {
 5254  var events = target._events;
 5255
 5256  if (!events)
 5257    return [];
 5258
 5259  var evlistener = events[type];
 5260  if (!evlistener)
 5261    return [];
 5262
 5263  if (typeof evlistener === 'function')
 5264    return unwrap ? [evlistener.listener || evlistener] : [evlistener];
 5265
 5266  return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
 5267}
 5268
 5269EventEmitter.prototype.listeners = function listeners(type) {
 5270  return _listeners(this, type, true);
 5271};
 5272
 5273EventEmitter.prototype.rawListeners = function rawListeners(type) {
 5274  return _listeners(this, type, false);
 5275};
 5276
 5277EventEmitter.listenerCount = function(emitter, type) {
 5278  if (typeof emitter.listenerCount === 'function') {
 5279    return emitter.listenerCount(type);
 5280  } else {
 5281    return listenerCount.call(emitter, type);
 5282  }
 5283};
 5284
 5285EventEmitter.prototype.listenerCount = listenerCount;
 5286function listenerCount(type) {
 5287  var events = this._events;
 5288
 5289  if (events) {
 5290    var evlistener = events[type];
 5291
 5292    if (typeof evlistener === 'function') {
 5293      return 1;
 5294    } else if (evlistener) {
 5295      return evlistener.length;
 5296    }
 5297  }
 5298
 5299  return 0;
 5300}
 5301
 5302EventEmitter.prototype.eventNames = function eventNames() {
 5303  return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
 5304};
 5305
 5306// About 1.5x faster than the two-arg version of Array#splice().
 5307function spliceOne(list, index) {
 5308  for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
 5309    list[i] = list[k];
 5310  list.pop();
 5311}
 5312
 5313function arrayClone(arr, n) {
 5314  var copy = new Array(n);
 5315  for (var i = 0; i < n; ++i)
 5316    copy[i] = arr[i];
 5317  return copy;
 5318}
 5319
 5320function unwrapListeners(arr) {
 5321  var ret = new Array(arr.length);
 5322  for (var i = 0; i < ret.length; ++i) {
 5323    ret[i] = arr[i].listener || arr[i];
 5324  }
 5325  return ret;
 5326}
 5327
 5328function objectCreatePolyfill(proto) {
 5329  var F = function() {};
 5330  F.prototype = proto;
 5331  return new F;
 5332}
 5333function objectKeysPolyfill(obj) {
 5334  var keys = [];
 5335  for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
 5336    keys.push(k);
 5337  }
 5338  return k;
 5339}
 5340function functionBindPolyfill(context) {
 5341  var fn = this;
 5342  return function () {
 5343    return fn.apply(context, arguments);
 5344  };
 5345}
 5346
 5347},{}],12:[function(require,module,exports){
 5348
 5349exports.Scalar = require("./src/scalar");
 5350exports.PolField = require("./src/polfield.js");
 5351exports.F1Field = require("./src/f1field");
 5352exports.F2Field = require("./src/f2field");
 5353exports.F3Field = require("./src/f3field");
 5354
 5355exports.ZqField = exports.F1Field;
 5356
 5357exports.EC = require("./src/ec");
 5358
 5359exports.bn128 = require("./src/bn128.js");
 5360
 5361exports.utils = require("./src/utils");
 5362
 5363
 5364
 5365},{"./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){
 5366/*
 5367    Copyright 2018 0kims association.
 5368
 5369    This file is part of snarkjs.
 5370
 5371    snarkjs is a free software: you can redistribute it and/or
 5372    modify it under the terms of the GNU General Public License as published by the
 5373    Free Software Foundation, either version 3 of the License, or (at your option)
 5374    any later version.
 5375
 5376    snarkjs is distributed in the hope that it will be useful,
 5377    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 5378    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 5379    more details.
 5380
 5381    You should have received a copy of the GNU General Public License along with
 5382    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 5383*/
 5384
 5385const Scalar = require("./scalar");
 5386const F1Field = require("./f1field");
 5387const F2Field = require("./f2field");
 5388const F3Field = require("./f3field");
 5389const EC = require("./ec.js");
 5390
 5391class BN128 {
 5392
 5393    constructor() {
 5394
 5395        this.q = Scalar.fromString("21888242871839275222246405745257275088696311157297823662689037894645226208583");
 5396        this.r = Scalar.fromString("21888242871839275222246405745257275088548364400416034343698204186575808495617");
 5397
 5398
 5399        this.F1 = new F1Field(this.q);
 5400        this.nonResidueF2 = this.F1.e("21888242871839275222246405745257275088696311157297823662689037894645226208582");
 5401
 5402        this.F2 = new F2Field(this.F1, this.nonResidueF2);
 5403        this.g1 = [ this.F1.e(1), this.F1.e(2), this.F1.e(1)];
 5404        this.g2 = [
 5405            [
 5406                this.F1.e("10857046999023057135944570762232829481370756359578518086990519993285655852781"),
 5407                this.F1.e("11559732032986387107991004021392285783925812861821192530917403151452391805634")
 5408            ],
 5409            [
 5410                this.F1.e("8495653923123431417604973247489272438418190587263600148770280649306958101930"),
 5411                this.F1.e("4082367875863433681332203403145435568316851327593401208105741076214120093531")
 5412            ],
 5413            [
 5414                this.F1.e("1"),
 5415                this.F1.e("0")
 5416            ]
 5417        ];
 5418        this.G1 = new EC(this.F1, this.g1);
 5419        this.G2 = new EC(this.F2, this.g2);
 5420
 5421        this.nonResidueF6 = [ this.F1.e("9"), this.F1.e("1") ];
 5422
 5423        this.F6 = new F3Field(this.F2, this.nonResidueF6);
 5424        this.F12 = new F2Field(this.F6, this.nonResidueF6);
 5425        this.Fr = new F1Field(this.r);
 5426
 5427
 5428
 5429        const self = this;
 5430        this.F12._mulByNonResidue = function(a) {
 5431            return [self.F2.mul(this.nonResidue, a[2]), a[0], a[1]];
 5432        };
 5433
 5434        this._preparePairing();
 5435
 5436    }
 5437
 5438    _preparePairing() {
 5439        this.loopCount = Scalar.fromString("29793968203157093288");// CONSTANT
 5440
 5441        // Set loopCountNeg
 5442        if (Scalar.isNegative(this.loopCount)) {
 5443            this.loopCount = this.loopCount.neg();
 5444            this.loopCountNeg = true;
 5445        } else {
 5446            this.loopCountNeg = false;
 5447        }
 5448
 5449        // Set loop_count_bits
 5450        let lc = this.loopCount;
 5451        this.loop_count_bits = []; // Constant
 5452        while (!Scalar.isZero(lc)) {
 5453            this.loop_count_bits.push( Scalar.isOdd(lc) );
 5454            lc = Scalar.shiftRight(lc, 1);
 5455        }
 5456
 5457        this.two_inv = this.F1.inv(this.F1.e(2));
 5458
 5459        this.coef_b = this.F1.e(3);
 5460        this.twist = [this.F1.e(9) , this.F1.e(1)];
 5461        this.twist_coeff_b = this.F2.mulScalar(  this.F2.inv(this.twist), this.coef_b  );
 5462
 5463        this.frobenius_coeffs_c1_1 = this.F1.e("21888242871839275222246405745257275088696311157297823662689037894645226208582");
 5464        this.twist_mul_by_q_X =
 5465            [
 5466                this.F1.e("21575463638280843010398324269430826099269044274347216827212613867836435027261"),
 5467                this.F1.e("10307601595873709700152284273816112264069230130616436755625194854815875713954")
 5468            ];
 5469        this.twist_mul_by_q_Y =
 5470            [
 5471                this.F1.e("2821565182194536844548159561693502659359617185244120367078079554186484126554"),
 5472                this.F1.e("3505843767911556378687030309984248845540243509899259641013678093033130930403")
 5473            ];
 5474
 5475        this.final_exponent = Scalar.fromString("552484233613224096312617126783173147097382103762957654188882734314196910839907541213974502761540629817009608548654680343627701153829446747810907373256841551006201639677726139946029199968412598804882391702273019083653272047566316584365559776493027495458238373902875937659943504873220554161550525926302303331747463515644711876653177129578303191095900909191624817826566688241804408081892785725967931714097716709526092261278071952560171111444072049229123565057483750161460024353346284167282452756217662335528813519139808291170539072125381230815729071544861602750936964829313608137325426383735122175229541155376346436093930287402089517426973178917569713384748081827255472576937471496195752727188261435633271238710131736096299798168852925540549342330775279877006784354801422249722573783561685179618816480037695005515426162362431072245638324744480");
 5476
 5477    }
 5478
 5479
 5480    pairing(p1, p2) {
 5481
 5482        const pre1 = this.precomputeG1(p1);
 5483        const pre2 = this.precomputeG2(p2);
 5484
 5485        const r1 = this.millerLoop(pre1, pre2);
 5486
 5487        const res = this.finalExponentiation(r1);
 5488
 5489        return res;
 5490    }
 5491
 5492
 5493    precomputeG1(p) {
 5494        const Pcopy = this.G1.affine(p);
 5495
 5496        const res = {};
 5497        res.PX = Pcopy[0];
 5498        res.PY = Pcopy[1];
 5499
 5500        return res;
 5501    }
 5502
 5503    precomputeG2(p) {
 5504
 5505        const Qcopy = this.G2.affine(p);
 5506
 5507        const res = {
 5508            QX: Qcopy[0],
 5509            QY: Qcopy[1],
 5510            coeffs: []
 5511        };
 5512
 5513        const R = {
 5514            X: Qcopy[0],
 5515            Y: Qcopy[1],
 5516            Z: this.F2.one
 5517        };
 5518
 5519        let c;
 5520
 5521        for (let i = this.loop_count_bits.length-2; i >= 0; --i)
 5522        {
 5523            const bit = this.loop_count_bits[i];
 5524
 5525            c = this._doubleStep(R);
 5526            res.coeffs.push(c);
 5527
 5528            if (bit)
 5529            {
 5530                c = this._addStep(Qcopy, R);
 5531                res.coeffs.push(c);
 5532            }
 5533        }
 5534
 5535        const Q1 = this.G2.affine(this._g2MulByQ(Qcopy));
 5536        if (!this.F2.eq(Q1[2], this.F2.one))
 5537        {
 5538            throw new Error("Expected values are not equal");
 5539        }
 5540        const Q2 = this.G2.affine(this._g2MulByQ(Q1));
 5541        if (!this.F2.eq(Q2[2], this.F2.one))
 5542        {
 5543            throw new Error("Expected values are not equal");
 5544        }
 5545
 5546        if (this.loopCountNeg)
 5547        {
 5548            R.Y = this.F2.neg(R.Y);
 5549        }
 5550        Q2[1] = this.F2.neg(Q2[1]);
 5551
 5552        c = this._addStep(Q1, R);
 5553        res.coeffs.push(c);
 5554
 5555        c = this._addStep(Q2, R);
 5556        res.coeffs.push(c);
 5557
 5558        return res;
 5559    }
 5560
 5561    millerLoop(pre1, pre2) {
 5562        let f = this.F12.one;
 5563
 5564        let idx = 0;
 5565
 5566        let c;
 5567
 5568        for (let i = this.loop_count_bits.length-2; i >= 0; --i)
 5569        {
 5570            const bit = this.loop_count_bits[i];
 5571
 5572            /* code below gets executed for all bits (EXCEPT the MSB itself) of
 5573               alt_bn128_param_p (skipping leading zeros) in MSB to LSB
 5574               order */
 5575
 5576            c = pre2.coeffs[idx++];
 5577            f = this.F12.square(f);
 5578            f = this._mul_by_024(
 5579                f,
 5580                c.ell_0,
 5581                this.F2.mulScalar(c.ell_VW , pre1.PY),
 5582                this.F2.mulScalar(c.ell_VV , pre1.PX));
 5583
 5584            if (bit)
 5585            {
 5586                c = pre2.coeffs[idx++];
 5587                f = this._mul_by_024(
 5588                    f,
 5589                    c.ell_0,
 5590                    this.F2.mulScalar(c.ell_VW, pre1.PY),
 5591                    this.F2.mulScalar(c.ell_VV, pre1.PX));
 5592            }
 5593
 5594        }
 5595
 5596        if (this.loopCountNeg)
 5597        {
 5598            f = this.F12.inverse(f);
 5599        }
 5600
 5601        c = pre2.coeffs[idx++];
 5602        f = this._mul_by_024(
 5603            f,
 5604            c.ell_0,
 5605            this.F2.mulScalar(c.ell_VW, pre1.PY),
 5606            this.F2.mulScalar(c.ell_VV, pre1.PX));
 5607
 5608        c = pre2.coeffs[idx++];
 5609        f = this._mul_by_024(
 5610            f,
 5611            c.ell_0,
 5612            this.F2.mulScalar(c.ell_VW, pre1.PY),
 5613            this.F2.mulScalar(c.ell_VV, pre1.PX));
 5614
 5615        return f;
 5616    }
 5617
 5618    finalExponentiation(elt) {
 5619        // TODO: There is an optimization in FF
 5620
 5621        const res = this.F12.exp(elt,this.final_exponent);
 5622
 5623        return res;
 5624    }
 5625
 5626    _doubleStep(current) {
 5627        const X = current.X;
 5628        const Y = current.Y;
 5629        const Z = current.Z;
 5630
 5631        const A = this.F2.mulScalar(this.F2.mul(X,Y), this.two_inv);                     // A = X1 * Y1 / 2
 5632        const B = this.F2.square(Y);                           // B = Y1^2
 5633        const C = this.F2.square(Z);                           // C = Z1^2
 5634        const D = this.F2.add(C, this.F2.add(C,C));            // D = 3 * C
 5635        const E = this.F2.mul(this.twist_coeff_b, D);     // E = twist_b * D
 5636        const F = this.F2.add(E, this.F2.add(E,E));            // F = 3 * E
 5637        const G =
 5638            this.F2.mulScalar(
 5639                this.F2.add( B , F ),
 5640                this.two_inv);                            // G = (B+F)/2
 5641        const H =
 5642            this.F2.sub(
 5643                this.F2.square( this.F2.add(Y,Z) ),
 5644                this.F2.add( B , C));                          // H = (Y1+Z1)^2-(B+C)
 5645        const I = this.F2.sub(E, B);                           // I = E-B
 5646        const J = this.F2.square(X);                           // J = X1^2
 5647        const E_squared = this.F2.square(E);                   // E_squared = E^2
 5648
 5649        current.X = this.F2.mul( A, this.F2.sub(B,F) );        // X3 = A * (B-F)
 5650        current.Y =
 5651            this.F2.sub(
 5652                this.F2.sub( this.F2.square(G) , E_squared ),
 5653                this.F2.add( E_squared , E_squared ));         // Y3 = G^2 - 3*E^2
 5654        current.Z = this.F2.mul( B, H );                       // Z3 = B * H
 5655
 5656        const c = {
 5657            ell_0 : this.F2.mul( I, this.twist),          // ell_0 = xi * I
 5658            ell_VW: this.F2.neg( H ),                          // ell_VW = - H (later: * yP)
 5659            ell_VV: this.F2.add( J , this.F2.add(J,J) )        // ell_VV = 3*J (later: * xP)
 5660        };
 5661
 5662        return c;
 5663    }
 5664
 5665    _addStep(base, current) {
 5666
 5667        const X1 = current.X;
 5668        const Y1 = current.Y;
 5669        const Z1 = current.Z;
 5670        const x2 = base[0];
 5671        const y2 = base[1];
 5672
 5673        const D = this.F2.sub( X1, this.F2.mul(x2,Z1) );  // D = X1 - X2*Z1
 5674
 5675//        console.log("Y: "+ A[0].affine(this.q).toString(16));
 5676
 5677        const E = this.F2.sub( Y1, this.F2.mul(y2,Z1) );  // E = Y1 - Y2*Z1
 5678        const F = this.F2.square(D);                      // F = D^2
 5679        const G = this.F2.square(E);                      // G = E^2
 5680        const H = this.F2.mul(D,F);                       // H = D*F
 5681        const I = this.F2.mul(X1,F);                      // I = X1 * F
 5682        const J =
 5683            this.F2.sub(
 5684                this.F2.add( H, this.F2.mul(Z1,G) ),
 5685                this.F2.add( I, I ));                     // J = H + Z1*G - (I+I)
 5686
 5687        current.X = this.F2.mul( D , J );                 // X3 = D*J
 5688        current.Y =
 5689            this.F2.sub(
 5690                this.F2.mul( E , this.F2.sub(I,J) ),
 5691                this.F2.mul( H , Y1));                    // Y3 = E*(I-J)-(H*Y1)
 5692        current.Z = this.F2.mul(Z1,H);
 5693        const c = {
 5694            ell_0 :
 5695                this.F2.mul(
 5696                    this.twist,
 5697                    this.F2.sub(
 5698                        this.F2.mul(E , x2),
 5699                        this.F2.mul(D , y2))),            // ell_0 = xi * (E * X2 - D * Y2)
 5700            ell_VV : this.F2.neg(E),                      // ell_VV = - E (later: * xP)
 5701            ell_VW : D                                    // ell_VW = D (later: * yP )
 5702        };
 5703
 5704        return c;
 5705    }
 5706
 5707    _mul_by_024(a, ell_0, ell_VW, ell_VV) {
 5708
 5709        //  Old implementation
 5710/*
 5711        const b = [
 5712            [ell_0, this.F2.zero, ell_VV],
 5713            [this.F2.zero, ell_VW, this.F2.zero]
 5714        ];
 5715
 5716        return this.F12.mul(a,b);
 5717*/
 5718
 5719        // This is a new implementation,
 5720        //  But it does not look worthy
 5721        //  at least in javascript.
 5722
 5723        let z0 = a[0][0];
 5724        let z1 = a[0][1];
 5725        let z2 = a[0][2];
 5726        let z3 = a[1][0];
 5727        let z4 = a[1][1];
 5728        let z5 = a[1][2];
 5729
 5730        const x0 = ell_0;
 5731        const x2 = ell_VV;
 5732        const x4 = ell_VW;
 5733
 5734        const D0 = this.F2.mul(z0, x0);
 5735        const D2 = this.F2.mul(z2, x2);
 5736        const D4 = this.F2.mul(z4, x4);
 5737        const t2 = this.F2.add(z0, z4);
 5738        let t1 = this.F2.add(z0, z2);
 5739        const s0 = this.F2.add(this.F2.add(z1,z3),z5);
 5740
 5741        // For z.a_.a_ = z0.
 5742        let S1 = this.F2.mul(z1, x2);
 5743        let T3 = this.F2.add(S1, D4);
 5744        let T4 = this.F2.add( this.F2.mul(this.nonResidueF6, T3),D0);
 5745        z0 = T4;
 5746
 5747        // For z.a_.b_ = z1
 5748        T3 = this.F2.mul(z5, x4);
 5749        S1 = this.F2.add(S1, T3);
 5750        T3 = this.F2.add(T3, D2);
 5751        T4 = this.F2.mul(this.nonResidueF6, T3);
 5752        T3 = this.F2.mul(z1, x0);
 5753        S1 = this.F2.add(S1, T3);
 5754        T4 = this.F2.add(T4, T3);
 5755        z1 = T4;
 5756
 5757        // For z.a_.c_ = z2
 5758        let t0 = this.F2.add(x0, x2);
 5759        T3 = this.F2.sub(
 5760            this.F2.mul(t1, t0),
 5761            this.F2.add(D0, D2));
 5762        T4 = this.F2.mul(z3, x4);
 5763        S1 = this.F2.add(S1, T4);
 5764
 5765        // For z.b_.a_ = z3 (z3 needs z2)
 5766        t0 = this.F2.add(z2, z4);
 5767        z2 = this.F2.add(T3, T4);
 5768        t1 = this.F2.add(x2, x4);
 5769        T3 = this.F2.sub(
 5770            this.F2.mul(t0,t1),
 5771            this.F2.add(D2, D4));
 5772
 5773        T4 = this.F2.mul(this.nonResidueF6,  T3);
 5774        T3 = this.F2.mul(z3, x0);
 5775        S1 = this.F2.add(S1, T3);
 5776        T4 = this.F2.add(T4, T3);
 5777        z3 = T4;
 5778
 5779        // For z.b_.b_ = z4
 5780        T3 = this.F2.mul(z5, x2);
 5781        S1 = this.F2.add(S1, T3);
 5782        T4 = this.F2.mul(this.nonResidueF6, T3);
 5783        t0 = this.F2.add(x0, x4);
 5784        T3 = this.F2.sub(
 5785            this.F2.mul(t2,t0),
 5786            this.F2.add(D0, D4));
 5787        T4 = this.F2.add(T4, T3);
 5788        z4 = T4;
 5789
 5790        // For z.b_.c_ = z5.
 5791        t0 = this.F2.add(this.F2.add(x0, x2), x4);
 5792        T3 = this.F2.sub(this.F2.mul(s0, t0), S1);
 5793        z5 = T3;
 5794
 5795        return [
 5796            [z0, z1, z2],
 5797            [z3, z4, z5]
 5798        ];
 5799
 5800
 5801    }
 5802
 5803    _g2MulByQ(p) {
 5804        const fmx = [p[0][0], this.F1.mul(p[0][1], this.frobenius_coeffs_c1_1 )];
 5805        const fmy = [p[1][0], this.F1.mul(p[1][1], this.frobenius_coeffs_c1_1 )];
 5806        const fmz = [p[2][0], this.F1.mul(p[2][1], this.frobenius_coeffs_c1_1 )];
 5807        return [
 5808            this.F2.mul(this.twist_mul_by_q_X , fmx),
 5809            this.F2.mul(this.twist_mul_by_q_Y , fmy),
 5810            fmz
 5811        ];
 5812    }
 5813}
 5814
 5815module.exports = new BN128();
 5816
 5817},{"./ec.js":14,"./f1field":15,"./f2field":18,"./f3field":19,"./scalar":22}],14:[function(require,module,exports){
 5818/*
 5819    Copyright 2018 0kims association.
 5820
 5821    This file is part of snarkjs.
 5822
 5823    snarkjs is a free software: you can redistribute it and/or
 5824    modify it under the terms of the GNU General Public License as published by the
 5825    Free Software Foundation, either version 3 of the License, or (at your option)
 5826    any later version.
 5827
 5828    snarkjs is distributed in the hope that it will be useful,
 5829    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 5830    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 5831    more details.
 5832
 5833    You should have received a copy of the GNU General Public License along with
 5834    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 5835*/
 5836
 5837const fUtils = require("./futils.js");
 5838
 5839class EC {
 5840
 5841    constructor(F, g) {
 5842        this.F = F;
 5843        this.g = g;
 5844        if (this.g.length == 2) this.g[2] = this.F.one;
 5845        this.zero = [this.F.zero, this.F.one, this.F.zero];
 5846    }
 5847
 5848    add(p1, p2) {
 5849
 5850        const F = this.F;
 5851
 5852        if (this.eq(p1, this.zero)) return p2;
 5853        if (this.eq(p2, this.zero)) return p1;
 5854
 5855        const res = new Array(3);
 5856
 5857        const Z1Z1 = F.square( p1[2] );
 5858        const Z2Z2 = F.square( p2[2] );
 5859
 5860        const U1 = F.mul( p1[0] , Z2Z2 );     // U1 = X1  * Z2Z2
 5861        const U2 = F.mul( p2[0] , Z1Z1 );     // U2 = X2  * Z1Z1
 5862
 5863        const Z1_cubed = F.mul( p1[2] , Z1Z1);
 5864        const Z2_cubed = F.mul( p2[2] , Z2Z2);
 5865
 5866        const S1 = F.mul( p1[1] , Z2_cubed);  // S1 = Y1 * Z2 * Z2Z2
 5867        const S2 = F.mul( p2[1] , Z1_cubed);  // S2 = Y2 * Z1 * Z1Z1
 5868
 5869        if (F.eq(U1,U2) && F.eq(S1,S2)) {
 5870            return this.double(p1);
 5871        }
 5872
 5873        const H = F.sub( U2 , U1 );                    // H = U2-U1
 5874
 5875        const S2_minus_S1 = F.sub( S2 , S1 );
 5876
 5877        const I = F.square( F.add(H,H) );         // I = (2 * H)^2
 5878        const J = F.mul( H , I );                      // J = H * I
 5879
 5880        const r = F.add( S2_minus_S1 , S2_minus_S1 );  // r = 2 * (S2-S1)
 5881        const V = F.mul( U1 , I );                     // V = U1 * I
 5882
 5883        res[0] =
 5884            F.sub(
 5885                F.sub( F.square(r) , J ),
 5886                F.add( V , V ));                       // X3 = r^2 - J - 2 * V
 5887
 5888        const S1_J = F.mul( S1 , J );
 5889
 5890        res[1] =
 5891            F.sub(
 5892                F.mul( r , F.sub(V,res[0])),
 5893                F.add( S1_J,S1_J ));                   // Y3 = r * (V-X3)-2 S1 J
 5894
 5895        res[2] =
 5896            F.mul(
 5897                H,
 5898                F.sub(
 5899                    F.square( F.add(p1[2],p2[2]) ),
 5900                    F.add( Z1Z1 , Z2Z2 )));            // Z3 = ((Z1+Z2)^2-Z1Z1-Z2Z2) * H
 5901
 5902        return res;
 5903    }
 5904
 5905    neg(p) {
 5906        return [p[0], this.F.neg(p[1]), p[2]];
 5907    }
 5908
 5909    sub(a, b) {
 5910        return this.add(a, this.neg(b));
 5911    }
 5912
 5913    double(p) {
 5914        const F = this.F;
 5915
 5916        const res = new Array(3);
 5917
 5918        if (this.eq(p, this.zero)) return p;
 5919
 5920        const A = F.square( p[0] );                    // A = X1^2
 5921        const B = F.square( p[1] );                    // B = Y1^2
 5922        const C = F.square( B );                       // C = B^2
 5923
 5924        let D =
 5925            F.sub(
 5926                F.square( F.add(p[0] , B )),
 5927                F.add( A , C));
 5928        D = F.add(D,D);                    // D = 2 * ((X1 + B)^2 - A - C)
 5929
 5930        const E = F.add( F.add(A,A), A);          // E = 3 * A
 5931        const FF =F.square( E );                       // F = E^2
 5932
 5933        res[0] = F.sub( FF , F.add(D,D) );         // X3 = F - 2 D
 5934
 5935        let eightC = F.add( C , C );
 5936        eightC = F.add( eightC , eightC );
 5937        eightC = F.add( eightC , eightC );
 5938
 5939        res[1] =
 5940            F.sub(
 5941                F.mul(
 5942                    E,
 5943                    F.sub( D, res[0] )),
 5944                eightC);                                    // Y3 = E * (D - X3) - 8 * C
 5945
 5946        const Y1Z1 = F.mul( p[1] , p[2] );
 5947        res[2] = F.add( Y1Z1 , Y1Z1 );                 // Z3 = 2 * Y1 * Z1
 5948
 5949        return res;
 5950    }
 5951
 5952    mulScalar(base, e) {
 5953        return fUtils.mulScalar(this, base, e);
 5954    }
 5955
 5956    affine(p) {
 5957        const F = this.F;
 5958        if (this.eq(p, this.zero)) {
 5959            return this.zero;
 5960        } else {
 5961            const Z_inv = F.inv(p[2]);
 5962            const Z2_inv = F.square(Z_inv);
 5963            const Z3_inv = F.mul(Z2_inv, Z_inv);
 5964
 5965            const res = new Array(3);
 5966            res[0] = F.mul(p[0],Z2_inv);
 5967            res[1] = F.mul(p[1],Z3_inv);
 5968            res[2] = F.one;
 5969
 5970            return res;
 5971        }
 5972    }
 5973
 5974    multiAffine(arr) {
 5975        const keys = Object.keys(arr);
 5976        const F = this.F;
 5977        const accMul = new Array(keys.length+1);
 5978        accMul[0] = F.one;
 5979        for (let i = 0; i< keys.length; i++) {
 5980            if (F.eq(arr[keys[i]][2], F.zero)) {
 5981                accMul[i+1] = accMul[i];
 5982            } else {
 5983                accMul[i+1] = F.mul(accMul[i], arr[keys[i]][2]);
 5984            }
 5985        }
 5986
 5987        accMul[keys.length] = F.inv(accMul[keys.length]);
 5988
 5989        for (let i = keys.length-1; i>=0; i--) {
 5990            if (F.eq(arr[keys[i]][2], F.zero)) {
 5991                accMul[i] = accMul[i+1];
 5992                arr[keys[i]] = this.zero;
 5993            } else {
 5994                const Z_inv = F.mul(accMul[i], accMul[i+1]);
 5995                accMul[i] = F.mul(arr[keys[i]][2], accMul[i+1]);
 5996
 5997                const Z2_inv = F.square(Z_inv);
 5998                const Z3_inv = F.mul(Z2_inv, Z_inv);
 5999
 6000                arr[keys[i]][0] = F.mul(arr[keys[i]][0],Z2_inv);
 6001                arr[keys[i]][1] = F.mul(arr[keys[i]][1],Z3_inv);
 6002                arr[keys[i]][2] = F.one;
 6003            }
 6004        }
 6005
 6006    }
 6007
 6008    eq(p1, p2) {
 6009        const F = this.F;
 6010
 6011        if (this.F.eq(p1[2], this.F.zero)) return this.F.eq(p2[2], this.F.zero);
 6012        if (this.F.eq(p2[2], this.F.zero)) return false;
 6013
 6014        const Z1Z1 = F.square( p1[2] );
 6015        const Z2Z2 = F.square( p2[2] );
 6016
 6017        const U1 = F.mul( p1[0] , Z2Z2 );
 6018        const U2 = F.mul( p2[0] , Z1Z1 );
 6019
 6020        const Z1_cubed = F.mul( p1[2] , Z1Z1);
 6021        const Z2_cubed = F.mul( p2[2] , Z2Z2);
 6022
 6023        const S1 = F.mul( p1[1] , Z2_cubed);
 6024        const S2 = F.mul( p2[1] , Z1_cubed);
 6025
 6026        return (F.eq(U1,U2) && F.eq(S1,S2));
 6027    }
 6028
 6029    toString(p) {
 6030        const cp = this.affine(p);
 6031        return `[ ${this.F.toString(cp[0])} , ${this.F.toString(cp[1])} ]`;
 6032    }
 6033
 6034}
 6035
 6036module.exports = EC;
 6037
 6038
 6039},{"./futils.js":20}],15:[function(require,module,exports){
 6040const supportsNativeBigInt = typeof BigInt === "function";
 6041if (supportsNativeBigInt) {
 6042    module.exports = require("./f1field_native");
 6043} else {
 6044    module.exports = require("./f1field_bigint");
 6045}
 6046
 6047},{"./f1field_bigint":16,"./f1field_native":17}],16:[function(require,module,exports){
 6048const bigInt = require("big-integer");
 6049const assert = require("assert");
 6050
 6051function getRandomByte() {
 6052    if (typeof window !== "undefined") { // Browser
 6053        if (typeof window.crypto !== "undefined") { // Supported
 6054            let array = new Uint8Array(1);
 6055            window.crypto.getRandomValues(array);
 6056            return array[0];
 6057        }
 6058        else { // fallback
 6059            return Math.floor(Math.random() * 256);
 6060        }
 6061    }
 6062    else { // NodeJS
 6063        return module.require("crypto").randomBytes(1)[0];
 6064    }
 6065}
 6066
 6067module.exports = class ZqField {
 6068    constructor(p) {
 6069        this.one = bigInt.one;
 6070        this.zero = bigInt.zero;
 6071        this.p = bigInt(p);
 6072        this.minusone = this.p.minus(bigInt.one);
 6073        this.two = bigInt(2);
 6074        this.half = this.p.shiftRight(1);
 6075        this.bitLength = this.p.bitLength();
 6076        this.mask = bigInt.one.shiftLeft(this.bitLength).minus(bigInt.one);
 6077
 6078        this.n64 = Math.floor((this.bitLength - 1) / 64)+1;
 6079        this.R = bigInt.one.shiftLeft(this.n64*64);
 6080
 6081        const e = this.minusone.shiftRight(this.one);
 6082        this.nqr = this.two;
 6083        let r = this.pow(this.nqr, e);
 6084        while (!r.equals(this.minusone)) {
 6085            this.nqr = this.nqr.add(this.one);
 6086            r = this.pow(this.nqr, e);
 6087        }
 6088
 6089        this.s = this.zero;
 6090        this.t = this.minusone;
 6091
 6092        while (!this.t.isOdd()) {
 6093            this.s = this.s.add(this.one);
 6094            this.t = this.t.shiftRight(this.one);
 6095        }
 6096
 6097        this.nqr_to_t = this.pow(this.nqr, this.t);
 6098    }
 6099
 6100    e(a,b) {
 6101
 6102        const res = bigInt(a,b);
 6103
 6104        return this.normalize(res);
 6105
 6106    }
 6107
 6108    add(a, b) {
 6109        let res = a.add(b);
 6110        if (res.geq(this.p)) {
 6111            res = res.minus(this.p);
 6112        }
 6113        return res;
 6114    }
 6115
 6116    sub(a, b) {
 6117        if (a.geq(b)) {
 6118            return a.minus(b);
 6119        } else {
 6120            return this.p.minus(b.minus(a));
 6121        }
 6122    }
 6123
 6124    neg(a) {
 6125        if (a.isZero()) return a;
 6126        return this.p.minus(a);
 6127    }
 6128
 6129    mul(a, b) {
 6130        return a.times(b).mod(this.p);
 6131    }
 6132
 6133    mulScalar(base, s) {
 6134        return base.times(bigInt(s)).mod(this.p);
 6135    }
 6136
 6137    square(a) {
 6138        return a.square().mod(this.p);
 6139    }
 6140
 6141    eq(a, b) {
 6142        return a.eq(b);
 6143    }
 6144
 6145    neq(a, b) {
 6146        return a.neq(b);
 6147    }
 6148
 6149    lt(a, b) {
 6150        const aa = a.gt(this.half) ? a.minus(this.p) : a;
 6151        const bb = b.gt(this.half) ? b.minus(this.p) : b;
 6152        return aa.lt(bb);
 6153    }
 6154
 6155    gt(a, b) {
 6156        const aa = a.gt(this.half) ? a.minus(this.p) : a;
 6157        const bb = b.gt(this.half) ? b.minus(this.p) : b;
 6158        return aa.gt(bb);
 6159    }
 6160
 6161    leq(a, b) {
 6162        const aa = a.gt(this.half) ? a.minus(this.p) : a;
 6163        const bb = b.gt(this.half) ? b.minus(this.p) : b;
 6164        return aa.leq(bb);
 6165    }
 6166
 6167    geq(a, b) {
 6168        const aa = a.gt(this.half) ? a.minus(this.p) : a;
 6169        const bb = b.gt(this.half) ? b.minus(this.p) : b;
 6170        return aa.geq(bb);
 6171    }
 6172
 6173    div(a, b) {
 6174        assert(!b.isZero(), "Division by zero");
 6175        return a.times(b.modInv(this.p)).mod(this.p);
 6176    }
 6177
 6178    idiv(a, b) {
 6179        assert(!b.isZero(), "Division by zero");
 6180        return a.divide(b);
 6181    }
 6182
 6183    inv(a) {
 6184        assert(!a.isZero(), "Division by zero");
 6185        return a.modInv(this.p);
 6186    }
 6187
 6188    mod(a, b) {
 6189        return a.mod(b);
 6190    }
 6191
 6192    pow(a, b) {
 6193        return a.modPow(b, this.p);
 6194    }
 6195
 6196    band(a, b) {
 6197        return a.and(b).and(this.mask).mod(this.p);
 6198    }
 6199
 6200    bor(a, b) {
 6201        return a.or(b).and(this.mask).mod(this.p);
 6202    }
 6203
 6204    bxor(a, b) {
 6205        return a.xor(b).and(this.mask).mod(this.p);
 6206    }
 6207
 6208    bnot(a) {
 6209        return a.xor(this.mask).mod(this.p);
 6210    }
 6211
 6212    shl(a, b) {
 6213        if (b.lt(this.bitLength)) {
 6214            return a.shiftLeft(b).and(this.mask).mod(this.p);
 6215        } else {
 6216            const nb = this.p.minus(b);
 6217            if (nb.lt(this.bitLength)) {
 6218                return this.shr(a, nb);
 6219            } else {
 6220                return bigInt.zero;
 6221            }
 6222        }
 6223    }
 6224
 6225    shr(a, b) {
 6226        if (b.lt(this.bitLength)) {
 6227            return a.shiftRight(b);
 6228        } else {
 6229            const nb = this.p.minus(b);
 6230            if (nb.lt(this.bitLength)) {
 6231                return this.shl(a, nb);
 6232            } else {
 6233                return bigInt.zero;
 6234            }
 6235        }
 6236    }
 6237
 6238    land(a, b) {
 6239        return (a.isZero() || b.isZero()) ? bigInt.zero : bigInt.one;
 6240    }
 6241
 6242    lor(a, b) {
 6243        return (a.isZero() && b.isZero()) ? bigInt.zero : bigInt.one;
 6244    }
 6245
 6246    lnot(a) {
 6247        return a.isZero() ? bigInt.one : bigInt.zero;
 6248    }
 6249
 6250    sqrt(n) {
 6251
 6252        if (n.equals(this.zero)) return this.zero;
 6253
 6254        // Test that have solution
 6255        const res = this.pow(n, this.minusone.shiftRight(this.one));
 6256        if (!res.equals(this.one)) return null;
 6257
 6258        let m = parseInt(this.s);
 6259        let c = this.nqr_to_t;
 6260        let t = this.pow(n, this.t);
 6261        let r = this.pow(n, this.add(this.t, this.one).shiftRight(this.one) );
 6262
 6263        while (!t.equals(this.one)) {
 6264            let sq = this.square(t);
 6265            let i = 1;
 6266            while (!sq.equals(this.one)) {
 6267                i++;
 6268                sq = this.square(sq);
 6269            }
 6270
 6271            // b = c ^ m-i-1
 6272            let b = c;
 6273            for (let j=0; j< m-i-1; j ++) b = this.square(b);
 6274
 6275            m = i;
 6276            c = this.square(b);
 6277            t = this.mul(t, c);
 6278            r = this.mul(r, b);
 6279        }
 6280
 6281        if (r.greater(this.p.shiftRight(this.one))) {
 6282            r = this.neg(r);
 6283        }
 6284
 6285        return r;
 6286    }
 6287
 6288    normalize(a) {
 6289        a = bigInt(a);
 6290        if (a.isNegative()) {
 6291            return this.p.minus(a.abs().mod(this.p));
 6292        } else {
 6293            return a.mod(this.p);
 6294        }
 6295    }
 6296
 6297    random() {
 6298        let res = bigInt(0);
 6299        let n = bigInt(this.p.square());
 6300        while (!n.isZero()) {
 6301            res = res.shiftLeft(8).add(bigInt(getRandomByte()));
 6302            n = n.shiftRight(8);
 6303        }
 6304        return res.mod(this.p);
 6305    }
 6306
 6307    toString(a, base) {
 6308        let vs;
 6309        if (!a.lesserOrEquals(this.p.shiftRight(bigInt(1)))) {
 6310            const v = this.p.minus(a);
 6311            vs = "-"+v.toString(base);
 6312        } else {
 6313            vs = a.toString(base);
 6314        }
 6315
 6316        return vs;
 6317    }
 6318
 6319    isZero(a) {
 6320        return a.isZero();
 6321    }
 6322
 6323
 6324};
 6325
 6326
 6327},{"assert":1,"big-integer":6}],17:[function(require,module,exports){
 6328/* global BigInt */
 6329const assert = require("assert");
 6330const Scalar = require("./scalar");
 6331const futils = require("./futils");
 6332
 6333function getRandomByte() {
 6334    if (typeof window !== "undefined") { // Browser
 6335        if (typeof window.crypto !== "undefined") { // Supported
 6336            let array = new Uint8Array(1);
 6337            window.crypto.getRandomValues(array);
 6338            return array[0];
 6339        }
 6340        else { // fallback
 6341            return Math.floor(Math.random() * 256);
 6342        }
 6343    }
 6344    else { // NodeJS
 6345        return module.require("crypto").randomBytes(1)[0];
 6346    }
 6347}
 6348
 6349module.exports = class ZqField {
 6350    constructor(p) {
 6351        this.one = 1n;
 6352        this.zero = 0n;
 6353        this.p = BigInt(p);
 6354        this.minusone = this.p-1n;
 6355        this.two = 2n;
 6356        this.half = this.p >> 1n;
 6357        this.bitLength = Scalar.bitLength(this.p);
 6358        this.mask = (1n << BigInt(this.bitLength)) - 1n;
 6359
 6360        this.n64 = Math.floor((this.bitLength - 1) / 64)+1;
 6361        this.R = this.e(1n << BigInt(this.n64*64));
 6362
 6363        const e = this.minusone >> 1n;
 6364        this.nqr = this.two;
 6365        let r = this.pow(this.nqr, e);
 6366        while (!this.eq(r, this.minusone)) {
 6367            this.nqr = this.nqr + 1n;
 6368            r = this.pow(this.nqr, e);
 6369        }
 6370
 6371        this.s = 0;
 6372        this.t = this.minusone;
 6373
 6374        while ((this.t & 1n) == 0n) {
 6375            this.s = this.s + 1;
 6376            this.t = this.t >> 1n;
 6377        }
 6378
 6379        this.nqr_to_t = this.pow(this.nqr, this.t);
 6380    }
 6381
 6382    e(a,b) {
 6383        let res;
 6384        if (!b) {
 6385            res = BigInt(a);
 6386        } else if (b==16) {
 6387            res = BigInt("0x"+a);
 6388        }
 6389        if (res < 0) {
 6390            let nres = -res;
 6391            if (nres >= this.p) nres = nres % this.p;
 6392            return this.p - nres;
 6393        } else {
 6394            return (res>= this.p) ? res%this.p : res;
 6395        }
 6396
 6397    }
 6398
 6399    add(a, b) {
 6400        const res = a + b;
 6401        return res >= this.p ? res-this.p : res;
 6402    }
 6403
 6404    sub(a, b) {
 6405        return (a >= b) ? a-b : this.p-b+a;
 6406    }
 6407
 6408    neg(a) {
 6409        return a ? this.p-a : a;
 6410    }
 6411
 6412    mul(a, b) {
 6413        return (a*b)%this.p;
 6414    }
 6415
 6416    mulScalar(base, s) {
 6417        return (base * this.e(s)) % this.p;
 6418    }
 6419
 6420    square(a) {
 6421        return (a*a) % this.p;
 6422    }
 6423
 6424    eq(a, b) {
 6425        return a==b;
 6426    }
 6427
 6428    neq(a, b) {
 6429        return a!=b;
 6430    }
 6431
 6432    lt(a, b) {
 6433        const aa = (a > this.half) ? a - this.p : a;
 6434        const bb = (b > this.half) ? b - this.p : b;
 6435        return aa < bb;
 6436    }
 6437
 6438    gt(a, b) {
 6439        const aa = (a > this.half) ? a - this.p : a;
 6440        const bb = (b > this.half) ? b - this.p : b;
 6441        return aa > bb;
 6442    }
 6443
 6444    leq(a, b) {
 6445        const aa = (a > this.half) ? a - this.p : a;
 6446        const bb = (b > this.half) ? b - this.p : b;
 6447        return aa <= bb;
 6448    }
 6449
 6450    geq(a, b) {
 6451        const aa = (a > this.half) ? a - this.p : a;
 6452        const bb = (b > this.half) ? b - this.p : b;
 6453        return aa >= bb;
 6454    }
 6455
 6456    div(a, b) {
 6457        return this.mul(a, this.inv(b));
 6458    }
 6459
 6460    idiv(a, b) {
 6461        assert(b, "Division by zero");
 6462        return a / b;
 6463    }
 6464
 6465    inv(a) {
 6466        assert(a, "Division by zero");
 6467
 6468        let t = 0n;
 6469        let r = this.p;
 6470        let newt = 1n;
 6471        let newr = a % this.p;
 6472        while (newr) {
 6473            let q = r/newr;
 6474            [t, newt] = [newt, t-q*newt];
 6475            [r, newr] = [newr, r-q*newr];
 6476        }
 6477        if (t<0n) t += this.p;
 6478        return t;
 6479    }
 6480
 6481    mod(a, b) {
 6482        return a % b;
 6483    }
 6484
 6485    pow(b, e) {
 6486        return futils.exp(this, b, e);
 6487    }
 6488
 6489    band(a, b) {
 6490        const res =  ((a & b) & this.mask);
 6491        return res >= this.p ? res-this.p : res;
 6492    }
 6493
 6494    bor(a, b) {
 6495        const res =  ((a | b) & this.mask);
 6496        return res >= this.p ? res-this.p : res;
 6497    }
 6498
 6499    bxor(a, b) {
 6500        const res =  ((a ^ b) & this.mask);
 6501        return res >= this.p ? res-this.p : res;
 6502    }
 6503
 6504    bnot(a) {
 6505        const res = a ^ this.mask;
 6506        return res >= this.p ? res-this.p : res;
 6507    }
 6508
 6509    shl(a, b) {
 6510        if (Number(b) < this.bitLength) {
 6511            const res = (a << b) & this.mask;
 6512            return res >= this.p ? res-this.p : res;
 6513        } else {
 6514            const nb = this.p - b;
 6515            if (Number(nb) < this.bitLength) {
 6516                return a >> nb;
 6517            } else {
 6518                return 0n;
 6519            }
 6520        }
 6521    }
 6522
 6523    shr(a, b) {
 6524        if (Number(b) < this.bitLength) {
 6525            return a >> b;
 6526        } else {
 6527            const nb = this.p - b;
 6528            if (Number(nb) < this.bitLength) {
 6529                const res = (a << nb) & this.mask;
 6530                return res >= this.p ? res-this.p : res;
 6531            } else {
 6532                return 0;
 6533            }
 6534        }
 6535    }
 6536
 6537    land(a, b) {
 6538        return (a && b) ? 1n : 0n;
 6539    }
 6540
 6541    lor(a, b) {
 6542        return (a || b) ? 1n : 0n;
 6543    }
 6544
 6545    lnot(a) {
 6546        return (a) ? 0n : 1n;
 6547    }
 6548
 6549    sqrt(n) {
 6550
 6551        if (n == 0n) return this.zero;
 6552
 6553        // Test that have solution
 6554        const res = this.pow(n, this.minusone >> this.one);
 6555        if ( res != 1n ) return null;
 6556
 6557        let m = this.s;
 6558        let c = this.nqr_to_t;
 6559        let t = this.pow(n, this.t);
 6560        let r = this.pow(n, this.add(this.t, this.one) >> 1n );
 6561
 6562        while ( t != 1n ) {
 6563            let sq = this.square(t);
 6564            let i = 1;
 6565            while (sq != 1n ) {
 6566                i++;
 6567                sq = this.square(sq);
 6568            }
 6569
 6570            // b = c ^ m-i-1
 6571            let b = c;
 6572            for (let j=0; j< m-i-1; j ++) b = this.square(b);
 6573
 6574            m = i;
 6575            c = this.square(b);
 6576            t = this.mul(t, c);
 6577            r = this.mul(r, b);
 6578        }
 6579
 6580        if (r > (this.p >> 1n)) {
 6581            r = this.neg(r);
 6582        }
 6583
 6584        return r;
 6585    }
 6586
 6587    normalize(a, b) {
 6588        a = BigInt(a,b);
 6589        if (a < 0) {
 6590            let na = -a;
 6591            if (na >= this.p) na = na % this.p;
 6592            return this.p - na;
 6593        } else {
 6594            return (a>= this.p) ? a%this.p : a;
 6595        }
 6596    }
 6597
 6598    random() {
 6599        const nBytes = (this.bitLength*2 / 8);
 6600        let res =0n;
 6601        for (let i=0; i<nBytes; i++) {
 6602            res = (res << 8n) + BigInt(getRandomByte());
 6603        }
 6604        return res % this.p;
 6605    }
 6606
 6607    toString(a, base) {
 6608        let vs;
 6609        if (a > this.half) {
 6610            const v = this.p-a;
 6611            vs = "-"+v.toString(base);
 6612        } else {
 6613            vs = a.toString(base);
 6614        }
 6615        return vs;
 6616    }
 6617
 6618    isZero(a) {
 6619        return a == 0n;
 6620    }
 6621
 6622};
 6623
 6624
 6625},{"./futils":20,"./scalar":22,"assert":1}],18:[function(require,module,exports){
 6626/*
 6627    Copyright 2018 0kims association.
 6628
 6629    This file is part of snarkjs.
 6630
 6631    snarkjs is a free software: you can redistribute it and/or
 6632    modify it under the terms of the GNU General Public License as published by the
 6633    Free Software Foundation, either version 3 of the License, or (at your option)
 6634    any later version.
 6635
 6636    snarkjs is distributed in the hope that it will be useful,
 6637    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 6638    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 6639    more details.
 6640
 6641    You should have received a copy of the GNU General Public License along with
 6642    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 6643*/
 6644
 6645const fUtils = require("./futils.js");
 6646
 6647class F2Field {
 6648    constructor(F, nonResidue) {
 6649        this.F = F;
 6650        this.zero = [this.F.zero, this.F.zero];
 6651        this.one = [this.F.one, this.F.zero];
 6652        this.nonResidue = nonResidue;
 6653    }
 6654
 6655    _mulByNonResidue(a) {
 6656        return this.F.mul(this.nonResidue, a);
 6657    }
 6658
 6659    copy(a) {
 6660        return [this.F.copy(a[0]), this.F.copy(a[1])];
 6661    }
 6662
 6663    add(a, b) {
 6664        return [
 6665            this.F.add(a[0], b[0]),
 6666            this.F.add(a[1], b[1])
 6667        ];
 6668    }
 6669
 6670    double(a) {
 6671        return this.add(a,a);
 6672    }
 6673
 6674    sub(a, b) {
 6675        return [
 6676            this.F.sub(a[0], b[0]),
 6677            this.F.sub(a[1], b[1])
 6678        ];
 6679    }
 6680
 6681    neg(a) {
 6682        return this.sub(this.zero, a);
 6683    }
 6684
 6685    mul(a, b) {
 6686        const aA = this.F.mul(a[0] , b[0]);
 6687        const bB = this.F.mul(a[1] , b[1]);
 6688
 6689        return [
 6690            this.F.add( aA , this._mulByNonResidue(bB)),
 6691            this.F.sub(
 6692                this.F.mul(
 6693                    this.F.add(a[0], a[1]),
 6694                    this.F.add(b[0], b[1])),
 6695                this.F.add(aA, bB))];
 6696    }
 6697
 6698    inv(a) {
 6699        const t0 = this.F.square(a[0]);
 6700        const t1 = this.F.square(a[1]);
 6701        const t2 = this.F.sub(t0, this._mulByNonResidue(t1));
 6702        const t3 = this.F.inv(t2);
 6703        return [
 6704            this.F.mul(a[0], t3),
 6705            this.F.neg(this.F.mul( a[1], t3)) ];
 6706    }
 6707
 6708    div(a, b) {
 6709        return this.mul(a, this.inv(b));
 6710    }
 6711
 6712    square(a) {
 6713        const ab = this.F.mul(a[0] , a[1]);
 6714
 6715        /*
 6716        [
 6717            (a + b) * (a + non_residue * b) - ab - non_residue * ab,
 6718            ab + ab
 6719        ];
 6720        */
 6721
 6722        return [
 6723            this.F.sub(
 6724                this.F.mul(
 6725                    this.F.add(a[0], a[1]) ,
 6726                    this.F.add(
 6727                        a[0] ,
 6728                        this._mulByNonResidue(a[1]))),
 6729                this.F.add(
 6730                    ab,
 6731                    this._mulByNonResidue(ab))),
 6732            this.F.add(ab, ab)
 6733        ];
 6734    }
 6735
 6736    isZero(a) {
 6737        return this.F.isZero(a[0]) && this.F.isZero(a[1]);
 6738    }
 6739
 6740    eq(a, b) {
 6741        return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]);
 6742    }
 6743
 6744    mulScalar(base, e) {
 6745        return fUtils.mulScalar(this, base, e);
 6746    }
 6747
 6748    exp(base, e) {
 6749        return fUtils.exp(this, base, e);
 6750    }
 6751
 6752    toString(a) {
 6753        return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])} ]`;
 6754    }
 6755}
 6756
 6757module.exports = F2Field;
 6758
 6759},{"./futils.js":20}],19:[function(require,module,exports){
 6760/*
 6761    Copyright 2018 0kims association.
 6762
 6763    This file is part of snarkjs.
 6764
 6765    snarkjs is a free software: you can redistribute it and/or
 6766    modify it under the terms of the GNU General Public License as published by the
 6767    Free Software Foundation, either version 3 of the License, or (at your option)
 6768    any later version.
 6769
 6770    snarkjs is distributed in the hope that it will be useful,
 6771    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 6772    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 6773    more details.
 6774
 6775    You should have received a copy of the GNU General Public License along with
 6776    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 6777*/
 6778
 6779const fUtils = require("./futils.js");
 6780
 6781class F3Field {
 6782    constructor(F, nonResidue) {
 6783        this.F = F;
 6784        this.zero = [this.F.zero, this.F.zero, this.F.zero];
 6785        this.one = [this.F.one, this.F.zero, this.F.zero];
 6786        this.nonResidue = nonResidue;
 6787    }
 6788
 6789    _mulByNonResidue(a) {
 6790        return this.F.mul(this.nonResidue, a);
 6791    }
 6792
 6793    copy(a) {
 6794        return [this.F.copy(a[0]), this.F.copy(a[1]), this.F.copy(a[2])];
 6795    }
 6796
 6797    add(a, b) {
 6798        return [
 6799            this.F.add(a[0], b[0]),
 6800            this.F.add(a[1], b[1]),
 6801            this.F.add(a[2], b[2])
 6802        ];
 6803    }
 6804
 6805    double(a) {
 6806        return this.add(a,a);
 6807    }
 6808
 6809    sub(a, b) {
 6810        return [
 6811            this.F.sub(a[0], b[0]),
 6812            this.F.sub(a[1], b[1]),
 6813            this.F.sub(a[2], b[2])
 6814        ];
 6815    }
 6816
 6817    neg(a) {
 6818        return this.sub(this.zero, a);
 6819    }
 6820
 6821    mul(a, b) {
 6822
 6823        const aA = this.F.mul(a[0] , b[0]);
 6824        const bB = this.F.mul(a[1] , b[1]);
 6825        const cC = this.F.mul(a[2] , b[2]);
 6826
 6827        return [
 6828            this.F.add(
 6829                aA,
 6830                this._mulByNonResidue(
 6831                    this.F.sub(
 6832                        this.F.mul(
 6833                            this.F.add(a[1], a[2]),
 6834                            this.F.add(b[1], b[2])),
 6835                        this.F.add(bB, cC)))),    // aA + non_residue*((b+c)*(B+C)-bB-cC),
 6836
 6837            this.F.add(
 6838                this.F.sub(
 6839                    this.F.mul(
 6840                        this.F.add(a[0], a[1]),
 6841                        this.F.add(b[0], b[1])),
 6842                    this.F.add(aA, bB)),
 6843                this._mulByNonResidue( cC)),   // (a+b)*(A+B)-aA-bB+non_residue*cC
 6844
 6845            this.F.add(
 6846                this.F.sub(
 6847                    this.F.mul(
 6848                        this.F.add(a[0], a[2]),
 6849                        this.F.add(b[0], b[2])),
 6850                    this.F.add(aA, cC)),
 6851                bB)];                           // (a+c)*(A+C)-aA+bB-cC)
 6852    }
 6853
 6854    inv(a) {
 6855        const t0 = this.F.square(a[0]);             // t0 = a^2 ;
 6856        const t1 = this.F.square(a[1]);             // t1 = b^2 ;
 6857        const t2 = this.F.square(a[2]);             // t2 = c^2;
 6858        const t3 = this.F.mul(a[0],a[1]);           // t3 = ab
 6859        const t4 = this.F.mul(a[0],a[2]);           // t4 = ac
 6860        const t5 = this.F.mul(a[1],a[2]);           // t5 = bc;
 6861        // c0 = t0 - non_residue * t5;
 6862        const c0 = this.F.sub(t0, this._mulByNonResidue(t5));
 6863        // c1 = non_residue * t2 - t3;
 6864        const c1 = this.F.sub(this._mulByNonResidue(t2), t3);
 6865        const c2 = this.F.sub(t1, t4);              // c2 = t1-t4
 6866
 6867        // t6 = (a * c0 + non_residue * (c * c1 + b * c2)).inv();
 6868        const t6 =
 6869            this.F.inv(
 6870                this.F.add(
 6871                    this.F.mul(a[0], c0),
 6872                    this._mulByNonResidue(
 6873                        this.F.add(
 6874                            this.F.mul(a[2], c1),
 6875                            this.F.mul(a[1], c2)))));
 6876
 6877        return [
 6878            this.F.mul(t6, c0),         // t6*c0
 6879            this.F.mul(t6, c1),         // t6*c1
 6880            this.F.mul(t6, c2)];        // t6*c2
 6881    }
 6882
 6883    div(a, b) {
 6884        return this.mul(a, this.inv(b));
 6885    }
 6886
 6887    square(a) {
 6888        const s0 = this.F.square(a[0]);                   // s0 = a^2
 6889        const ab = this.F.mul(a[0], a[1]);                // ab = a*b
 6890        const s1 = this.F.add(ab, ab);                    // s1 = 2ab;
 6891        const s2 = this.F.square(
 6892            this.F.add(this.F.sub(a[0],a[1]), a[2]));     // s2 = (a - b + c)^2;
 6893        const bc = this.F.mul(a[1],a[2]);                 // bc = b*c
 6894        const s3 = this.F.add(bc, bc);                    // s3 = 2*bc
 6895        const s4 = this.F.square(a[2]);                   // s4 = c^2
 6896
 6897
 6898        return [
 6899            this.F.add(
 6900                s0,
 6901                this._mulByNonResidue(s3)),           // s0 + non_residue * s3,
 6902            this.F.add(
 6903                s1,
 6904                this._mulByNonResidue(s4)),           // s1 + non_residue * s4,
 6905            this.F.sub(
 6906                this.F.add( this.F.add(s1, s2) , s3 ),
 6907                this.F.add(s0, s4))];                      // s1 + s2 + s3 - s0 - s4
 6908    }
 6909
 6910    isZero(a) {
 6911        return this.F.isZero(a[0]) && this.F.isZero(a[1]) && this.F.isZero(a[2]);
 6912    }
 6913
 6914    eq(a, b) {
 6915        return this.F.eq(a[0], b[0]) && this.F.eq(a[1], b[1]) && this.F.eq(a[2], b[2]);
 6916    }
 6917
 6918    affine(a) {
 6919        return [this.F.affine(a[0]), this.F.affine(a[1]), this.F.affine(a[2])];
 6920    }
 6921
 6922    mulScalar(base, e) {
 6923        return fUtils.mulScalar(this, base, e);
 6924    }
 6925
 6926    exp(base, e) {
 6927        return fUtils.exp(this, base, e);
 6928    }
 6929
 6930    toString(a) {
 6931        return `[ ${this.F.toString(a[0])} , ${this.F.toString(a[1])}, ${this.F.toString(a[2])} ]`;
 6932    }
 6933}
 6934
 6935module.exports = F3Field;
 6936
 6937},{"./futils.js":20}],20:[function(require,module,exports){
 6938/*
 6939    Copyright 2018 0kims association.
 6940
 6941    This file is part of snarkjs.
 6942
 6943    snarkjs is a free software: you can redistribute it and/or
 6944    modify it under the terms of the GNU General Public License as published by the
 6945    Free Software Foundation, either version 3 of the License, or (at your option)
 6946    any later version.
 6947
 6948    snarkjs is distributed in the hope that it will be useful,
 6949    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 6950    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 6951    more details.
 6952
 6953    You should have received a copy of the GNU General Public License along with
 6954    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 6955*/
 6956
 6957const Scalar = require("./scalar.js");
 6958const assert = require("assert");
 6959
 6960
 6961exports.mulScalar = (F, base, e) => {
 6962    let res;
 6963
 6964    if (Scalar.isZero(e)) return F.zero;
 6965
 6966    const n = Scalar.naf(e);
 6967
 6968    if (n[n.length-1] == 1) {
 6969        res = base;
 6970    } else if (n[n.length-1] == -1) {
 6971        res = F.neg(base);
 6972    } else {
 6973        assert(false);
 6974    }
 6975
 6976    for (let i=n.length-2; i>=0; i--) {
 6977
 6978        res = F.double(res);
 6979
 6980        if (n[i] == 1) {
 6981            res = F.add(res, base);
 6982        } else if (n[i] == -1) {
 6983            res = F.sub(res, base);
 6984        }
 6985    }
 6986
 6987    return res;
 6988};
 6989
 6990
 6991/*
 6992exports.mulScalar = (F, base, e) =>{
 6993    let res = F.zero;
 6994    let rem = bigInt(e);
 6995    let exp = base;
 6996
 6997    while (! rem.eq(bigInt.zero)) {
 6998        if (rem.and(bigInt.one).eq(bigInt.one)) {
 6999            res = F.add(res, exp);
 7000        }
 7001        exp = F.double(exp);
 7002        rem = rem.shiftRight(1);
 7003    }
 7004
 7005    return res;
 7006};
 7007*/
 7008
 7009
 7010exports.exp = (F, base, e) => {
 7011
 7012    if (Scalar.isZero(e)) return F.one;
 7013
 7014    const n = Scalar.bits(e);
 7015
 7016    if (n.legth==0) return F.one;
 7017
 7018    let res = base;
 7019
 7020    for (let i=n.length-2; i>=0; i--) {
 7021
 7022        res = F.square(res);
 7023
 7024        if (n[i]) {
 7025            res = F.mul(res, base);
 7026        }
 7027    }
 7028
 7029    return res;
 7030};
 7031
 7032
 7033
 7034},{"./scalar.js":22,"assert":1}],21:[function(require,module,exports){
 7035/*
 7036    Copyright 2018 0kims association.
 7037
 7038    This file is part of snarkjs.
 7039
 7040    snarkjs is a free software: you can redistribute it and/or
 7041    modify it under the terms of the GNU General Public License as published by the
 7042    Free Software Foundation, either version 3 of the License, or (at your option)
 7043    any later version.
 7044
 7045    snarkjs is distributed in the hope that it will be useful,
 7046    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 7047    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 7048    more details.
 7049
 7050    You should have received a copy of the GNU General Public License along with
 7051    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 7052*/
 7053
 7054/*
 7055    This library does operations on polynomials with coefficients in a field F.
 7056
 7057    A polynomial P(x) = p0 + p1 * x + p2 * x^2 + ... + pn * x^n  is represented
 7058    by the array [ p0, p1, p2, ... , pn ].
 7059 */
 7060
 7061class PolField {
 7062    constructor (F) {
 7063        this.F = F;
 7064
 7065        let rem = F.t;
 7066        let s = F.s;
 7067
 7068        const five = this.F.add(this.F.add(this.F.two, this.F.two), this.F.one);
 7069
 7070        this.w = new Array(s+1);
 7071        this.wi = new Array(s+1);
 7072        this.w[s] = this.F.pow(five, rem);
 7073        this.wi[s] = this.F.inv(this.w[s]);
 7074
 7075        let n=s-1;
 7076        while (n>=0) {
 7077            this.w[n] = this.F.square(this.w[n+1]);
 7078            this.wi[n] = this.F.square(this.wi[n+1]);
 7079            n--;
 7080        }
 7081
 7082
 7083        this.roots = [];
 7084/*        for (let i=0; i<16; i++) {
 7085            let r = this.F.one;
 7086            n = 1 << i;
 7087            const rootsi = new Array(n);
 7088            for (let j=0; j<n; j++) {
 7089                rootsi[j] = r;
 7090                r = this.F.mul(r, this.w[i]);
 7091            }
 7092
 7093            this.roots.push(rootsi);
 7094        }
 7095    */
 7096        this._setRoots(15);
 7097    }
 7098
 7099    _setRoots(n) {
 7100        for (let i=n; (i>=0) && (!this.roots[i]); i--) {
 7101            let r = this.F.one;
 7102            const nroots = 1 << i;
 7103            const rootsi = new Array(nroots);
 7104            for (let j=0; j<nroots; j++) {
 7105                rootsi[j] = r;
 7106                r = this.F.mul(r, this.w[i]);
 7107            }
 7108
 7109            this.roots[i] = rootsi;
 7110        }
 7111    }
 7112
 7113    add(a, b) {
 7114        const m = Math.max(a.length, b.length);
 7115        const res = new Array(m);
 7116        for (let i=0; i<m; i++) {
 7117            res[i] = this.F.add(a[i] || this.F.zero, b[i] || this.F.zero);
 7118        }
 7119        return this.reduce(res);
 7120    }
 7121
 7122    double(a) {
 7123        return this.add(a,a);
 7124    }
 7125
 7126    sub(a, b) {
 7127        const m = Math.max(a.length, b.length);
 7128        const res = new Array(m);
 7129        for (let i=0; i<m; i++) {
 7130            res[i] = this.F.sub(a[i] || this.F.zero, b[i] || this.F.zero);
 7131        }
 7132        return this.reduce(res);
 7133    }
 7134
 7135    mulScalar(p, b) {
 7136        if (this.F.eq(b, this.F.zero)) return [];
 7137        if (this.F.eq(b, this.F.one)) return p;
 7138        const res = new Array(p.length);
 7139        for (let i=0; i<p.length; i++) {
 7140            res[i] = this.F.mul(p[i], b);
 7141        }
 7142        return res;
 7143    }
 7144
 7145
 7146
 7147    mul(a, b) {
 7148        if (a.length == 0) return [];
 7149        if (b.length == 0) return [];
 7150        if (a.length == 1) return this.mulScalar(b, a[0]);
 7151        if (b.length == 1) return this.mulScalar(a, b[0]);
 7152
 7153        if (b.length > a.length) {
 7154            [b, a] = [a, b];
 7155        }
 7156
 7157        if ((b.length <= 2) || (b.length < log2(a.length))) {
 7158            return this.mulNormal(a,b);
 7159        } else {
 7160            return this.mulFFT(a,b);
 7161        }
 7162    }
 7163
 7164    mulNormal(a, b) {
 7165        let res = [];
 7166        for (let i=0; i<b.length; i++) {
 7167            res = this.add(res, this.scaleX(this.mulScalar(a, b[i]), i) );
 7168        }
 7169        return res;
 7170    }
 7171
 7172    mulFFT(a,b) {
 7173        const longestN = Math.max(a.length, b.length);
 7174        const bitsResult = log2(longestN-1)+2;
 7175        this._setRoots(bitsResult);
 7176
 7177        const m = 1 << bitsResult;
 7178        const ea = this.extend(a,m);
 7179        const eb = this.extend(b,m);
 7180
 7181        const ta = __fft(this, ea, bitsResult, 0, 1, false);
 7182        const tb = __fft(this, eb, bitsResult, 0, 1, false);
 7183
 7184        const tres = new Array(m);
 7185
 7186        for (let i=0; i<m; i++) {
 7187            tres[i] = this.F.mul(ta[i], tb[i]);
 7188        }
 7189
 7190        const res = __fft(this, tres, bitsResult, 0, 1, true);
 7191
 7192        const twoinvm = this.F.inv( this.F.mulScalar(this.F.one, m) );
 7193        const resn = new Array(m);
 7194        for (let i=0; i<m; i++) {
 7195            resn[i] = this.F.mul(res[(m-i)%m], twoinvm);
 7196        }
 7197
 7198        return this.reduce(resn);
 7199    }
 7200
 7201
 7202
 7203    square(a) {
 7204        return this.mul(a,a);
 7205    }
 7206
 7207    scaleX(p, n) {
 7208        if (n==0) {
 7209            return p;
 7210        } else if (n>0) {
 7211            const z = new Array(n).fill(this.F.zero);
 7212            return z.concat(p);
 7213        } else {
 7214            if (-n >= p.length) return [];
 7215            return p.slice(-n);
 7216        }
 7217    }
 7218
 7219    eval2(p, x) {
 7220        let v = this.F.zero;
 7221        let ix = this.F.one;
 7222        for (let i=0; i<p.length; i++) {
 7223            v = this.F.add(v, this.F.mul(p[i], ix));
 7224            ix = this.F.mul(ix, x);
 7225        }
 7226        return v;
 7227    }
 7228
 7229    eval(p,x) {
 7230        const F = this.F;
 7231        if (p.length == 0) return F.zero;
 7232        const m = this._next2Power(p.length);
 7233        const ep = this.extend(p, m);
 7234
 7235        return _eval(ep, x, 0, 1, m);
 7236
 7237        function _eval(p, x, offset, step, n) {
 7238            if (n==1) return p[offset];
 7239            const newX = F.square(x);
 7240            const res= F.add(
 7241                _eval(p, newX, offset, step << 1, n >> 1),
 7242                F.mul(
 7243                    x,
 7244                    _eval(p, newX, offset+step , step << 1, n >> 1)));
 7245            return res;
 7246        }
 7247    }
 7248
 7249    lagrange(points) {
 7250        let roots = [this.F.one];
 7251        for (let i=0; i<points.length; i++) {
 7252            roots = this.mul(roots, [this.F.neg(points[i][0]), this.F.one]);
 7253        }
 7254
 7255        let sum = [];
 7256        for (let i=0; i<points.length; i++) {
 7257            let mpol = this.ruffini(roots, points[i][0]);
 7258            const factor =
 7259                this.F.mul(
 7260                    this.F.inv(this.eval(mpol, points[i][0])),
 7261                    points[i][1]);
 7262            mpol = this.mulScalar(mpol, factor);
 7263            sum = this.add(sum, mpol);
 7264        }
 7265        return sum;
 7266    }
 7267
 7268
 7269    fft(p) {
 7270        if (p.length <= 1) return p;
 7271        const bits = log2(p.length-1)+1;
 7272        this._setRoots(bits);
 7273
 7274        const m = 1 << bits;
 7275        const ep = this.extend(p, m);
 7276        const res = __fft(this, ep, bits, 0, 1);
 7277        return res;
 7278    }
 7279
 7280    ifft(p) {
 7281
 7282        if (p.length <= 1) return p;
 7283        const bits = log2(p.length-1)+1;
 7284        this._setRoots(bits);
 7285        const m = 1 << bits;
 7286        const ep = this.extend(p, m);
 7287        const res =  __fft(this, ep, bits, 0, 1);
 7288
 7289        const twoinvm = this.F.inv( this.F.mulScalar(this.F.one, m) );
 7290        const resn = new Array(m);
 7291        for (let i=0; i<m; i++) {
 7292            resn[i] = this.F.mul(res[(m-i)%m], twoinvm);
 7293        }
 7294
 7295        return resn;
 7296
 7297    }
 7298
 7299
 7300    _fft(pall, bits, offset, step) {
 7301
 7302        const n = 1 << bits;
 7303        if (n==1) {
 7304            return [ pall[offset] ];
 7305        }
 7306
 7307        const ndiv2 = n >> 1;
 7308        const p1 = this._fft(pall, bits-1, offset, step*2);
 7309        const p2 = this._fft(pall, bits-1, offset+step, step*2);
 7310
 7311        const out = new Array(n);
 7312
 7313        let m= this.F.one;
 7314        for (let i=0; i<ndiv2; i++) {
 7315            out[i] = this.F.add(p1[i], this.F.mul(m, p2[i]));
 7316            out[i+ndiv2] = this.F.sub(p1[i], this.F.mul(m, p2[i]));
 7317            m = this.F.mul(m, this.w[bits]);
 7318        }
 7319
 7320        return out;
 7321    }
 7322
 7323    extend(p, e) {
 7324        if (e == p.length) return p;
 7325        const z = new Array(e-p.length).fill(this.F.zero);
 7326
 7327        return p.concat(z);
 7328    }
 7329
 7330    reduce(p) {
 7331        if (p.length == 0) return p;
 7332        if (! this.F.eq(p[p.length-1], this.F.zero) ) return p;
 7333        let i=p.length-1;
 7334        while( i>0 && this.F.eq(p[i], this.F.zero) ) i--;
 7335        return p.slice(0, i+1);
 7336    }
 7337
 7338    eq(a, b) {
 7339        const pa = this.reduce(a);
 7340        const pb = this.reduce(b);
 7341
 7342        if (pa.length != pb.length) return false;
 7343        for (let i=0; i<pb.length; i++) {
 7344            if (!this.F.eq(pa[i], pb[i])) return false;
 7345        }
 7346
 7347        return true;
 7348    }
 7349
 7350    ruffini(p, r) {
 7351        const res = new Array(p.length-1);
 7352        res[res.length-1] = p[p.length-1];
 7353        for (let i = res.length-2; i>=0; i--) {
 7354            res[i] = this.F.add(this.F.mul(res[i+1], r), p[i+1]);
 7355        }
 7356        return res;
 7357    }
 7358
 7359    _next2Power(v) {
 7360        v--;
 7361        v |= v >> 1;
 7362        v |= v >> 2;
 7363        v |= v >> 4;
 7364        v |= v >> 8;
 7365        v |= v >> 16;
 7366        v++;
 7367        return v;
 7368    }
 7369
 7370    toString(p) {
 7371        const ap = this.normalize(p);
 7372        let S = "";
 7373        for (let i=ap.length-1; i>=0; i--) {
 7374            if (!this.F.eq(p[i], this.F.zero)) {
 7375                if (S!="") S += " + ";
 7376                S = S + p[i].toString(10);
 7377                if (i>0) {
 7378                    S = S + "x";
 7379                    if (i>1) {
 7380                        S = S + "^" +i;
 7381                    }
 7382                }
 7383            }
 7384        }
 7385        return S;
 7386    }
 7387
 7388    normalize(p) {
 7389        const res  = new Array(p.length);
 7390        for (let i=0; i<p.length; i++) {
 7391            res[i] = this.F.normalize(p[i]);
 7392        }
 7393        return res;
 7394    }
 7395
 7396
 7397    _reciprocal(p, bits) {
 7398        const k = 1 << bits;
 7399        if (k==1) {
 7400            return [ this.F.inv(p[0]) ];
 7401        }
 7402        const np = this.scaleX(p, -k/2);
 7403        const q = this._reciprocal(np, bits-1);
 7404        const a = this.scaleX(this.double(q), 3*k/2-2);
 7405        const b = this.mul( this.square(q), p);
 7406
 7407        return this.scaleX(this.sub(a,b),   -(k-2));
 7408    }
 7409
 7410    // divides x^m / v
 7411    _div2(m, v) {
 7412        const kbits = log2(v.length-1)+1;
 7413        const k = 1 << kbits;
 7414
 7415        const scaleV = k - v.length;
 7416
 7417        // rec = x^(k - 2) / v* x^scaleV =>
 7418        // rec = x^(k-2-scaleV)/ v
 7419        //
 7420        // res = x^m/v = x^(m + (2*k-2 - scaleV) - (2*k-2 - scaleV)) /v =>
 7421        // res = rec * x^(m - (2*k-2 - scaleV)) =>
 7422        // res = rec * x^(m - 2*k + 2 + scaleV)
 7423
 7424        const rec = this._reciprocal(this.scaleX(v, scaleV), kbits);
 7425        const res = this.scaleX(rec, m - 2*k + 2 + scaleV);
 7426
 7427        return res;
 7428    }
 7429
 7430    div(_u, _v) {
 7431        if (_u.length < _v.length) return [];
 7432        const kbits = log2(_v.length-1)+1;
 7433        const k = 1 << kbits;
 7434
 7435        const u = this.scaleX(_u, k-_v.length);
 7436        const v = this.scaleX(_v, k-_v.length);
 7437
 7438        const n = v.length-1;
 7439        let m = u.length-1;
 7440
 7441        const s = this._reciprocal(v, kbits);
 7442        let t;
 7443        if (m>2*n) {
 7444            t = this.sub(this.scaleX([this.F.one], 2*n), this.mul(s, v));
 7445        }
 7446
 7447        let q = [];
 7448        let rem = u;
 7449        let us, ut;
 7450        let finish = false;
 7451
 7452        while (!finish) {
 7453            us = this.mul(rem, s);
 7454            q = this.add(q, this.scaleX(us, -2*n));
 7455
 7456            if ( m > 2*n ) {
 7457                ut = this.mul(rem, t);
 7458                rem = this.scaleX(ut, -2*n);
 7459                m = rem.length-1;
 7460            } else {
 7461                finish = true;
 7462            }
 7463        }
 7464
 7465        return q;
 7466    }
 7467
 7468
 7469    // returns the ith nth-root of one
 7470    oneRoot(n, i) {
 7471        let nbits = log2(n-1)+1;
 7472        let res = this.F.one;
 7473        let r = i;
 7474
 7475        if(i>=n) {
 7476            throw new Error("Given 'i' should be lower than 'n'");
 7477        }
 7478        else if (1<<nbits !== n) {
 7479            throw new Error(`Internal errlr: ${n} should equal ${1<<nbits}`);
 7480        }
 7481
 7482        while (r>0) {
 7483            if (r & 1 == 1) {
 7484                res = this.F.mul(res, this.w[nbits]);
 7485            }
 7486            r = r >> 1;
 7487            nbits --;
 7488        }
 7489        return res;
 7490    }
 7491
 7492    computeVanishingPolinomial(bits, t) {
 7493        const m = 1 << bits;
 7494        return this.F.sub(this.F.pow(t, m), this.F.one);
 7495    }
 7496
 7497    evaluateLagrangePolynomials(bits, t) {
 7498        const m= 1 << bits;
 7499        const tm = this.F.pow(t, m);
 7500        const u= new Array(m).fill(this.F.zero);
 7501        this._setRoots(bits);
 7502        const omega = this.w[bits];
 7503
 7504        if (this.F.eq(tm, this.F.one)) {
 7505            for (let i = 0; i < m; i++) {
 7506                if (this.F.eq(this.roots[bits][0],t)) { // i.e., t equals omega^i
 7507                    u[i] = this.F.one;
 7508                    return u;
 7509                }
 7510            }
 7511        }
 7512
 7513        const z = this.F.sub(tm, this.F.one);
 7514//        let l = this.F.mul(z,  this.F.pow(this.F.twoinv, m));
 7515        let l = this.F.mul(z,  this.F.inv(this.F.e(m)));
 7516        for (let i = 0; i < m; i++) {
 7517            u[i] = this.F.mul(l, this.F.inv(this.F.sub(t,this.roots[bits][i])));
 7518            l = this.F.mul(l, omega);
 7519        }
 7520
 7521        return u;
 7522    }
 7523
 7524    log2(V) {
 7525        return log2(V);
 7526    }
 7527}
 7528
 7529function log2( V )
 7530{
 7531    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 ) );
 7532}
 7533
 7534
 7535function __fft(PF, pall, bits, offset, step) {
 7536
 7537    const n = 1 << bits;
 7538    if (n==1) {
 7539        return [ pall[offset] ];
 7540    } else if (n==2) {
 7541        return [
 7542            PF.F.add(pall[offset], pall[offset + step]),
 7543            PF.F.sub(pall[offset], pall[offset + step])];
 7544    }
 7545
 7546    const ndiv2 = n >> 1;
 7547    const p1 = __fft(PF, pall, bits-1, offset, step*2);
 7548    const p2 = __fft(PF, pall, bits-1, offset+step, step*2);
 7549
 7550    const out = new Array(n);
 7551
 7552    for (let i=0; i<ndiv2; i++) {
 7553        out[i] = PF.F.add(p1[i], PF.F.mul(PF.roots[bits][i], p2[i]));
 7554        out[i+ndiv2] = PF.F.sub(p1[i], PF.F.mul(PF.roots[bits][i], p2[i]));
 7555    }
 7556
 7557    return out;
 7558}
 7559
 7560
 7561module.exports = PolField;
 7562
 7563},{}],22:[function(require,module,exports){
 7564
 7565
 7566const supportsNativeBigInt = typeof BigInt === "function";
 7567if (supportsNativeBigInt) {
 7568    module.exports = require("./scalar_native.js");
 7569} else {
 7570    module.exports = require("./scalar_bigint.js");
 7571}
 7572
 7573
 7574},{"./scalar_bigint.js":23,"./scalar_native.js":24}],23:[function(require,module,exports){
 7575const bigInt = require("big-integer");
 7576const assert = require("assert");
 7577
 7578module.exports.fromString = function fromString(s, radix) {
 7579    return bigInt(s,radix);
 7580};
 7581
 7582module.exports.fromArray = function fromArray(a, radix) {
 7583    return bigInt.fromArray(a, radix);
 7584};
 7585
 7586module.exports.bitLength = function (a) {
 7587    return bigInt(a).bitLength();
 7588};
 7589
 7590module.exports.isNegative = function (a) {
 7591    return bigInt(a).isNegative();
 7592};
 7593
 7594module.exports.isZero = function (a) {
 7595    return bigInt(a).isZero();
 7596};
 7597
 7598module.exports.shiftLeft = function (a, n) {
 7599    return bigInt(a).shiftLeft(n);
 7600};
 7601
 7602module.exports.shiftRight = function (a, n) {
 7603    return bigInt(a).shiftRight(n);
 7604};
 7605
 7606module.exports.shl = module.exports.shiftLeft;
 7607module.exports.shr = module.exports.shiftRight;
 7608
 7609module.exports.isOdd = function (a) {
 7610    return bigInt(a).isOdd();
 7611};
 7612
 7613
 7614module.exports.naf = function naf(n) {
 7615    let E = bigInt(n);
 7616    const res = [];
 7617    while (E.gt(bigInt.zero)) {
 7618        if (E.isOdd()) {
 7619            const z = 2 - E.mod(4).toJSNumber();
 7620            res.push( z );
 7621            E = E.minus(z);
 7622        } else {
 7623            res.push( 0 );
 7624        }
 7625        E = E.shiftRight(1);
 7626    }
 7627    return res;
 7628};
 7629
 7630
 7631module.exports.bits = function naf(n) {
 7632    let E = bigInt(n);
 7633    const res = [];
 7634    while (E.gt(bigInt.zero)) {
 7635        if (E.isOdd()) {
 7636            res.push(1);
 7637        } else {
 7638            res.push( 0 );
 7639        }
 7640        E = E.shiftRight(1);
 7641    }
 7642    return res;
 7643};
 7644
 7645module.exports.toNumber = function(s) {
 7646    assert(s.lt(bigInt("100000000", 16)));
 7647    return s.toJSNumber();
 7648};
 7649
 7650module.exports.toArray = function(s, radix) {
 7651    return bigInt(s).toArray(radix);
 7652};
 7653
 7654module.exports.e = function(a) {
 7655    return bigInt(a);
 7656};
 7657
 7658module.exports.add = function(a, b) {
 7659    return bigInt(a).add(bigInt(b));
 7660};
 7661
 7662module.exports.sub = function(a, b) {
 7663    return bigInt(a).minus(bigInt(b));
 7664};
 7665
 7666module.exports.neg = function(a) {
 7667    return bigInt.zero.minus(bigInt(a));
 7668};
 7669
 7670module.exports.mul = function(a, b) {
 7671    return bigInt(a).times(bigInt(b));
 7672};
 7673
 7674module.exports.square = function(a) {
 7675    return bigInt(a).square();
 7676};
 7677
 7678module.exports.div = function(a, b) {
 7679    return bigInt(a).divide(bigInt(b));
 7680};
 7681
 7682module.exports.mod = function(a, b) {
 7683    return bigInt(a).mod(bigInt(b));
 7684};
 7685
 7686module.exports.eq = function(a, b) {
 7687    return bigInt(a).eq(bigInt(b));
 7688};
 7689
 7690module.exports.neq = function(a, b) {
 7691    return bigInt(a).neq(bigInt(b));
 7692};
 7693
 7694module.exports.lt = function(a, b) {
 7695    return bigInt(a).lt(bigInt(b));
 7696};
 7697
 7698module.exports.gt = function(a, b) {
 7699    return bigInt(a).gt(bigInt(b));
 7700};
 7701
 7702module.exports.leq = function(a, b) {
 7703    return bigInt(a).leq(bigInt(b));
 7704};
 7705
 7706module.exports.geq = function(a, b) {
 7707    return bigInt(a).geq(bigInt(b));
 7708};
 7709
 7710module.exports.band = function(a, b) {
 7711    return bigInt(a).and(bigInt(b));
 7712};
 7713
 7714module.exports.bor = function(a, b) {
 7715    return bigInt(a).or(bigInt(b));
 7716};
 7717
 7718module.exports.bxor = function(a, b) {
 7719    return bigInt(a).xor(bigInt(b));
 7720};
 7721
 7722module.exports.band = function(a, b) {
 7723    return (!bigInt(a).isZero()) && (!bigInt(b).isZero());
 7724};
 7725
 7726module.exports.bor = function(a, b) {
 7727    return (!bigInt(a).isZero()) || (!bigInt(b).isZero());
 7728};
 7729
 7730module.exports.bnot = function(a) {
 7731    return bigInt(a).isZero();
 7732};
 7733
 7734
 7735
 7736},{"assert":1,"big-integer":6}],24:[function(require,module,exports){
 7737/* global BigInt */
 7738const assert = require("assert");
 7739const hexLen = [ 0, 1, 2, 2, 3, 3, 3, 3, 4 ,4 ,4 ,4 ,4 ,4 ,4 ,4];
 7740
 7741module.exports.fromString = function fromString(s, radix) {
 7742    if ((!radix)||(radix==10)) {
 7743        return BigInt(s);
 7744    } else if (radix==16) {
 7745        return BigInt("0x"+s);
 7746    }
 7747};
 7748
 7749module.exports.fromArray = function fromArray(a, radix) {
 7750    let acc =0n;
 7751    radix = BigInt(radix);
 7752    for (let i=0; i<a.length; i++) {
 7753        acc = acc*radix + BigInt(a[i]);
 7754    }
 7755    return acc;
 7756};
 7757
 7758module.exports.bitLength = function (a) {
 7759    const aS =a.toString(16);
 7760    return (aS.length-1)*4 +hexLen[aS[0]];
 7761};
 7762
 7763module.exports.isNegative = function (a) {
 7764    return BigInt(a) < 0n;
 7765};
 7766
 7767module.exports.isZero = function (a) {
 7768    return !a;
 7769};
 7770
 7771module.exports.shiftLeft = function (a, n) {
 7772    return BigInt(a) << BigInt(n);
 7773};
 7774
 7775module.exports.shiftRight = function (a, n) {
 7776    return BigInt(a) >> BigInt(n);
 7777};
 7778
 7779module.exports.shl = module.exports.shiftLeft;
 7780module.exports.shr = module.exports.shiftRight;
 7781
 7782module.exports.isOdd = function (a) {
 7783    return (BigInt(a) & 1n) == 1n;
 7784};
 7785
 7786
 7787module.exports.naf = function naf(n) {
 7788    let E = BigInt(n);
 7789    const res = [];
 7790    while (E) {
 7791        if (E & 1n) {
 7792            const z = 2 - Number(E % 4n);
 7793            res.push( z );
 7794            E = E - BigInt(z);
 7795        } else {
 7796            res.push( 0 );
 7797        }
 7798        E = E >> 1n;
 7799    }
 7800    return res;
 7801};
 7802
 7803
 7804module.exports.bits = function naf(n) {
 7805    let E = BigInt(n);
 7806    const res = [];
 7807    while (E) {
 7808        if (E & 1n) {
 7809            res.push(1);
 7810        } else {
 7811            res.push( 0 );
 7812        }
 7813        E = E >> 1n;
 7814    }
 7815    return res;
 7816};
 7817
 7818module.exports.toNumber = function(s) {
 7819    assert(s<0x100000000n);
 7820    return Number(s);
 7821};
 7822
 7823module.exports.toArray = function(s, radix) {
 7824    const res = [];
 7825    let rem = BigInt(s);
 7826    radix = BigInt(radix);
 7827    while (rem) {
 7828        res.unshift( Number(rem % radix));
 7829        rem = rem / radix;
 7830    }
 7831    return res;
 7832};
 7833
 7834
 7835module.exports.e = function(a) {
 7836    return BigInt(a);
 7837};
 7838
 7839module.exports.add = function(a, b) {
 7840    return BigInt(a) + BigInt(b);
 7841};
 7842
 7843module.exports.sub = function(a, b) {
 7844    return BigInt(a) - BigInt(b);
 7845};
 7846
 7847module.exports.neg = function(a) {
 7848    return -BigInt(a);
 7849};
 7850
 7851module.exports.mul = function(a, b) {
 7852    return BigInt(a) * BigInt(b);
 7853};
 7854
 7855module.exports.square = function(a) {
 7856    return BigInt(a) * BigInt(a);
 7857};
 7858
 7859module.exports.div = function(a, b) {
 7860    return BigInt(a) / BigInt(b);
 7861};
 7862
 7863module.exports.mod = function(a, b) {
 7864    return BigInt(a) % BigInt(b);
 7865};
 7866
 7867module.exports.eq = function(a, b) {
 7868    return BigInt(a) == BigInt(b);
 7869};
 7870
 7871module.exports.neq = function(a, b) {
 7872    return BigInt(a) != BigInt(b);
 7873};
 7874
 7875module.exports.lt = function(a, b) {
 7876    return BigInt(a) < BigInt(b);
 7877};
 7878
 7879module.exports.gt = function(a, b) {
 7880    return BigInt(a) > BigInt(b);
 7881};
 7882
 7883module.exports.leq = function(a, b) {
 7884    return BigInt(a) <= BigInt(b);
 7885};
 7886
 7887module.exports.geq = function(a, b) {
 7888    return BigInt(a) >= BigInt(b);
 7889};
 7890
 7891module.exports.band = function(a, b) {
 7892    return BigInt(a) & BigInt(b);
 7893};
 7894
 7895module.exports.bor = function(a, b) {
 7896    return BigInt(a) | BigInt(b);
 7897};
 7898
 7899module.exports.bxor = function(a, b) {
 7900    return BigInt(a) ^ BigInt(b);
 7901};
 7902
 7903module.exports.band = function(a, b) {
 7904    return BigInt(a) && BigInt(b);
 7905};
 7906
 7907module.exports.bor = function(a, b) {
 7908    return BigInt(a) || BigInt(b);
 7909};
 7910
 7911module.exports.bnot = function(a) {
 7912    return !BigInt(a);
 7913};
 7914
 7915
 7916},{"assert":1}],25:[function(require,module,exports){
 7917
 7918const supportsNativeBigInt = typeof BigInt === "function";
 7919if (supportsNativeBigInt) {
 7920    module.exports = require("./utils_native.js");
 7921} else {
 7922    module.exports = require("./utils_bigint.js");
 7923}
 7924
 7925
 7926},{"./utils_bigint.js":26,"./utils_native.js":27}],26:[function(require,module,exports){
 7927(function (Buffer){
 7928const assert = require("assert");
 7929const bigInt = require("big-integer");
 7930
 7931module.exports.stringifyBigInts = function stringifyBigInts(o) {
 7932    if ((typeof(o) == "bigint") || o.eq !== undefined)  {
 7933        return o.toString(10);
 7934    } else if (Array.isArray(o)) {
 7935        return o.map(stringifyBigInts);
 7936    } else if (typeof o == "object") {
 7937        const res = {};
 7938        for (let k in o) {
 7939            res[k] = stringifyBigInts(o[k]);
 7940        }
 7941        return res;
 7942    } else {
 7943        return o;
 7944    }
 7945};
 7946
 7947module.exports.unstringifyBigInts = function unstringifyBigInts(o) {
 7948    if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) ))  {
 7949        return bigInt(o);
 7950    } else if (Array.isArray(o)) {
 7951        return o.map(unstringifyBigInts);
 7952    } else if (typeof o == "object") {
 7953        const res = {};
 7954        for (let k in o) {
 7955            res[k] = unstringifyBigInts(o[k]);
 7956        }
 7957        return res;
 7958    } else {
 7959        return o;
 7960    }
 7961};
 7962
 7963module.exports.beBuff2int = function beBuff2int(buff) {
 7964    let res = bigInt.zero;
 7965    for (let i=0; i<buff.length; i++) {
 7966        const n = bigInt(buff[buff.length - i - 1]);
 7967        res = res.add(n.shiftLeft(i*8));
 7968    }
 7969    return res;
 7970};
 7971
 7972module.exports.beInt2Buff = function beInt2Buff(n, len) {
 7973    let r = n;
 7974    let o =len-1;
 7975    const buff = Buffer.alloc(len);
 7976    while ((r.gt(bigInt.zero))&&(o>=0)) {
 7977        let c = Number(r.and(bigInt("255")));
 7978        buff[o] = c;
 7979        o--;
 7980        r = r.shiftRight(8);
 7981    }
 7982    assert(r.eq(bigInt.zero));
 7983    return buff;
 7984};
 7985
 7986
 7987module.exports.leBuff2int = function leBuff2int (buff) {
 7988    let res = bigInt.zero;
 7989    for (let i=0; i<buff.length; i++) {
 7990        const n = bigInt(buff[i]);
 7991        res = res.add(n.shiftLeft(i*8));
 7992    }
 7993    return res;
 7994};
 7995
 7996module.exports.leInt2Buff = function leInt2Buff(n, len) {
 7997    let r = n;
 7998    let o =0;
 7999    const buff = Buffer.alloc(len);
 8000    while ((r.gt(bigInt.zero))&&(o<buff.length)) {
 8001        let c = Number(r.and(bigInt(255)));
 8002        buff[o] = c;
 8003        o++;
 8004        r = r.shiftRight(8);
 8005    }
 8006    assert(r.eq(bigInt.zero));
 8007    return buff;
 8008};
 8009
 8010}).call(this,require("buffer").Buffer)
 8011},{"assert":1,"big-integer":6,"buffer":8}],27:[function(require,module,exports){
 8012(function (Buffer){
 8013/* global BigInt */
 8014const assert = require("assert");
 8015
 8016module.exports.stringifyBigInts = function stringifyBigInts(o) {
 8017    if ((typeof(o) == "bigint") || o.eq !== undefined)  {
 8018        return o.toString(10);
 8019    } else if (Array.isArray(o)) {
 8020        return o.map(stringifyBigInts);
 8021    } else if (typeof o == "object") {
 8022        const res = {};
 8023        for (let k in o) {
 8024            res[k] = stringifyBigInts(o[k]);
 8025        }
 8026        return res;
 8027    } else {
 8028        return o;
 8029    }
 8030};
 8031
 8032module.exports.unstringifyBigInts = function unstringifyBigInts(o) {
 8033    if ((typeof(o) == "string") && (/^[0-9]+$/.test(o) ))  {
 8034        return BigInt(o);
 8035    } else if (Array.isArray(o)) {
 8036        return o.map(unstringifyBigInts);
 8037    } else if (typeof o == "object") {
 8038        const res = {};
 8039        for (let k in o) {
 8040            res[k] = unstringifyBigInts(o[k]);
 8041        }
 8042        return res;
 8043    } else {
 8044        return o;
 8045    }
 8046};
 8047
 8048module.exports.beBuff2int = function beBuff2int(buff) {
 8049    let res = 0n;
 8050    let i = buff.length;
 8051    while (i>0) {
 8052        if (i >= 4) {
 8053            i -= 4;
 8054            res += BigInt(buff.readUInt32BE(i)) << BigInt( i*8);
 8055        } else if (i >= 2) {
 8056            i -= 2;
 8057            res += BigInt(buff.readUInt16BE(i)) << BigInt( i*8);
 8058        } else {
 8059            i -= 1;
 8060            res += BigInt(buff.readUInt8(i)) << BigInt( i*8);
 8061        }
 8062    }
 8063    return res;
 8064};
 8065
 8066module.exports.beInt2Buff = function beInt2Buff(n, len) {
 8067    let r = n;
 8068    const buff = Buffer.alloc(len);
 8069    let o = len;
 8070    while (o > 0) {
 8071        if (o-4 >= 0) {
 8072            o -= 4;
 8073            buff.writeUInt32BE(Number(r & 0xFFFFFFFFn), o);
 8074            r = r >> 32n;
 8075        } else if (o-2 >= 0) {
 8076            o -= 2;
 8077            buff.writeUInt16BE(Number(r & 0xFFFFn), o);
 8078            r = r >> 16n;
 8079        } else {
 8080            o -= 1;
 8081            buff.writeUInt8(Number(r & 0xFFn),o );
 8082            r = r >> 8n;
 8083        }
 8084    }
 8085    assert(r == 0n);
 8086    return buff;
 8087};
 8088
 8089
 8090module.exports.leBuff2int = function leBuff2int(buff) {
 8091    let res = 0n;
 8092    let i = 0;
 8093    while (i<buff.length) {
 8094        if (i + 4 <= buff.length) {
 8095            res += BigInt(buff.readUInt32LE(i)) << BigInt( i*8);
 8096            i += 4;
 8097        } else if (i + 4 <= buff.length) {
 8098            res += BigInt(buff.readUInt16LE(i)) << BigInt( i*8);
 8099            i += 2;
 8100        } else {
 8101            res += BigInt(buff.readUInt8(i)) << BigInt( i*8);
 8102            i += 1;
 8103        }
 8104    }
 8105    return res;
 8106};
 8107
 8108module.exports.leInt2Buff = function leInt2Buff(n, len) {
 8109    let r = n;
 8110    const buff = Buffer.alloc(len);
 8111    let o = 0;
 8112    while (o < len) {
 8113        if (o+4 <= len) {
 8114            buff.writeUInt32LE(Number(r & 0xFFFFFFFFn), o );
 8115            o += 4;
 8116            r = r >> 32n;
 8117        } else if (o+2 <= len) {
 8118            buff.writeUInt16LE(Number(r & 0xFFFFn), o );
 8119            o += 2;
 8120            r = r >> 16n;
 8121        } else {
 8122            buff.writeUInt8(Number(r & 0xFFn), o );
 8123            o += 1;
 8124            r = r >> 8n;
 8125        }
 8126    }
 8127    assert(r == 0n);
 8128    return buff;
 8129};
 8130
 8131}).call(this,require("buffer").Buffer)
 8132},{"assert":1,"buffer":8}],28:[function(require,module,exports){
 8133exports.read = function (buffer, offset, isLE, mLen, nBytes) {
 8134  var e, m
 8135  var eLen = (nBytes * 8) - mLen - 1
 8136  var eMax = (1 << eLen) - 1
 8137  var eBias = eMax >> 1
 8138  var nBits = -7
 8139  var i = isLE ? (nBytes - 1) : 0
 8140  var d = isLE ? -1 : 1
 8141  var s = buffer[offset + i]
 8142
 8143  i += d
 8144
 8145  e = s & ((1 << (-nBits)) - 1)
 8146  s >>= (-nBits)
 8147  nBits += eLen
 8148  for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
 8149
 8150  m = e & ((1 << (-nBits)) - 1)
 8151  e >>= (-nBits)
 8152  nBits += mLen
 8153  for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
 8154
 8155  if (e === 0) {
 8156    e = 1 - eBias
 8157  } else if (e === eMax) {
 8158    return m ? NaN : ((s ? -1 : 1) * Infinity)
 8159  } else {
 8160    m = m + Math.pow(2, mLen)
 8161    e = e - eBias
 8162  }
 8163  return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
 8164}
 8165
 8166exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
 8167  var e, m, c
 8168  var eLen = (nBytes * 8) - mLen - 1
 8169  var eMax = (1 << eLen) - 1
 8170  var eBias = eMax >> 1
 8171  var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
 8172  var i = isLE ? 0 : (nBytes - 1)
 8173  var d = isLE ? 1 : -1
 8174  var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
 8175
 8176  value = Math.abs(value)
 8177
 8178  if (isNaN(value) || value === Infinity) {
 8179    m = isNaN(value) ? 1 : 0
 8180    e = eMax
 8181  } else {
 8182    e = Math.floor(Math.log(value) / Math.LN2)
 8183    if (value * (c = Math.pow(2, -e)) < 1) {
 8184      e--
 8185      c *= 2
 8186    }
 8187    if (e + eBias >= 1) {
 8188      value += rt / c
 8189    } else {
 8190      value += rt * Math.pow(2, 1 - eBias)
 8191    }
 8192    if (value * c >= 2) {
 8193      e++
 8194      c /= 2
 8195    }
 8196
 8197    if (e + eBias >= eMax) {
 8198      m = 0
 8199      e = eMax
 8200    } else if (e + eBias >= 1) {
 8201      m = ((value * c) - 1) * Math.pow(2, mLen)
 8202      e = e + eBias
 8203    } else {
 8204      m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
 8205      e = 0
 8206    }
 8207  }
 8208
 8209  for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
 8210
 8211  e = (e << mLen) | m
 8212  eLen += mLen
 8213  for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
 8214
 8215  buffer[offset + i - d] |= s * 128
 8216}
 8217
 8218},{}],29:[function(require,module,exports){
 8219if (typeof Object.create === 'function') {
 8220  // implementation from standard node.js 'util' module
 8221  module.exports = function inherits(ctor, superCtor) {
 8222    if (superCtor) {
 8223      ctor.super_ = superCtor
 8224      ctor.prototype = Object.create(superCtor.prototype, {
 8225        constructor: {
 8226          value: ctor,
 8227          enumerable: false,
 8228          writable: true,
 8229          configurable: true
 8230        }
 8231      })
 8232    }
 8233  };
 8234} else {
 8235  // old school shim for old browsers
 8236  module.exports = function inherits(ctor, superCtor) {
 8237    if (superCtor) {
 8238      ctor.super_ = superCtor
 8239      var TempCtor = function () {}
 8240      TempCtor.prototype = superCtor.prototype
 8241      ctor.prototype = new TempCtor()
 8242      ctor.prototype.constructor = ctor
 8243    }
 8244  }
 8245}
 8246
 8247},{}],30:[function(require,module,exports){
 8248/*!
 8249 * Determine if an object is a Buffer
 8250 *
 8251 * @author   Feross Aboukhadijeh <https://feross.org>
 8252 * @license  MIT
 8253 */
 8254
 8255// The _isBuffer check is for Safari 5-7 support, because it's missing
 8256// Object.prototype.constructor. Remove this eventually
 8257module.exports = function (obj) {
 8258  return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
 8259}
 8260
 8261function isBuffer (obj) {
 8262  return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
 8263}
 8264
 8265// For Node v0.10 support. Remove this eventually.
 8266function isSlowBuffer (obj) {
 8267  return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
 8268}
 8269
 8270},{}],31:[function(require,module,exports){
 8271var toString = {}.toString;
 8272
 8273module.exports = Array.isArray || function (arr) {
 8274  return toString.call(arr) == '[object Array]';
 8275};
 8276
 8277},{}],32:[function(require,module,exports){
 8278module.exports = require('./lib/api')(require('./lib/keccak'))
 8279
 8280},{"./lib/api":33,"./lib/keccak":37}],33:[function(require,module,exports){
 8281const createKeccak = require('./keccak')
 8282const createShake = require('./shake')
 8283
 8284module.exports = function (KeccakState) {
 8285  const Keccak = createKeccak(KeccakState)
 8286  const Shake = createShake(KeccakState)
 8287
 8288  return function (algorithm, options) {
 8289    const hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm
 8290    switch (hash) {
 8291      case 'keccak224': return new Keccak(1152, 448, null, 224, options)
 8292      case 'keccak256': return new Keccak(1088, 512, null, 256, options)
 8293      case 'keccak384': return new Keccak(832, 768, null, 384, options)
 8294      case 'keccak512': return new Keccak(576, 1024, null, 512, options)
 8295
 8296      case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options)
 8297      case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options)
 8298      case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options)
 8299      case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options)
 8300
 8301      case 'shake128': return new Shake(1344, 256, 0x1f, options)
 8302      case 'shake256': return new Shake(1088, 512, 0x1f, options)
 8303
 8304      default: throw new Error('Invald algorithm: ' + algorithm)
 8305    }
 8306  }
 8307}
 8308
 8309},{"./keccak":34,"./shake":35}],34:[function(require,module,exports){
 8310(function (Buffer){
 8311const { Transform } = require('stream')
 8312
 8313module.exports = (KeccakState) => class Keccak extends Transform {
 8314  constructor (rate, capacity, delimitedSuffix, hashBitLength, options) {
 8315    super(options)
 8316
 8317    this._rate = rate
 8318    this._capacity = capacity
 8319    this._delimitedSuffix = delimitedSuffix
 8320    this._hashBitLength = hashBitLength
 8321    this._options = options
 8322
 8323    this._state = new KeccakState()
 8324    this._state.initialize(rate, capacity)
 8325    this._finalized = false
 8326  }
 8327
 8328  _transform (chunk, encoding, callback) {
 8329    let error = null
 8330    try {
 8331      this.update(chunk, encoding)
 8332    } catch (err) {
 8333      error = err
 8334    }
 8335
 8336    callback(error)
 8337  }
 8338
 8339  _flush (callback) {
 8340    let error = null
 8341    try {
 8342      this.push(this.digest())
 8343    } catch (err) {
 8344      error = err
 8345    }
 8346
 8347    callback(error)
 8348  }
 8349
 8350  update (data, encoding) {
 8351    if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
 8352    if (this._finalized) throw new Error('Digest already called')
 8353    if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
 8354
 8355    this._state.absorb(data)
 8356
 8357    return this
 8358  }
 8359
 8360  digest (encoding) {
 8361    if (this._finalized) throw new Error('Digest already called')
 8362    this._finalized = true
 8363
 8364    if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix)
 8365    let digest = this._state.squeeze(this._hashBitLength / 8)
 8366    if (encoding !== undefined) digest = digest.toString(encoding)
 8367
 8368    this._resetState()
 8369
 8370    return digest
 8371  }
 8372
 8373  // remove result from memory
 8374  _resetState () {
 8375    this._state.initialize(this._rate, this._capacity)
 8376    return this
 8377  }
 8378
 8379  // because sometimes we need hash right now and little later
 8380  _clone () {
 8381    const clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options)
 8382    this._state.copy(clone._state)
 8383    clone._finalized = this._finalized
 8384
 8385    return clone
 8386  }
 8387}
 8388
 8389}).call(this,require("buffer").Buffer)
 8390},{"buffer":8,"stream":51}],35:[function(require,module,exports){
 8391(function (Buffer){
 8392const { Transform } = require('stream')
 8393
 8394module.exports = (KeccakState) => class Shake extends Transform {
 8395  constructor (rate, capacity, delimitedSuffix, options) {
 8396    super(options)
 8397
 8398    this._rate = rate
 8399    this._capacity = capacity
 8400    this._delimitedSuffix = delimitedSuffix
 8401    this._options = options
 8402
 8403    this._state = new KeccakState()
 8404    this._state.initialize(rate, capacity)
 8405    this._finalized = false
 8406  }
 8407
 8408  _transform (chunk, encoding, callback) {
 8409    let error = null
 8410    try {
 8411      this.update(chunk, encoding)
 8412    } catch (err) {
 8413      error = err
 8414    }
 8415
 8416    callback(error)
 8417  }
 8418
 8419  _flush () {}
 8420
 8421  _read (size) {
 8422    this.push(this.squeeze(size))
 8423  }
 8424
 8425  update (data, encoding) {
 8426    if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
 8427    if (this._finalized) throw new Error('Squeeze already called')
 8428    if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
 8429
 8430    this._state.absorb(data)
 8431
 8432    return this
 8433  }
 8434
 8435  squeeze (dataByteLength, encoding) {
 8436    if (!this._finalized) {
 8437      this._finalized = true
 8438      this._state.absorbLastFewBits(this._delimitedSuffix)
 8439    }
 8440
 8441    let data = this._state.squeeze(dataByteLength)
 8442    if (encoding !== undefined) data = data.toString(encoding)
 8443
 8444    return data
 8445  }
 8446
 8447  _resetState () {
 8448    this._state.initialize(this._rate, this._capacity)
 8449    return this
 8450  }
 8451
 8452  _clone () {
 8453    const clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options)
 8454    this._state.copy(clone._state)
 8455    clone._finalized = this._finalized
 8456
 8457    return clone
 8458  }
 8459}
 8460
 8461}).call(this,require("buffer").Buffer)
 8462},{"buffer":8,"stream":51}],36:[function(require,module,exports){
 8463const 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]
 8464
 8465exports.p1600 = function (s) {
 8466  for (let round = 0; round < 24; ++round) {
 8467    // theta
 8468    const lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]
 8469    const hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]
 8470    const lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]
 8471    const hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]
 8472    const lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]
 8473    const hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]
 8474    const lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]
 8475    const hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]
 8476    const lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]
 8477    const hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]
 8478
 8479    let lo = lo4 ^ (lo1 << 1 | hi1 >>> 31)
 8480    let hi = hi4 ^ (hi1 << 1 | lo1 >>> 31)
 8481    const t1slo0 = s[0] ^ lo
 8482    const t1shi0 = s[1] ^ hi
 8483    const t1slo5 = s[10] ^ lo
 8484    const t1shi5 = s[11] ^ hi
 8485    const t1slo10 = s[20] ^ lo
 8486    const t1shi10 = s[21] ^ hi
 8487    const t1slo15 = s[30] ^ lo
 8488    const t1shi15 = s[31] ^ hi
 8489    const t1slo20 = s[40] ^ lo
 8490    const t1shi20 = s[41] ^ hi
 8491    lo = lo0 ^ (lo2 << 1 | hi2 >>> 31)
 8492    hi = hi0 ^ (hi2 << 1 | lo2 >>> 31)
 8493    const t1slo1 = s[2] ^ lo
 8494    const t1shi1 = s[3] ^ hi
 8495    const t1slo6 = s[12] ^ lo
 8496    const t1shi6 = s[13] ^ hi
 8497    const t1slo11 = s[22] ^ lo
 8498    const t1shi11 = s[23] ^ hi
 8499    const t1slo16 = s[32] ^ lo
 8500    const t1shi16 = s[33] ^ hi
 8501    const t1slo21 = s[42] ^ lo
 8502    const t1shi21 = s[43] ^ hi
 8503    lo = lo1 ^ (lo3 << 1 | hi3 >>> 31)
 8504    hi = hi1 ^ (hi3 << 1 | lo3 >>> 31)
 8505    const t1slo2 = s[4] ^ lo
 8506    const t1shi2 = s[5] ^ hi
 8507    const t1slo7 = s[14] ^ lo
 8508    const t1shi7 = s[15] ^ hi
 8509    const t1slo12 = s[24] ^ lo
 8510    const t1shi12 = s[25] ^ hi
 8511    const t1slo17 = s[34] ^ lo
 8512    const t1shi17 = s[35] ^ hi
 8513    const t1slo22 = s[44] ^ lo
 8514    const t1shi22 = s[45] ^ hi
 8515    lo = lo2 ^ (lo4 << 1 | hi4 >>> 31)
 8516    hi = hi2 ^ (hi4 << 1 | lo4 >>> 31)
 8517    const t1slo3 = s[6] ^ lo
 8518    const t1shi3 = s[7] ^ hi
 8519    const t1slo8 = s[16] ^ lo
 8520    const t1shi8 = s[17] ^ hi
 8521    const t1slo13 = s[26] ^ lo
 8522    const t1shi13 = s[27] ^ hi
 8523    const t1slo18 = s[36] ^ lo
 8524    const t1shi18 = s[37] ^ hi
 8525    const t1slo23 = s[46] ^ lo
 8526    const t1shi23 = s[47] ^ hi
 8527    lo = lo3 ^ (lo0 << 1 | hi0 >>> 31)
 8528    hi = hi3 ^ (hi0 << 1 | lo0 >>> 31)
 8529    const t1slo4 = s[8] ^ lo
 8530    const t1shi4 = s[9] ^ hi
 8531    const t1slo9 = s[18] ^ lo
 8532    const t1shi9 = s[19] ^ hi
 8533    const t1slo14 = s[28] ^ lo
 8534    const t1shi14 = s[29] ^ hi
 8535    const t1slo19 = s[38] ^ lo
 8536    const t1shi19 = s[39] ^ hi
 8537    const t1slo24 = s[48] ^ lo
 8538    const t1shi24 = s[49] ^ hi
 8539
 8540    // rho & pi
 8541    const t2slo0 = t1slo0
 8542    const t2shi0 = t1shi0
 8543    const t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28)
 8544    const t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28)
 8545    const t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29)
 8546    const t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29)
 8547    const t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23)
 8548    const t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23)
 8549    const t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14)
 8550    const t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14)
 8551    const t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31)
 8552    const t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31)
 8553    const t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20)
 8554    const t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20)
 8555    const t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22)
 8556    const t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22)
 8557    const t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19)
 8558    const t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19)
 8559    const t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30)
 8560    const t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30)
 8561    const t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2)
 8562    const t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2)
 8563    const t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26)
 8564    const t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26)
 8565    const t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21)
 8566    const t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21)
 8567    const t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17)
 8568    const t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17)
 8569    const t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3)
 8570    const t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3)
 8571    const t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4)
 8572    const t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4)
 8573    const t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9)
 8574    const t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9)
 8575    const t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7)
 8576    const t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7)
 8577    const t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11)
 8578    const t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11)
 8579    const t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8)
 8580    const t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8)
 8581    const t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5)
 8582    const t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5)
 8583    const t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12)
 8584    const t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12)
 8585    const t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25)
 8586    const t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25)
 8587    const t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24)
 8588    const t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24)
 8589    const t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18)
 8590    const t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18)
 8591
 8592    // chi
 8593    s[0] = t2slo0 ^ (~t2slo1 & t2slo2)
 8594    s[1] = t2shi0 ^ (~t2shi1 & t2shi2)
 8595    s[10] = t2slo5 ^ (~t2slo6 & t2slo7)
 8596    s[11] = t2shi5 ^ (~t2shi6 & t2shi7)
 8597    s[20] = t2slo10 ^ (~t2slo11 & t2slo12)
 8598    s[21] = t2shi10 ^ (~t2shi11 & t2shi12)
 8599    s[30] = t2slo15 ^ (~t2slo16 & t2slo17)
 8600    s[31] = t2shi15 ^ (~t2shi16 & t2shi17)
 8601    s[40] = t2slo20 ^ (~t2slo21 & t2slo22)
 8602    s[41] = t2shi20 ^ (~t2shi21 & t2shi22)
 8603    s[2] = t2slo1 ^ (~t2slo2 & t2slo3)
 8604    s[3] = t2shi1 ^ (~t2shi2 & t2shi3)
 8605    s[12] = t2slo6 ^ (~t2slo7 & t2slo8)
 8606    s[13] = t2shi6 ^ (~t2shi7 & t2shi8)
 8607    s[22] = t2slo11 ^ (~t2slo12 & t2slo13)
 8608    s[23] = t2shi11 ^ (~t2shi12 & t2shi13)
 8609    s[32] = t2slo16 ^ (~t2slo17 & t2slo18)
 8610    s[33] = t2shi16 ^ (~t2shi17 & t2shi18)
 8611    s[42] = t2slo21 ^ (~t2slo22 & t2slo23)
 8612    s[43] = t2shi21 ^ (~t2shi22 & t2shi23)
 8613    s[4] = t2slo2 ^ (~t2slo3 & t2slo4)
 8614    s[5] = t2shi2 ^ (~t2shi3 & t2shi4)
 8615    s[14] = t2slo7 ^ (~t2slo8 & t2slo9)
 8616    s[15] = t2shi7 ^ (~t2shi8 & t2shi9)
 8617    s[24] = t2slo12 ^ (~t2slo13 & t2slo14)
 8618    s[25] = t2shi12 ^ (~t2shi13 & t2shi14)
 8619    s[34] = t2slo17 ^ (~t2slo18 & t2slo19)
 8620    s[35] = t2shi17 ^ (~t2shi18 & t2shi19)
 8621    s[44] = t2slo22 ^ (~t2slo23 & t2slo24)
 8622    s[45] = t2shi22 ^ (~t2shi23 & t2shi24)
 8623    s[6] = t2slo3 ^ (~t2slo4 & t2slo0)
 8624    s[7] = t2shi3 ^ (~t2shi4 & t2shi0)
 8625    s[16] = t2slo8 ^ (~t2slo9 & t2slo5)
 8626    s[17] = t2shi8 ^ (~t2shi9 & t2shi5)
 8627    s[26] = t2slo13 ^ (~t2slo14 & t2slo10)
 8628    s[27] = t2shi13 ^ (~t2shi14 & t2shi10)
 8629    s[36] = t2slo18 ^ (~t2slo19 & t2slo15)
 8630    s[37] = t2shi18 ^ (~t2shi19 & t2shi15)
 8631    s[46] = t2slo23 ^ (~t2slo24 & t2slo20)
 8632    s[47] = t2shi23 ^ (~t2shi24 & t2shi20)
 8633    s[8] = t2slo4 ^ (~t2slo0 & t2slo1)
 8634    s[9] = t2shi4 ^ (~t2shi0 & t2shi1)
 8635    s[18] = t2slo9 ^ (~t2slo5 & t2slo6)
 8636    s[19] = t2shi9 ^ (~t2shi5 & t2shi6)
 8637    s[28] = t2slo14 ^ (~t2slo10 & t2slo11)
 8638    s[29] = t2shi14 ^ (~t2shi10 & t2shi11)
 8639    s[38] = t2slo19 ^ (~t2slo15 & t2slo16)
 8640    s[39] = t2shi19 ^ (~t2shi15 & t2shi16)
 8641    s[48] = t2slo24 ^ (~t2slo20 & t2slo21)
 8642    s[49] = t2shi24 ^ (~t2shi20 & t2shi21)
 8643
 8644    // iota
 8645    s[0] ^= P1600_ROUND_CONSTANTS[round * 2]
 8646    s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]
 8647  }
 8648}
 8649
 8650},{}],37:[function(require,module,exports){
 8651(function (Buffer){
 8652const keccakState = require('./keccak-state-unroll')
 8653
 8654function Keccak () {
 8655  // much faster than `new Array(50)`
 8656  this.state = [
 8657    0, 0, 0, 0, 0,
 8658    0, 0, 0, 0, 0,
 8659    0, 0, 0, 0, 0,
 8660    0, 0, 0, 0, 0,
 8661    0, 0, 0, 0, 0
 8662  ]
 8663
 8664  this.blockSize = null
 8665  this.count = 0
 8666  this.squeezing = false
 8667}
 8668
 8669Keccak.prototype.initialize = function (rate, capacity) {
 8670  for (let i = 0; i < 50; ++i) this.state[i] = 0
 8671  this.blockSize = rate / 8
 8672  this.count = 0
 8673  this.squeezing = false
 8674}
 8675
 8676Keccak.prototype.absorb = function (data) {
 8677  for (let i = 0; i < data.length; ++i) {
 8678    this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4))
 8679    this.count += 1
 8680    if (this.count === this.blockSize) {
 8681      keccakState.p1600(this.state)
 8682      this.count = 0
 8683    }
 8684  }
 8685}
 8686
 8687Keccak.prototype.absorbLastFewBits = function (bits) {
 8688  this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4))
 8689  if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state)
 8690  this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4))
 8691  keccakState.p1600(this.state)
 8692  this.count = 0
 8693  this.squeezing = true
 8694}
 8695
 8696Keccak.prototype.squeeze = function (length) {
 8697  if (!this.squeezing) this.absorbLastFewBits(0x01)
 8698
 8699  const output = Buffer.alloc(length)
 8700  for (let i = 0; i < length; ++i) {
 8701    output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff
 8702    this.count += 1
 8703    if (this.count === this.blockSize) {
 8704      keccakState.p1600(this.state)
 8705      this.count = 0
 8706    }
 8707  }
 8708
 8709  return output
 8710}
 8711
 8712Keccak.prototype.copy = function (dest) {
 8713  for (let i = 0; i < 50; ++i) dest.state[i] = this.state[i]
 8714  dest.blockSize = this.blockSize
 8715  dest.count = this.count
 8716  dest.squeezing = this.squeezing
 8717}
 8718
 8719module.exports = Keccak
 8720
 8721}).call(this,require("buffer").Buffer)
 8722},{"./keccak-state-unroll":36,"buffer":8}],38:[function(require,module,exports){
 8723/*
 8724object-assign
 8725(c) Sindre Sorhus
 8726@license MIT
 8727*/
 8728
 8729'use strict';
 8730/* eslint-disable no-unused-vars */
 8731var getOwnPropertySymbols = Object.getOwnPropertySymbols;
 8732var hasOwnProperty = Object.prototype.hasOwnProperty;
 8733var propIsEnumerable = Object.prototype.propertyIsEnumerable;
 8734
 8735function toObject(val) {
 8736	if (val === null || val === undefined) {
 8737		throw new TypeError('Object.assign cannot be called with null or undefined');
 8738	}
 8739
 8740	return Object(val);
 8741}
 8742
 8743function shouldUseNative() {
 8744	try {
 8745		if (!Object.assign) {
 8746			return false;
 8747		}
 8748
 8749		// Detect buggy property enumeration order in older V8 versions.
 8750
 8751		// https://bugs.chromium.org/p/v8/issues/detail?id=4118
 8752		var test1 = new String('abc');  // eslint-disable-line no-new-wrappers
 8753		test1[5] = 'de';
 8754		if (Object.getOwnPropertyNames(test1)[0] === '5') {
 8755			return false;
 8756		}
 8757
 8758		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
 8759		var test2 = {};
 8760		for (var i = 0; i < 10; i++) {
 8761			test2['_' + String.fromCharCode(i)] = i;
 8762		}
 8763		var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
 8764			return test2[n];
 8765		});
 8766		if (order2.join('') !== '0123456789') {
 8767			return false;
 8768		}
 8769
 8770		// https://bugs.chromium.org/p/v8/issues/detail?id=3056
 8771		var test3 = {};
 8772		'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
 8773			test3[letter] = letter;
 8774		});
 8775		if (Object.keys(Object.assign({}, test3)).join('') !==
 8776				'abcdefghijklmnopqrst') {
 8777			return false;
 8778		}
 8779
 8780		return true;
 8781	} catch (err) {
 8782		// We don't expect any of the above to throw, but better to be safe.
 8783		return false;
 8784	}
 8785}
 8786
 8787module.exports = shouldUseNative() ? Object.assign : function (target, source) {
 8788	var from;
 8789	var to = toObject(target);
 8790	var symbols;
 8791
 8792	for (var s = 1; s < arguments.length; s++) {
 8793		from = Object(arguments[s]);
 8794
 8795		for (var key in from) {
 8796			if (hasOwnProperty.call(from, key)) {
 8797				to[key] = from[key];
 8798			}
 8799		}
 8800
 8801		if (getOwnPropertySymbols) {
 8802			symbols = getOwnPropertySymbols(from);
 8803			for (var i = 0; i < symbols.length; i++) {
 8804				if (propIsEnumerable.call(from, symbols[i])) {
 8805					to[symbols[i]] = from[symbols[i]];
 8806				}
 8807			}
 8808		}
 8809	}
 8810
 8811	return to;
 8812};
 8813
 8814},{}],39:[function(require,module,exports){
 8815(function (process){
 8816'use strict';
 8817
 8818if (typeof process === 'undefined' ||
 8819    !process.version ||
 8820    process.version.indexOf('v0.') === 0 ||
 8821    process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
 8822  module.exports = { nextTick: nextTick };
 8823} else {
 8824  module.exports = process
 8825}
 8826
 8827function nextTick(fn, arg1, arg2, arg3) {
 8828  if (typeof fn !== 'function') {
 8829    throw new TypeError('"callback" argument must be a function');
 8830  }
 8831  var len = arguments.length;
 8832  var args, i;
 8833  switch (len) {
 8834  case 0:
 8835  case 1:
 8836    return process.nextTick(fn);
 8837  case 2:
 8838    return process.nextTick(function afterTickOne() {
 8839      fn.call(null, arg1);
 8840    });
 8841  case 3:
 8842    return process.nextTick(function afterTickTwo() {
 8843      fn.call(null, arg1, arg2);
 8844    });
 8845  case 4:
 8846    return process.nextTick(function afterTickThree() {
 8847      fn.call(null, arg1, arg2, arg3);
 8848    });
 8849  default:
 8850    args = new Array(len - 1);
 8851    i = 0;
 8852    while (i < args.length) {
 8853      args[i++] = arguments[i];
 8854    }
 8855    return process.nextTick(function afterTick() {
 8856      fn.apply(null, args);
 8857    });
 8858  }
 8859}
 8860
 8861
 8862}).call(this,require('_process'))
 8863},{"_process":9}],40:[function(require,module,exports){
 8864/* eslint-disable node/no-deprecated-api */
 8865var buffer = require('buffer')
 8866var Buffer = buffer.Buffer
 8867
 8868// alternative to using Object.keys for old browsers
 8869function copyProps (src, dst) {
 8870  for (var key in src) {
 8871    dst[key] = src[key]
 8872  }
 8873}
 8874if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
 8875  module.exports = buffer
 8876} else {
 8877  // Copy properties from require('buffer')
 8878  copyProps(buffer, exports)
 8879  exports.Buffer = SafeBuffer
 8880}
 8881
 8882function SafeBuffer (arg, encodingOrOffset, length) {
 8883  return Buffer(arg, encodingOrOffset, length)
 8884}
 8885
 8886// Copy static methods from Buffer
 8887copyProps(Buffer, SafeBuffer)
 8888
 8889SafeBuffer.from = function (arg, encodingOrOffset, length) {
 8890  if (typeof arg === 'number') {
 8891    throw new TypeError('Argument must not be a number')
 8892  }
 8893  return Buffer(arg, encodingOrOffset, length)
 8894}
 8895
 8896SafeBuffer.alloc = function (size, fill, encoding) {
 8897  if (typeof size !== 'number') {
 8898    throw new TypeError('Argument must be a number')
 8899  }
 8900  var buf = Buffer(size)
 8901  if (fill !== undefined) {
 8902    if (typeof encoding === 'string') {
 8903      buf.fill(fill, encoding)
 8904    } else {
 8905      buf.fill(fill)
 8906    }
 8907  } else {
 8908    buf.fill(0)
 8909  }
 8910  return buf
 8911}
 8912
 8913SafeBuffer.allocUnsafe = function (size) {
 8914  if (typeof size !== 'number') {
 8915    throw new TypeError('Argument must be a number')
 8916  }
 8917  return Buffer(size)
 8918}
 8919
 8920SafeBuffer.allocUnsafeSlow = function (size) {
 8921  if (typeof size !== 'number') {
 8922    throw new TypeError('Argument must be a number')
 8923  }
 8924  return buffer.SlowBuffer(size)
 8925}
 8926
 8927},{"buffer":8}],41:[function(require,module,exports){
 8928/*
 8929    Copyright 2018 0kims association.
 8930
 8931    This file is part of snarkjs.
 8932
 8933    snarkjs is a free software: you can redistribute it and/or
 8934    modify it under the terms of the GNU General Public License as published by the
 8935    Free Software Foundation, either version 3 of the License, or (at your option)
 8936    any later version.
 8937
 8938    snarkjs is distributed in the hope that it will be useful,
 8939    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 8940    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 8941    more details.
 8942
 8943    You should have received a copy of the GNU General Public License along with
 8944    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 8945*/
 8946
 8947exports.original = {
 8948    setup: require("./src/setup_original.js"),
 8949    genProof: require("./src/prover_original.js"),
 8950    isValid: require("./src/verifier_original.js")
 8951};
 8952exports.groth = {
 8953    setup: require("./src/setup_groth.js"),
 8954    genProof: require("./src/prover_groth.js"),
 8955    isValid: require("./src/verifier_groth.js")
 8956};
 8957exports.kimleeoh = {
 8958    setup: require("./src/setup_kimleeoh.js"),
 8959    genProof: require("./src/prover_kimleeoh.js"),
 8960    isValid: require("./src/verifier_kimleeoh.js")
 8961};
 8962
 8963
 8964},{"./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){
 8965/*
 8966    Copyright 2018 0kims association.
 8967
 8968    This file is part of snarkjs.
 8969
 8970    snarkjs is a free software: you can redistribute it and/or
 8971    modify it under the terms of the GNU General Public License as published by the
 8972    Free Software Foundation, either version 3 of the License, or (at your option)
 8973    any later version.
 8974
 8975    snarkjs is distributed in the hope that it will be useful,
 8976    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 8977    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 8978    more details.
 8979
 8980    You should have received a copy of the GNU General Public License along with
 8981    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 8982*/
 8983
 8984/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
 8985
 8986const bn128 = require("ffjavascript").bn128;
 8987const PolField = require("ffjavascript").PolField;
 8988const ZqField = require("ffjavascript").ZqField;
 8989
 8990const PolF = new PolField(new ZqField(bn128.r));
 8991const G1 = bn128.G1;
 8992const G2 = bn128.G2;
 8993
 8994module.exports = function genProof(vk_proof, witness, verbose) {
 8995
 8996    const proof = {};
 8997
 8998    const r = PolF.F.random();
 8999    const s = PolF.F.random();
 9000
 9001/* Uncomment to generate a deterministic proof to debug
 9002    const r = PolF.F.zero;
 9003    const s = PolF.F.zero;
 9004*/
 9005
 9006
 9007    proof.pi_a = G1.zero;
 9008    proof.pi_b = G2.zero;
 9009    proof.pi_c = G1.zero;
 9010
 9011    let pib1 = G1.zero;
 9012
 9013
 9014    // Skip public entries and the "1" signal that are forced by the verifier
 9015
 9016    for (let s= 0; s< vk_proof.nVars; s++) {
 9017        // pi_a = pi_a + A[s] * witness[s];
 9018        proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
 9019
 9020        // pi_b = pi_b + B[s] * witness[s];
 9021        proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B2[s], witness[s]));
 9022
 9023        pib1 = G1.add( pib1, G1.mulScalar( vk_proof.B1[s], witness[s]));
 9024
 9025        if ((verbose)&&(s%1000 == 1)) console.log("A, B1, B2: ", s);
 9026
 9027    }
 9028
 9029    for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
 9030
 9031        // pi_a  = pi_a  + A[s]  * witness[s];
 9032        proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
 9033
 9034        if ((verbose)&&(s%1000 == 1)) console.log("C: ", s);
 9035    }
 9036
 9037    proof.pi_a  = G1.add( proof.pi_a, vk_proof.vk_alfa_1 );
 9038    proof.pi_a  = G1.add( proof.pi_a, G1.mulScalar( vk_proof.vk_delta_1, r ));
 9039
 9040    proof.pi_b  = G2.add( proof.pi_b, vk_proof.vk_beta_2 );
 9041    proof.pi_b  = G2.add( proof.pi_b, G2.mulScalar( vk_proof.vk_delta_2, s ));
 9042
 9043    pib1 = G1.add( pib1, vk_proof.vk_beta_1 );
 9044    pib1 = G1.add( pib1, G1.mulScalar( vk_proof.vk_delta_1, s ));
 9045
 9046    const h = calculateH(vk_proof, witness);
 9047
 9048    // proof.pi_c = G1.affine(proof.pi_c);
 9049    // console.log("pi_onlyc", proof.pi_c);
 9050
 9051    for (let i = 0; i < h.length; i++) {
 9052        // console.log(i + "->" + h[i].toString());
 9053        proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.hExps[i], h[i]));
 9054
 9055        if ((verbose)&&(i%1000 == 1)) console.log("H: ", i);
 9056    }
 9057
 9058    // proof.pi_c = G1.affine(proof.pi_c);
 9059    // console.log("pi_candh", proof.pi_c);
 9060
 9061    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( proof.pi_a, s ));
 9062    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( pib1, r ));
 9063    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( vk_proof.vk_delta_1, PolF.F.neg(PolF.F.mul(r,s) )));
 9064
 9065
 9066    const publicSignals = witness.slice(1, vk_proof.nPublic+1);
 9067
 9068    proof.pi_a = G1.affine(proof.pi_a);
 9069    proof.pi_b = G2.affine(proof.pi_b);
 9070    proof.pi_c = G1.affine(proof.pi_c);
 9071
 9072    proof.protocol = "groth";
 9073
 9074    return {proof, publicSignals};
 9075
 9076};
 9077
 9078
 9079/*
 9080// Old Method.  (It's clear for academic understanding)
 9081function calculateH(vk_proof, witness) {
 9082
 9083    const F = PolF.F;
 9084    const m = vk_proof.domainSize;
 9085    const polA_T = new Array(m).fill(PolF.F.zero);
 9086    const polB_T = new Array(m).fill(PolF.F.zero);
 9087    const polC_T = new Array(m).fill(PolF.F.zero);
 9088
 9089    for (let s=0; s<vk_proof.nVars; s++) {
 9090        for (let c in vk_proof.polsA[s]) {
 9091            polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
 9092        }
 9093        for (let c in vk_proof.polsB[s]) {
 9094            polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
 9095        }
 9096
 9097        for (let c in vk_proof.polsC[s]) {
 9098            polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
 9099        }
 9100
 9101    }
 9102
 9103    const polA_S = PolF.ifft(polA_T);
 9104    const polB_S = PolF.ifft(polB_T);
 9105
 9106    const polAB_S = PolF.mul(polA_S, polB_S);
 9107
 9108    const polC_S = PolF.ifft(polC_T);
 9109
 9110    const polABC_S = PolF.sub(polAB_S, polC_S);
 9111
 9112    const H_S = polABC_S.slice(m);
 9113
 9114    return H_S;
 9115}
 9116*/
 9117
 9118function calculateH(vk_proof, witness) {
 9119
 9120    const F = PolF.F;
 9121    const m = vk_proof.domainSize;
 9122    const polA_T = new Array(m).fill(PolF.F.zero);
 9123    const polB_T = new Array(m).fill(PolF.F.zero);
 9124
 9125    for (let s=0; s<vk_proof.nVars; s++) {
 9126        for (let c in vk_proof.polsA[s]) {
 9127            polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
 9128        }
 9129        for (let c in vk_proof.polsB[s]) {
 9130            polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
 9131        }
 9132    }
 9133
 9134    const polA_S = PolF.ifft(polA_T);
 9135    const polB_S = PolF.ifft(polB_T);
 9136
 9137    // F(wx) = [1, w, w^2, ...... w^(m-1)] in time is the same than shift in in frequency
 9138    const r = PolF.log2(m)+1;
 9139    PolF._setRoots(r);
 9140    for (let i=0; i<polA_S.length; i++) {
 9141        polA_S[i] = PolF.F.mul( polA_S[i], PolF.roots[r][i]);
 9142        polB_S[i] = PolF.F.mul( polB_S[i], PolF.roots[r][i]);
 9143    }
 9144
 9145    const polA_Todd = PolF.fft(polA_S);
 9146    const polB_Todd = PolF.fft(polB_S);
 9147
 9148    const polAB_T = new Array(polA_S.length*2);
 9149    for (let i=0; i<polA_S.length; i++) {
 9150        polAB_T[2*i] = PolF.F.mul( polA_T[i], polB_T[i]);
 9151        polAB_T[2*i+1] = PolF.F.mul( polA_Todd[i], polB_Todd[i]);
 9152    }
 9153
 9154    // We only need the to half of the fft, so we could optimize at least by m multiplications.
 9155    let H_S = PolF.ifft(polAB_T);
 9156
 9157    H_S = H_S.slice(m);
 9158
 9159    return H_S;
 9160
 9161}
 9162
 9163},{"ffjavascript":12}],43:[function(require,module,exports){
 9164(function (Buffer){
 9165/*
 9166    Copyright 2018 0kims association.
 9167
 9168    This file is part of snarkjs.
 9169
 9170    snarkjs is a free software: you can redistribute it and/or
 9171    modify it under the terms of the GNU General Public License as published by the
 9172    Free Software Foundation, either version 3 of the License, or (at your option)
 9173    any later version.
 9174
 9175    snarkjs is distributed in the hope that it will be useful,
 9176    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 9177    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 9178    more details.
 9179
 9180    You should have received a copy of the GNU General Public License along with
 9181    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 9182*/
 9183
 9184/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
 9185
 9186const bn128 = require("ffjavascript").bn128;
 9187const PolField = require("ffjavascript").PolField;
 9188const ZqField = require("ffjavascript").ZqField;
 9189const createKeccakHash = require("keccak");
 9190const utils = require("ffjavascript").utils;
 9191
 9192
 9193const PolF = new PolField(new ZqField(bn128.r));
 9194const G1 = bn128.G1;
 9195const G2 = bn128.G2;
 9196
 9197module.exports = function genProof(vk_proof, witness) {
 9198
 9199    const proof = {};
 9200
 9201    const r = PolF.F.random();
 9202    const s = PolF.F.random();
 9203
 9204//    const r = PolF.F.zero;
 9205//    const s = PolF.F.zero;
 9206
 9207/* Uncomment to generate a deterministic proof to debug
 9208    const r = PolF.F.zero;
 9209    const s = PolF.F.zero;
 9210*/
 9211
 9212
 9213    proof.pi_a = G1.zero;
 9214    proof.pi_b = G2.zero;
 9215    proof.pi_c = G1.zero;
 9216
 9217    let pib1 = G1.zero;
 9218    let piadelta = G1.zero;
 9219
 9220
 9221    // Skip public entries and the "1" signal that are forced by the verifier
 9222
 9223    for (let s= 0; s< vk_proof.nVars; s++) {
 9224        // pi_a = pi_a + A[s] * witness[s];
 9225        proof.pi_a = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
 9226
 9227        // pi_b = pi_b + B[s] * witness[s];
 9228        proof.pi_b = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B2[s], witness[s]));
 9229
 9230        piadelta = G1.add( piadelta, G1.mulScalar( vk_proof.Adelta[s], witness[s]));
 9231        pib1 = G1.add( pib1, G1.mulScalar( vk_proof.B1[s], witness[s]));
 9232    }
 9233
 9234    for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
 9235
 9236        // pi_a  = pi_a  + A[s]  * witness[s];
 9237        proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
 9238    }
 9239
 9240    proof.pi_a  = G1.add( proof.pi_a, vk_proof.vk_alfa_1 );
 9241    proof.pi_a  = G1.add( proof.pi_a, G1.mulScalar( G1.g, r ));
 9242
 9243    piadelta = G1.add( piadelta, vk_proof.vk_alfadelta_1);
 9244    piadelta = G1.add( piadelta, G1.mulScalar( vk_proof.vk_delta_1, r ));
 9245
 9246    proof.pi_b  = G2.add( proof.pi_b, vk_proof.vk_beta_2 );
 9247    proof.pi_b  = G2.add( proof.pi_b, G2.mulScalar( G2.g, s ));
 9248
 9249    pib1 = G1.add( pib1, vk_proof.vk_beta_1 );
 9250    pib1 = G1.add( pib1, G1.mulScalar( G1.g, s ));
 9251
 9252    proof.pi_a = G1.affine(proof.pi_a);
 9253    proof.pi_b = G2.affine(proof.pi_b);
 9254
 9255    const buff = Buffer.concat([
 9256        utils.beInt2Buff(proof.pi_a[0],32),
 9257        utils.beInt2Buff(proof.pi_a[1],32),
 9258        utils.beInt2Buff(proof.pi_b[0][0],32),
 9259        utils.beInt2Buff(proof.pi_b[0][1],32),
 9260        utils.beInt2Buff(proof.pi_b[1][0],32),
 9261        utils.beInt2Buff(proof.pi_b[1][1],32)
 9262    ]);
 9263
 9264    const h1buff = createKeccakHash("keccak256").update(buff).digest();
 9265    const h2buff = createKeccakHash("keccak256").update(h1buff).digest();
 9266
 9267    const h1 = utils.beBuff2int(h1buff);
 9268    const h2 = utils.beBuff2int(h2buff);
 9269
 9270    // const h1 = PolF.F.zero;
 9271    // const h2 = PolF.F.zero;
 9272
 9273    // console.log(h1.toString());
 9274    // console.log(h2.toString());
 9275
 9276    const h = calculateH(vk_proof, witness);
 9277
 9278    // proof.pi_c = G1.affine(proof.pi_c);
 9279    // console.log("pi_onlyc", proof.pi_c);
 9280
 9281    for (let i = 0; i < h.length; i++) {
 9282        // console.log(i + "->" + h[i].toString());
 9283        proof.pi_c = G1.add( proof.pi_c, G1.mulScalar( vk_proof.hExps[i], h[i]));
 9284    }
 9285
 9286    // proof.pi_c = G1.affine(proof.pi_c);
 9287    // console.log("pi_candh", proof.pi_c);
 9288
 9289    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( proof.pi_a, s ));
 9290    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( pib1, r ));
 9291    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( G1.g, PolF.F.neg(PolF.F.mul(r,s) )));
 9292
 9293    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( piadelta, h2 ));
 9294    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( pib1, h1 ));
 9295    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( vk_proof.vk_delta_1, PolF.F.mul(h1,h2)));
 9296
 9297    const publicSignals = witness.slice(1, vk_proof.nPublic+1);
 9298
 9299    proof.pi_c = G1.affine(proof.pi_c);
 9300
 9301    proof.protocol = "kimleeoh";
 9302
 9303    return {proof, publicSignals};
 9304
 9305};
 9306
 9307
 9308function calculateH(vk_proof, witness) {
 9309
 9310    const F = PolF.F;
 9311    const m = vk_proof.domainSize;
 9312    const polA_T = new Array(m).fill(PolF.F.zero);
 9313    const polB_T = new Array(m).fill(PolF.F.zero);
 9314    const polC_T = new Array(m).fill(PolF.F.zero);
 9315
 9316    for (let s=0; s<vk_proof.nVars; s++) {
 9317        for (let c in vk_proof.polsA[s]) {
 9318            polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
 9319        }
 9320        for (let c in vk_proof.polsB[s]) {
 9321            polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
 9322        }
 9323        for (let c in vk_proof.polsC[s]) {
 9324            polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
 9325        }
 9326    }
 9327
 9328    const polA_S = PolF.ifft(polA_T);
 9329    const polB_S = PolF.ifft(polB_T);
 9330
 9331    const polAB_S = PolF.mul(polA_S, polB_S);
 9332
 9333    const polC_S = PolF.ifft(polC_T);
 9334
 9335    const polABC_S = PolF.sub(polAB_S, polC_S);
 9336
 9337    const H_S = polABC_S.slice(m);
 9338
 9339    return H_S;
 9340}
 9341
 9342}).call(this,require("buffer").Buffer)
 9343},{"buffer":8,"ffjavascript":12,"keccak":32}],44:[function(require,module,exports){
 9344/*
 9345    Copyright 2018 0kims association.
 9346
 9347    This file is part of snarkjs.
 9348
 9349    snarkjs is a free software: you can redistribute it and/or
 9350    modify it under the terms of the GNU General Public License as published by the
 9351    Free Software Foundation, either version 3 of the License, or (at your option)
 9352    any later version.
 9353
 9354    snarkjs is distributed in the hope that it will be useful,
 9355    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 9356    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 9357    more details.
 9358
 9359    You should have received a copy of the GNU General Public License along with
 9360    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 9361*/
 9362
 9363const bn128 = require("ffjavascript").bn128;
 9364const PolField = require("ffjavascript").PolField;
 9365const ZqField = require("ffjavascript").ZqField;
 9366
 9367const PolF = new PolField(new ZqField(bn128.r));
 9368const G1 = bn128.G1;
 9369const G2 = bn128.G2;
 9370
 9371module.exports = function genProof(vk_proof, witness) {
 9372
 9373    const proof = {};
 9374
 9375
 9376    const d1 = PolF.F.random();
 9377    const d2 = PolF.F.random();
 9378    const d3 = PolF.F.random();
 9379
 9380    proof.pi_a = G1.zero;
 9381    proof.pi_ap = G1.zero;
 9382    proof.pi_b = G2.zero;
 9383    proof.pi_bp = G1.zero;
 9384    proof.pi_c = G1.zero;
 9385    proof.pi_cp = G1.zero;
 9386    proof.pi_kp = G1.zero;
 9387    proof.pi_h = G1.zero;
 9388
 9389
 9390    // Skip public entries and the "1" signal that are forced by the verifier
 9391    for (let s= vk_proof.nPublic+1; s< vk_proof.nVars; s++) {
 9392
 9393        // pi_a  = pi_a  + A[s]  * witness[s];
 9394        proof.pi_a  = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[s], witness[s]));
 9395
 9396        // pi_ap = pi_ap + Ap[s] * witness[s];
 9397        proof.pi_ap = G1.add( proof.pi_ap, G1.mulScalar( vk_proof.Ap[s], witness[s]));
 9398    }
 9399
 9400    for (let s= 0; s< vk_proof.nVars; s++) {
 9401        // pi_a  = pi_a  + A[s]  * witness[s];
 9402        proof.pi_b  = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B[s], witness[s]));
 9403
 9404        // pi_ap = pi_ap + Ap[s] * witness[s];
 9405        proof.pi_bp = G1.add( proof.pi_bp, G1.mulScalar( vk_proof.Bp[s], witness[s]));
 9406
 9407        // pi_a  = pi_a  + A[s]  * witness[s];
 9408        proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[s], witness[s]));
 9409
 9410        // pi_ap = pi_ap + Ap[s] * witness[s];
 9411        proof.pi_cp = G1.add( proof.pi_cp, G1.mulScalar( vk_proof.Cp[s], witness[s]));
 9412
 9413        // pi_ap = pi_ap + Ap[s] * witness[s];
 9414        proof.pi_kp = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[s], witness[s]));
 9415    }
 9416
 9417    proof.pi_a  = G1.add( proof.pi_a, G1.mulScalar( vk_proof.A[vk_proof.nVars], d1));
 9418    proof.pi_ap  = G1.add( proof.pi_ap, G1.mulScalar( vk_proof.Ap[vk_proof.nVars], d1));
 9419
 9420    proof.pi_b  = G2.add( proof.pi_b, G2.mulScalar( vk_proof.B[vk_proof.nVars], d2));
 9421    proof.pi_bp  = G1.add( proof.pi_bp, G1.mulScalar( vk_proof.Bp[vk_proof.nVars], d2));
 9422
 9423    proof.pi_c  = G1.add( proof.pi_c, G1.mulScalar( vk_proof.C[vk_proof.nVars], d3));
 9424    proof.pi_cp  = G1.add( proof.pi_cp, G1.mulScalar( vk_proof.Cp[vk_proof.nVars], d3));
 9425
 9426    proof.pi_kp  = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars  ], d1));
 9427    proof.pi_kp  = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars+1], d2));
 9428    proof.pi_kp  = G1.add( proof.pi_kp, G1.mulScalar( vk_proof.Kp[vk_proof.nVars+2], d3));
 9429
 9430/*
 9431    let polA = [];
 9432    let polB = [];
 9433    let polC = [];
 9434
 9435    for (let s= 0; s< vk_proof.nVars; s++) {
 9436        polA = PolF.add(
 9437            polA,
 9438            PolF.mul(
 9439                vk_proof.polsA[s],
 9440                [witness[s]] ));
 9441
 9442        polB = PolF.add(
 9443            polB,
 9444            PolF.mul(
 9445                vk_proof.polsB[s],
 9446                [witness[s]] ));
 9447
 9448        polC = PolF.add(
 9449            polC,
 9450            PolF.mul(
 9451                vk_proof.polsC[s],
 9452                [witness[s]] ));
 9453    }
 9454
 9455
 9456    let polFull = PolF.sub(PolF.mul( polA, polB), polC);
 9457
 9458    const h = PolF.div(polFull, vk_proof.polZ );
 9459*/
 9460
 9461    const h = calculateH(vk_proof, witness, d1, d2, d3);
 9462
 9463//    console.log(h.length + "/" + vk_proof.hExps.length);
 9464
 9465    for (let i = 0; i < h.length; i++) {
 9466        proof.pi_h = G1.add( proof.pi_h, G1.mulScalar( vk_proof.hExps[i], h[i]));
 9467    }
 9468
 9469    proof.pi_a = G1.affine(proof.pi_a);
 9470    proof.pi_b = G2.affine(proof.pi_b);
 9471    proof.pi_c = G1.affine(proof.pi_c);
 9472    proof.pi_ap = G1.affine(proof.pi_ap);
 9473    proof.pi_bp = G1.affine(proof.pi_bp);
 9474    proof.pi_cp = G1.affine(proof.pi_cp);
 9475    proof.pi_kp = G1.affine(proof.pi_kp);
 9476    proof.pi_h = G1.affine(proof.pi_h);
 9477
 9478//    proof.h=h;
 9479
 9480    proof.protocol = "original";
 9481
 9482    const publicSignals = witness.slice(1, vk_proof.nPublic+1);
 9483
 9484    return {proof, publicSignals};
 9485};
 9486
 9487
 9488function calculateH(vk_proof, witness, d1, d2, d3) {
 9489
 9490    const F = PolF.F;
 9491    const m = vk_proof.domainSize;
 9492    const polA_T = new Array(m).fill(PolF.F.zero);
 9493    const polB_T = new Array(m).fill(PolF.F.zero);
 9494    const polC_T = new Array(m).fill(PolF.F.zero);
 9495
 9496    for (let s=0; s<vk_proof.nVars; s++) {
 9497        for (let c in vk_proof.polsA[s]) {
 9498            polA_T[c] = F.add(polA_T[c], F.mul(witness[s], vk_proof.polsA[s][c]));
 9499        }
 9500        for (let c in vk_proof.polsB[s]) {
 9501            polB_T[c] = F.add(polB_T[c], F.mul(witness[s], vk_proof.polsB[s][c]));
 9502        }
 9503        for (let c in vk_proof.polsC[s]) {
 9504            polC_T[c] = F.add(polC_T[c], F.mul(witness[s], vk_proof.polsC[s][c]));
 9505        }
 9506    }
 9507
 9508    const polA_S = PolF.ifft(polA_T);
 9509    const polB_S = PolF.ifft(polB_T);
 9510
 9511    const polAB_S = PolF.mul(polA_S, polB_S);
 9512
 9513    const polC_S = PolF.ifft(polC_T);
 9514
 9515    const polABC_S = PolF.sub(polAB_S, polC_S);
 9516
 9517    const polZ_S = new Array(m+1).fill(F.zero);
 9518    polZ_S[m] = F.one;
 9519    polZ_S[0] = F.neg(F.one);
 9520
 9521    let H_S = PolF.div(polABC_S, polZ_S);
 9522/*
 9523    const H2S = PolF.mul(H_S, polZ_S);
 9524
 9525    if (PolF.equals(H2S, polABC_S)) {
 9526        console.log("Is Divisible!");
 9527    } else {
 9528        console.log("ERROR: Not divisible!");
 9529    }
 9530*/
 9531
 9532    /* add coefficients of the polynomial (d2*A + d1*B - d3) + d1*d2*Z */
 9533
 9534    H_S = PolF.extend(H_S, m+1);
 9535
 9536    for (let i=0; i<m; i++) {
 9537        const d2A = PolF.F.mul(d2, polA_S[i]);
 9538        const d1B = PolF.F.mul(d1, polB_S[i]);
 9539        H_S[i] = PolF.F.add(H_S[i], PolF.F.add(d2A, d1B));
 9540    }
 9541
 9542    H_S[0] = PolF.F.sub(H_S[0], d3);
 9543
 9544    // Z = x^m -1
 9545    const d1d2 = PolF.F.mul(d1, d2);
 9546    H_S[m] = PolF.F.add(H_S[m], d1d2);
 9547    H_S[0] = PolF.F.sub(H_S[0], d1d2);
 9548
 9549    H_S = PolF.reduce(H_S);
 9550
 9551    return H_S;
 9552}
 9553
 9554},{"ffjavascript":12}],45:[function(require,module,exports){
 9555/*
 9556    Copyright 2018 0kims association.
 9557
 9558    This file is part of snarkjs.
 9559
 9560    snarkjs is a free software: you can redistribute it and/or
 9561    modify it under the terms of the GNU General Public License as published by the
 9562    Free Software Foundation, either version 3 of the License, or (at your option)
 9563    any later version.
 9564
 9565    snarkjs is distributed in the hope that it will be useful,
 9566    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 9567    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 9568    more details.
 9569
 9570    You should have received a copy of the GNU General Public License along with
 9571    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 9572*/
 9573
 9574/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
 9575
 9576const bigInt = require("big-integer");
 9577
 9578const bn128 = require("ffjavascript").bn128;
 9579const PolField = require("ffjavascript").PolField;
 9580const ZqField = require("ffjavascript").ZqField;
 9581
 9582const G1 = bn128.G1;
 9583const G2 = bn128.G2;
 9584const PolF = new PolField(new ZqField(bn128.r));
 9585const F = new ZqField(bn128.r);
 9586
 9587module.exports = function setup(circuit, verbose) {
 9588    const setup = {
 9589        vk_proof : {
 9590            protocol: "groth",
 9591            nVars: circuit.nVars,
 9592            nPublic: circuit.nPubInputs + circuit.nOutputs
 9593        },
 9594        vk_verifier: {
 9595            protocol: "groth",
 9596            nPublic: circuit.nPubInputs + circuit.nOutputs
 9597        },
 9598        toxic: {}
 9599    };
 9600
 9601
 9602    setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
 9603    setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
 9604
 9605    calculatePolinomials(setup, circuit);
 9606    setup.toxic.t = F.random();
 9607    calculateEncriptedValuesAtT(setup, circuit, verbose);
 9608
 9609    return setup;
 9610};
 9611
 9612
 9613function calculatePolinomials(setup, circuit) {
 9614
 9615    setup.vk_proof.polsA = new Array(circuit.nVars);
 9616    setup.vk_proof.polsB = new Array(circuit.nVars);
 9617    setup.vk_proof.polsC = new Array(circuit.nVars);
 9618    for (let i=0; i<circuit.nVars; i++) {
 9619        setup.vk_proof.polsA[i] = {};
 9620        setup.vk_proof.polsB[i] = {};
 9621        setup.vk_proof.polsC[i] = {};
 9622    }
 9623    for (let c=0; c<circuit.nConstraints; c++) {
 9624
 9625        for (let s in circuit.constraints[c][0]) {
 9626            setup.vk_proof.polsA[s][c] = circuit.constraints[c][0][s];
 9627        }
 9628        for (let s in circuit.constraints[c][1]) {
 9629            setup.vk_proof.polsB[s][c] = circuit.constraints[c][1][s];
 9630        }
 9631        for (let s in circuit.constraints[c][2]) {
 9632            setup.vk_proof.polsC[s][c] = circuit.constraints[c][2][s];
 9633        }
 9634    }
 9635
 9636    /**
 9637     * add and process the constraints
 9638     *     input_i * 0 = 0
 9639     * to ensure soundness of input consistency
 9640     */
 9641    for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
 9642    {
 9643        setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
 9644    }
 9645}
 9646
 9647function calculateValuesAtT(setup, circuit) {
 9648    const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
 9649    const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
 9650
 9651    const a_t = new Array(circuit.nVars).fill(F.zero);
 9652    const b_t = new Array(circuit.nVars).fill(F.zero);
 9653    const c_t = new Array(circuit.nVars).fill(F.zero);
 9654
 9655    // TODO: substitute setup.polsA for coeficients
 9656    for (let s=0; s<circuit.nVars; s++) {
 9657        for (let c in setup.vk_proof.polsA[s]) {
 9658            a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
 9659        }
 9660        for (let c in setup.vk_proof.polsB[s]) {
 9661            b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
 9662        }
 9663        for (let c in setup.vk_proof.polsC[s]) {
 9664            c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
 9665        }
 9666    }
 9667
 9668    return {a_t, b_t, c_t, z_t};
 9669
 9670}
 9671
 9672
 9673
 9674
 9675function calculateEncriptedValuesAtT(setup, circuit, verbose) {
 9676
 9677    const v = calculateValuesAtT(setup, circuit);
 9678    setup.vk_proof.A = new Array(circuit.nVars);
 9679    setup.vk_proof.B1 = new Array(circuit.nVars);
 9680    setup.vk_proof.B2 = new Array(circuit.nVars);
 9681    setup.vk_proof.C = new Array(circuit.nVars);
 9682    setup.vk_verifier.IC = new Array(circuit.nPubInputs + circuit.nOutputs + 1);
 9683
 9684    setup.toxic.kalfa = F.random();
 9685    setup.toxic.kbeta = F.random();
 9686    setup.toxic.kgamma = F.random();
 9687    setup.toxic.kdelta = F.random();
 9688
 9689    let invDelta = F.inv(setup.toxic.kdelta);
 9690    let invGamma = F.inv(setup.toxic.kgamma);
 9691
 9692    setup.vk_proof.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
 9693    setup.vk_proof.vk_beta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kbeta));
 9694    setup.vk_proof.vk_delta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kdelta));
 9695
 9696    setup.vk_proof.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
 9697    setup.vk_proof.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
 9698
 9699
 9700    setup.vk_verifier.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
 9701
 9702    setup.vk_verifier.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
 9703    setup.vk_verifier.vk_gamma_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
 9704    setup.vk_verifier.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
 9705
 9706    setup.vk_verifier.vk_alfabeta_12 = bn128.pairing( setup.vk_verifier.vk_alfa_1 , setup.vk_verifier.vk_beta_2 );
 9707
 9708    for (let s=0; s<circuit.nVars; s++) {
 9709
 9710        const A = G1.mulScalar(G1.g, v.a_t[s]);
 9711
 9712        setup.vk_proof.A[s] = A;
 9713
 9714        const B1 = G1.mulScalar(G1.g, v.b_t[s]);
 9715
 9716        setup.vk_proof.B1[s] = B1;
 9717
 9718        const B2 = G2.mulScalar(G2.g, v.b_t[s]);
 9719
 9720        setup.vk_proof.B2[s] = B2;
 9721
 9722        if ((verbose)&&(s%1000 == 1)) console.log("A, B1, B2: ", s);
 9723    }
 9724
 9725
 9726    for (let s=0; s<=setup.vk_proof.nPublic; s++) {
 9727        let ps =
 9728            F.mul(
 9729                invGamma,
 9730                F.add(
 9731                    F.add(
 9732                        F.mul(v.a_t[s], setup.toxic.kbeta),
 9733                        F.mul(v.b_t[s], setup.toxic.kalfa)),
 9734                    v.c_t[s]));
 9735
 9736        const IC = G1.mulScalar(G1.g, ps);
 9737        setup.vk_verifier.IC[s]=IC;
 9738    }
 9739
 9740    for (let s=setup.vk_proof.nPublic+1; s<circuit.nVars; s++) {
 9741        let ps =
 9742            F.mul(
 9743                invDelta,
 9744                F.add(
 9745                    F.add(
 9746                        F.mul(v.a_t[s], setup.toxic.kbeta),
 9747                        F.mul(v.b_t[s], setup.toxic.kalfa)),
 9748                    v.c_t[s]));
 9749        const C = G1.mulScalar(G1.g, ps);
 9750        setup.vk_proof.C[s]=C;
 9751
 9752        if ((verbose)&&(s%1000 == 1)) console.log("C: ", s);
 9753
 9754    }
 9755
 9756    // Calculate HExps
 9757
 9758    const maxH = setup.vk_proof.domainSize+1;
 9759
 9760    setup.vk_proof.hExps = new Array(maxH);
 9761
 9762    const zod = F.mul(invDelta, v.z_t);
 9763
 9764    setup.vk_proof.hExps[0] = G1.affine(G1.mulScalar(G1.g, zod));
 9765    let eT = setup.toxic.t;
 9766    for (let i=1; i<maxH; i++) {
 9767        setup.vk_proof.hExps[i] = G1.mulScalar(G1.g, F.mul(eT, zod));
 9768        eT = F.mul(eT, setup.toxic.t);
 9769
 9770        if ((verbose)&&(i%1000 == 1)) console.log("Tau: ", i);
 9771
 9772    }
 9773
 9774    G1.multiAffine(setup.vk_proof.A);
 9775    G1.multiAffine(setup.vk_proof.B1);
 9776    G2.multiAffine(setup.vk_proof.B2);
 9777    G1.multiAffine(setup.vk_proof.C);
 9778    G1.multiAffine(setup.vk_proof.hExps);
 9779
 9780    G1.multiAffine(setup.vk_verifier.IC);
 9781
 9782}
 9783
 9784
 9785},{"big-integer":6,"ffjavascript":12}],46:[function(require,module,exports){
 9786/*
 9787    Copyright 2018 0kims association.
 9788
 9789    This file is part of snarkjs.
 9790
 9791    snarkjs is a free software: you can redistribute it and/or
 9792    modify it under the terms of the GNU General Public License as published by the
 9793    Free Software Foundation, either version 3 of the License, or (at your option)
 9794    any later version.
 9795
 9796    snarkjs is distributed in the hope that it will be useful,
 9797    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
 9798    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 9799    more details.
 9800
 9801    You should have received a copy of the GNU General Public License along with
 9802    snarkjs. If not, see <https://www.gnu.org/licenses/>.
 9803*/
 9804
 9805/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
 9806
 9807const bigInt = require("big-integer");
 9808
 9809const bn128 = require("ffjavascript").bn128;
 9810const PolField = require("ffjavascript").PolField;
 9811const ZqField = require("ffjavascript").ZqField;
 9812
 9813const G1 = bn128.G1;
 9814const G2 = bn128.G2;
 9815const PolF = new PolField(new ZqField(bn128.r));
 9816const F = new ZqField(bn128.r);
 9817
 9818module.exports = function setup(circuit) {
 9819    const setup = {
 9820        vk_proof : {
 9821            protocol: "kimleeoh",
 9822            nVars: circuit.nVars,
 9823            nPublic: circuit.nPubInputs + circuit.nOutputs
 9824        },
 9825        vk_verifier: {
 9826            protocol: "kimleeoh",
 9827            nPublic: circuit.nPubInputs + circuit.nOutputs
 9828        },
 9829        toxic: {}
 9830    };
 9831
 9832
 9833    setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
 9834    setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
 9835
 9836    calculatePolinomials(setup, circuit);
 9837    setup.toxic.t = F.random();
 9838    calculateEncriptedValuesAtT(setup, circuit);
 9839
 9840    return setup;
 9841};
 9842
 9843
 9844function calculatePolinomials(setup, circuit) {
 9845
 9846    setup.vk_proof.polsA = new Array(circuit.nVars);
 9847    setup.vk_proof.polsB = new Array(circuit.nVars);
 9848    setup.vk_proof.polsC = new Array(circuit.nVars);
 9849    for (let i=0; i<circuit.nVars; i++) {
 9850        setup.vk_proof.polsA[i] = {};
 9851        setup.vk_proof.polsB[i] = {};
 9852        setup.vk_proof.polsC[i] = {};
 9853    }
 9854    for (let c=0; c<circuit.nConstraints; c++) {
 9855
 9856        for (let s in circuit.constraints[c][0]) {
 9857            setup.vk_proof.polsA[s][c] = circuit.constraints[c][0][s];
 9858        }
 9859        for (let s in circuit.constraints[c][1]) {
 9860            setup.vk_proof.polsB[s][c] = circuit.constraints[c][1][s];
 9861        }
 9862        for (let s in circuit.constraints[c][2]) {
 9863            setup.vk_proof.polsC[s][c] = circuit.constraints[c][2][s];
 9864        }
 9865    }
 9866
 9867    /**
 9868     * add and process the constraints
 9869     *     input_i * 0 = 0
 9870     * to ensure soundness of input consistency
 9871     */
 9872    for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
 9873    {
 9874        setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
 9875    }
 9876}
 9877
 9878function calculateValuesAtT(setup, circuit) {
 9879    const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
 9880    const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
 9881
 9882    const a_t = new Array(circuit.nVars).fill(F.zero);
 9883    const b_t = new Array(circuit.nVars).fill(F.zero);
 9884    const c_t = new Array(circuit.nVars).fill(F.zero);
 9885
 9886    // TODO: substitute setup.polsA for coeficients
 9887    for (let s=0; s<circuit.nVars; s++) {
 9888        for (let c in setup.vk_proof.polsA[s]) {
 9889            a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
 9890        }
 9891        for (let c in setup.vk_proof.polsB[s]) {
 9892            b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
 9893        }
 9894        for (let c in setup.vk_proof.polsC[s]) {
 9895            c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
 9896        }
 9897    }
 9898
 9899    return {a_t, b_t, c_t, z_t};
 9900
 9901}
 9902
 9903
 9904
 9905
 9906function calculateEncriptedValuesAtT(setup, circuit) {
 9907
 9908    const v = calculateValuesAtT(setup, circuit);
 9909    setup.vk_proof.A = new Array(circuit.nVars);
 9910    setup.vk_proof.Adelta = new Array(circuit.nVars);
 9911    setup.vk_proof.B1 = new Array(circuit.nVars);
 9912    setup.vk_proof.B2 = new Array(circuit.nVars);
 9913    setup.vk_proof.C = new Array(circuit.nVars);
 9914    setup.vk_verifier.IC = new Array(circuit.nPubInputs + circuit.nOutputs + 1);
 9915
 9916    setup.toxic.kalfa = F.random();
 9917    setup.toxic.kbeta = F.random();
 9918    setup.toxic.kgamma = F.random();
 9919    setup.toxic.kdelta = F.random();
 9920
 9921    const gammaSquare = F.mul(setup.toxic.kgamma, setup.toxic.kgamma);
 9922
 9923    setup.vk_proof.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
 9924    setup.vk_proof.vk_beta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kbeta));
 9925    setup.vk_proof.vk_delta_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kdelta));
 9926    setup.vk_proof.vk_alfadelta_1 = G1.affine(G1.mulScalar( G1.g, F.mul(setup.toxic.kalfa, setup.toxic.kdelta)));
 9927
 9928    setup.vk_proof.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
 9929
 9930
 9931    setup.vk_verifier.vk_alfa_1 = G1.affine(G1.mulScalar( G1.g, setup.toxic.kalfa));
 9932
 9933    setup.vk_verifier.vk_beta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kbeta));
 9934    setup.vk_verifier.vk_gamma_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
 9935    setup.vk_verifier.vk_delta_2 = G2.affine(G2.mulScalar( G2.g, setup.toxic.kdelta));
 9936
 9937    setup.vk_verifier.vk_alfabeta_12 = bn128.pairing( setup.vk_verifier.vk_alfa_1 , setup.vk_verifier.vk_beta_2 );
 9938
 9939    for (let s=0; s<circuit.nVars; s++) {
 9940
 9941        const A = G1.affine(G1.mulScalar(G1.g, F.mul(setup.toxic.kgamma, v.a_t[s])));
 9942
 9943        setup.vk_proof.A[s] = A;
 9944        setup.vk_proof.Adelta[s] = G1.affine(G1.mulScalar(A, setup.toxic.kdelta));
 9945
 9946        const B1 = G1.affine(G1.mulScalar(G1.g, F.mul(setup.toxic.kgamma, v.b_t[s])));
 9947
 9948        setup.vk_proof.B1[s] = B1;
 9949
 9950        const B2 = G2.affine(G2.mulScalar(G2.g, F.mul(setup.toxic.kgamma, v.b_t[s])));
 9951
 9952        setup.vk_proof.B2[s] = B2;
 9953    }
 9954
 9955    for (let s=0; s<=setup.vk_proof.nPublic; s++) {
 9956
 9957        let ps =
 9958            F.add(
 9959                F.mul(
 9960                    setup.toxic.kgamma,
 9961                    v.c_t[s]
 9962                ),
 9963                F.add(
 9964                    F.mul(
 9965                        setup.toxic.kbeta,
 9966                        v.a_t[s]
 9967                    ),
 9968                    F.mul(
 9969                        setup.toxic.kalfa,
 9970                        v.b_t[s]
 9971                    )
 9972                )
 9973            );
 9974
 9975        const IC = G1.affine(G1.mulScalar(G1.g, ps));
 9976        setup.vk_verifier.IC[s]=IC;
 9977    }
 9978
 9979    for (let s=setup.vk_proof.nPublic+1; s<circuit.nVars; s++) {
 9980        let ps =
 9981            F.add(
 9982                F.mul(
 9983                    gammaSquare,
 9984                    v.c_t[s]
 9985                ),
 9986                F.add(
 9987                    F.mul(
 9988                        F.mul(setup.toxic.kbeta, setup.toxic.kgamma),
 9989                        v.a_t[s]
 9990                    ),
 9991                    F.mul(
 9992                        F.mul(setup.toxic.kalfa, setup.toxic.kgamma),
 9993                        v.b_t[s]
 9994                    )
 9995                )
 9996            );
 9997
 9998        const C = G1.affine(G1.mulScalar(G1.g, ps));
 9999        setup.vk_proof.C[s]=C;
10000    }
10001
10002    // Calculate HExps
10003
10004    const maxH = setup.vk_proof.domainSize+1;
10005
10006    setup.vk_proof.hExps = new Array(maxH);
10007
10008    const zod = F.mul(gammaSquare, v.z_t);
10009
10010    setup.vk_proof.hExps[0] = G1.affine(G1.mulScalar(G1.g, zod));
10011    let eT = setup.toxic.t;
10012    for (let i=1; i<maxH; i++) {
10013        setup.vk_proof.hExps[i] = G1.affine(G1.mulScalar(G1.g, F.mul(eT, zod)));
10014        eT = F.mul(eT, setup.toxic.t);
10015    }
10016}
10017
10018
10019},{"big-integer":6,"ffjavascript":12}],47:[function(require,module,exports){
10020/*
10021    Copyright 2018 0kims association.
10022
10023    This file is part of snarkjs.
10024
10025    snarkjs is a free software: you can redistribute it and/or
10026    modify it under the terms of the GNU General Public License as published by the
10027    Free Software Foundation, either version 3 of the License, or (at your option)
10028    any later version.
10029
10030    snarkjs is distributed in the hope that it will be useful,
10031    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10032    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
10033    more details.
10034
10035    You should have received a copy of the GNU General Public License along with
10036    snarkjs. If not, see <https://www.gnu.org/licenses/>.
10037*/
10038
10039const bigInt = require("big-integer");
10040
10041const bn128 = require("ffjavascript").bn128;
10042const PolField = require("ffjavascript").PolField;
10043const ZqField = require("ffjavascript").ZqField;
10044
10045const G1 = bn128.G1;
10046const G2 = bn128.G2;
10047const PolF = new PolField(new ZqField(bn128.r));
10048const F = new ZqField(bn128.r);
10049
10050module.exports = function setup(circuit) {
10051    const setup = {
10052        vk_proof : {
10053            protocol: "original",
10054            nVars: circuit.nVars,
10055            nPublic: circuit.nPubInputs + circuit.nOutputs
10056        },
10057        vk_verifier: {
10058            protocol: "original",
10059            nPublic: circuit.nPubInputs + circuit.nOutputs
10060        },
10061        toxic: {}
10062    };
10063
10064
10065    setup.vk_proof.domainBits = PolF.log2(circuit.nConstraints + circuit.nPubInputs + circuit.nOutputs +1 -1) +1;
10066    setup.vk_proof.domainSize = 1 << setup.vk_proof.domainBits;
10067
10068    calculatePolinomials(setup, circuit);
10069    setup.toxic.t = F.random();
10070    calculateEncriptedValuesAtT(setup, circuit);
10071    calculateHexps(setup, circuit);
10072
10073    return setup;
10074};
10075
10076
10077function calculatePolinomials(setup, circuit) {
10078
10079    setup.vk_proof.polsA = new Array(circuit.nVars);
10080    setup.vk_proof.polsB = new Array(circuit.nVars);
10081    setup.vk_proof.polsC = new Array(circuit.nVars);
10082    for (let i=0; i<circuit.nVars; i++) {
10083        setup.vk_proof.polsA[i] = {};
10084        setup.vk_proof.polsB[i] = {};
10085        setup.vk_proof.polsC[i] = {};
10086    }
10087    for (let c=0; c<circuit.nConstraints; c++) {
10088
10089        for (let s in circuit.constraints[c][0]) {
10090            setup.vk_proof.polsA[s][c] = circuit.constraints[c][0][s];
10091        }
10092        for (let s in circuit.constraints[c][1]) {
10093            setup.vk_proof.polsB[s][c] = circuit.constraints[c][1][s];
10094        }
10095        for (let s in circuit.constraints[c][2]) {
10096            setup.vk_proof.polsC[s][c] = circuit.constraints[c][2][s];
10097        }
10098    }
10099
10100    /**
10101     * add and process the constraints
10102     *     input_i * 0 = 0
10103     * to ensure soundness of input consistency
10104     */
10105    for (let i = 0; i < circuit.nPubInputs + circuit.nOutputs + 1; ++i)
10106    {
10107        setup.vk_proof.polsA[i][circuit.nConstraints + i] = F.one;
10108    }
10109}
10110
10111function calculateValuesAtT(setup, circuit) {
10112    const z_t = PolF.computeVanishingPolinomial(setup.vk_proof.domainBits, setup.toxic.t);
10113    const u = PolF.evaluateLagrangePolynomials(setup.vk_proof.domainBits, setup.toxic.t);
10114
10115    const a_t = new Array(circuit.nVars).fill(F.zero);
10116    const b_t = new Array(circuit.nVars).fill(F.zero);
10117    const c_t = new Array(circuit.nVars).fill(F.zero);
10118
10119    // TODO: substitute setup.polsA for coeficients
10120    for (let s=0; s<circuit.nVars; s++) {
10121        for (let c in setup.vk_proof.polsA[s]) {
10122            a_t[s] = F.add(a_t[s], F.mul(u[c], setup.vk_proof.polsA[s][c]));
10123        }
10124        for (let c in setup.vk_proof.polsB[s]) {
10125            b_t[s] = F.add(b_t[s], F.mul(u[c], setup.vk_proof.polsB[s][c]));
10126        }
10127        for (let c in setup.vk_proof.polsC[s]) {
10128            c_t[s] = F.add(c_t[s], F.mul(u[c], setup.vk_proof.polsC[s][c]));
10129        }
10130    }
10131
10132    return {a_t, b_t, c_t, z_t};
10133
10134}
10135
10136
10137
10138
10139function calculateEncriptedValuesAtT(setup, circuit) {
10140
10141    const v = calculateValuesAtT(setup, circuit);
10142    setup.vk_proof.A = new Array(circuit.nVars+1);
10143    setup.vk_proof.B = new Array(circuit.nVars+1);
10144    setup.vk_proof.C = new Array(circuit.nVars+1);
10145    setup.vk_proof.Ap = new Array(circuit.nVars+1);
10146    setup.vk_proof.Bp = new Array(circuit.nVars+1);
10147    setup.vk_proof.Cp = new Array(circuit.nVars+1);
10148    setup.vk_proof.Kp = new Array(circuit.nVars+3);
10149    setup.vk_verifier.IC = new Array(circuit.nPubInputs);
10150    setup.vk_verifier.IC = new Array(circuit.nPubInputs + circuit.nOutputs + 1);
10151
10152    setup.toxic.ka = F.random();
10153    setup.toxic.kb = F.random();
10154    setup.toxic.kc = F.random();
10155    setup.toxic.ra = F.random();
10156    setup.toxic.rb = F.random();
10157    setup.toxic.rc = F.mul(setup.toxic.ra, setup.toxic.rb);
10158    setup.toxic.kbeta = F.random();
10159    setup.toxic.kgamma = F.random();
10160
10161    const gb = F.mul(setup.toxic.kbeta, setup.toxic.kgamma);
10162
10163    setup.vk_verifier.vk_a = G2.affine(G2.mulScalar( G2.g, setup.toxic.ka));
10164    setup.vk_verifier.vk_b = G1.affine(G1.mulScalar( G1.g, setup.toxic.kb));
10165    setup.vk_verifier.vk_c = G2.affine(G2.mulScalar( G2.g, setup.toxic.kc));
10166    setup.vk_verifier.vk_gb_1 = G1.affine(G1.mulScalar( G1.g, gb));
10167    setup.vk_verifier.vk_gb_2 = G2.affine(G2.mulScalar( G2.g, gb));
10168    setup.vk_verifier.vk_g = G2.affine(G2.mulScalar( G2.g, setup.toxic.kgamma));
10169
10170    for (let s=0; s<circuit.nVars; s++) {
10171
10172        // A[i] = G1 * polA(t)
10173        const raat = F.mul(setup.toxic.ra, v.a_t[s]);
10174        const A = G1.affine(G1.mulScalar(G1.g, raat));
10175
10176        setup.vk_proof.A[s] = A;
10177
10178        if (s <= setup.vk_proof.nPublic) {
10179            setup.vk_verifier.IC[s]=A;
10180        }
10181
10182
10183        // B1[i] = G1 * polB(t)
10184        const rbbt = F.mul(setup.toxic.rb, v.b_t[s]);
10185        const B1 = G1.affine(G1.mulScalar(G1.g, rbbt));
10186
10187        // B2[i] = G2 * polB(t)
10188        const B2 = G2.affine(G2.mulScalar(G2.g, rbbt));
10189
10190        setup.vk_proof.B[s]=B2;
10191
10192        // C[i] = G1 * polC(t)
10193        const rcct = F.mul(setup.toxic.rc, v.c_t[s]);
10194        const C = G1.affine(G1.mulScalar( G1.g, rcct));
10195        setup.vk_proof.C[s] =C;
10196
10197        // K = G1 * (A+B+C)
10198
10199        const kt = F.add(F.add(raat, rbbt), rcct);
10200        const K = G1.affine(G1.mulScalar( G1.g, kt));
10201
10202        /*
10203        // Comment this lines to improve the process
10204                const Ktest = G1.affine(G1.add(G1.add(A, B1), C));
10205
10206                if (!G1.equals(K, Ktest)) {
10207                    console.log ("=====FAIL======");
10208                }
10209        */
10210
10211        if (s > setup.vk_proof.nPublic) {
10212            setup.vk_proof.Ap[s] = G1.affine(G1.mulScalar(A, setup.toxic.ka));
10213        }
10214        setup.vk_proof.Bp[s] = G1.affine(G1.mulScalar(B1, setup.toxic.kb));
10215        setup.vk_proof.Cp[s] = G1.affine(G1.mulScalar(C, setup.toxic.kc));
10216        setup.vk_proof.Kp[s] = G1.affine(G1.mulScalar(K, setup.toxic.kbeta));
10217    }
10218
10219    // Extra coeficients
10220    const A = G1.mulScalar( G1.g, F.mul(setup.toxic.ra, v.z_t));
10221    setup.vk_proof.A[circuit.nVars] = G1.affine(A);
10222    setup.vk_proof.Ap[circuit.nVars] = G1.affine(G1.mulScalar(A, setup.toxic.ka));
10223
10224    const B1 = G1.mulScalar( G1.g, F.mul(setup.toxic.rb, v.z_t));
10225    const B2 = G2.mulScalar( G2.g, F.mul(setup.toxic.rb, v.z_t));
10226    setup.vk_proof.B[circuit.nVars] = G2.affine(B2);
10227    setup.vk_proof.Bp[circuit.nVars] = G1.affine(G1.mulScalar(B1, setup.toxic.kb));
10228
10229    const C = G1.mulScalar( G1.g, F.mul(setup.toxic.rc, v.z_t));
10230    setup.vk_proof.C[circuit.nVars] = G1.affine(C);
10231    setup.vk_proof.Cp[circuit.nVars] = G1.affine(G1.mulScalar(C, setup.toxic.kc));
10232
10233    setup.vk_proof.Kp[circuit.nVars  ] = G1.affine(G1.mulScalar(A, setup.toxic.kbeta));
10234    setup.vk_proof.Kp[circuit.nVars+1] = G1.affine(G1.mulScalar(B1, setup.toxic.kbeta));
10235    setup.vk_proof.Kp[circuit.nVars+2] = G1.affine(G1.mulScalar(C, setup.toxic.kbeta));
10236
10237//    setup.vk_verifier.A[0] = G1.affine(G1.add(setup.vk_verifier.A[0], setup.vk_proof.A[circuit.nVars]));
10238
10239    // vk_z
10240    setup.vk_verifier.vk_z = G2.affine(G2.mulScalar(
10241        G2.g,
10242        F.mul(setup.toxic.rc, v.z_t)));
10243}
10244
10245function calculateHexps(setup) {
10246
10247    const maxH = setup.vk_proof.domainSize+1;
10248
10249    setup.vk_proof.hExps = new Array(maxH);
10250    setup.vk_proof.hExps[0] = G1.g;
10251    let eT = setup.toxic.t;
10252    for (let i=1; i<maxH; i++) {
10253        setup.vk_proof.hExps[i] = G1.affine(G1.mulScalar(G1.g, eT));
10254        eT = F.mul(eT, setup.toxic.t);
10255    }
10256}
10257
10258
10259},{"big-integer":6,"ffjavascript":12}],48:[function(require,module,exports){
10260/*
10261    Copyright 2018 0kims association.
10262
10263    This file is part of snarkjs.
10264
10265    snarkjs is a free software: you can redistribute it and/or
10266    modify it under the terms of the GNU General Public License as published by the
10267    Free Software Foundation, either version 3 of the License, or (at your option)
10268    any later version.
10269
10270    snarkjs is distributed in the hope that it will be useful,
10271    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10272    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
10273    more details.
10274
10275    You should have received a copy of the GNU General Public License along with
10276    snarkjs. If not, see <https://www.gnu.org/licenses/>.
10277*/
10278
10279/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
10280
10281
10282const bn128 = require("ffjavascript").bn128;
10283
10284const G1 = bn128.G1;
10285
10286module.exports = function isValid(vk_verifier, proof, publicSignals) {
10287
10288    let cpub = vk_verifier.IC[0];
10289    for (let s= 0; s< vk_verifier.nPublic; s++) {
10290        cpub  = G1.add( cpub, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
10291    }
10292
10293    if (! bn128.F12.eq(
10294        bn128.pairing( proof.pi_a , proof.pi_b ),
10295        bn128.F12.mul(
10296            vk_verifier.vk_alfabeta_12,
10297            bn128.F12.mul(
10298                bn128.pairing( cpub , vk_verifier.vk_gamma_2 ),
10299                bn128.pairing( proof.pi_c , vk_verifier.vk_delta_2 )
10300            ))))
10301        return false;
10302
10303    return true;
10304};
10305
10306},{"ffjavascript":12}],49:[function(require,module,exports){
10307(function (Buffer){
10308/*
10309    Copyright 2018 0kims association.
10310
10311    This file is part of snarkjs.
10312
10313    snarkjs is a free software: you can redistribute it and/or
10314    modify it under the terms of the GNU General Public License as published by the
10315    Free Software Foundation, either version 3 of the License, or (at your option)
10316    any later version.
10317
10318    snarkjs is distributed in the hope that it will be useful,
10319    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10320    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
10321    more details.
10322
10323    You should have received a copy of the GNU General Public License along with
10324    snarkjs. If not, see <https://www.gnu.org/licenses/>.
10325*/
10326
10327/* Implementation of this paper: https://eprint.iacr.org/2016/260.pdf */
10328
10329
10330const bn128 = require("ffjavascript").bn128;
10331const createKeccakHash = require("keccak");
10332const utils = require("ffjavascript").utils;
10333
10334const G1 = bn128.G1;
10335const G2 = bn128.G2;
10336
10337module.exports = function isValid(vk_verifier, proof, publicSignals) {
10338
10339    let cpub = vk_verifier.IC[0];
10340    for (let s= 0; s< vk_verifier.nPublic; s++) {
10341        cpub  = G1.add( cpub, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
10342    }
10343
10344    const buff = Buffer.concat([
10345        utils.beInt2Buff(proof.pi_a[0], 32),
10346        utils.beInt2Buff(proof.pi_a[1], 32),
10347        utils.beInt2Buff(proof.pi_b[0][0], 32),
10348        utils.beInt2Buff(proof.pi_b[0][1], 32),
10349        utils.beInt2Buff(proof.pi_b[1][0], 32),
10350        utils.beInt2Buff(proof.pi_b[1][1], 32),
10351    ]);
10352
10353    const h1buff = createKeccakHash("keccak256").update(buff).digest();
10354    const h2buff = createKeccakHash("keccak256").update(h1buff).digest();
10355
10356    const h1 = utils.beBuff2int(h1buff);
10357    const h2 = utils.beBuff2int(h2buff);
10358
10359
10360    // const h1 = bn128.Fr.zero;
10361    // const h2 = bn128.Fr.zero;
10362
10363    // console.log(h1.toString());
10364    // console.log(h2.toString());
10365
10366
10367    if (! bn128.F12.eq(
10368        bn128.pairing(
10369            G1.add(proof.pi_a, G1.mulScalar(G1.g, h1)),
10370            G2.add(proof.pi_b, G2.mulScalar(vk_verifier.vk_delta_2, h2))
10371        ),
10372        bn128.F12.mul(
10373            vk_verifier.vk_alfabeta_12,
10374            bn128.F12.mul(
10375                bn128.pairing( cpub , vk_verifier.vk_gamma_2 ),
10376                bn128.pairing( proof.pi_c , G2.g )
10377            ))))
10378        return false;
10379
10380    return true;
10381};
10382
10383}).call(this,require("buffer").Buffer)
10384},{"buffer":8,"ffjavascript":12,"keccak":32}],50:[function(require,module,exports){
10385/*
10386    Copyright 2018 0kims association.
10387
10388    This file is part of snarkjs.
10389
10390    snarkjs is a free software: you can redistribute it and/or
10391    modify it under the terms of the GNU General Public License as published by the
10392    Free Software Foundation, either version 3 of the License, or (at your option)
10393    any later version.
10394
10395    snarkjs is distributed in the hope that it will be useful,
10396    but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
10397    or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
10398    more details.
10399
10400    You should have received a copy of the GNU General Public License along with
10401    snarkjs. If not, see <https://www.gnu.org/licenses/>.
10402*/
10403
10404const bn128 = require("ffjavascript").bn128;
10405
10406const G1 = bn128.G1;
10407const G2 = bn128.G2;
10408
10409module.exports = function isValid(vk_verifier, proof, publicSignals) {
10410
10411    let full_pi_a = vk_verifier.IC[0];
10412    for (let s= 0; s< vk_verifier.nPublic; s++) {
10413        full_pi_a  = G1.add( full_pi_a, G1.mulScalar( vk_verifier.IC[s+1], publicSignals[s]));
10414    }
10415
10416    full_pi_a  = G1.add( full_pi_a, proof.pi_a);
10417
10418    if (! bn128.F12.eq(
10419        bn128.pairing( proof.pi_a , vk_verifier.vk_a ),
10420        bn128.pairing( proof.pi_ap , G2.g )))
10421        return false;
10422
10423    if (! bn128.F12.eq(
10424        bn128.pairing( vk_verifier.vk_b,  proof.pi_b ),
10425        bn128.pairing( proof.pi_bp , G2.g )))
10426        return false;
10427
10428    if (! bn128.F12.eq(
10429        bn128.pairing( proof.pi_c , vk_verifier.vk_c ),
10430        bn128.pairing( proof.pi_cp , G2.g )))
10431        return false;
10432
10433    if (! bn128.F12.eq(
10434        bn128.F12.mul(
10435            bn128.pairing( G1.add(full_pi_a, proof.pi_c) , vk_verifier.vk_gb_2 ),
10436            bn128.pairing( vk_verifier.vk_gb_1 , proof.pi_b )
10437        ),
10438        bn128.pairing( proof.pi_kp , vk_verifier.vk_g )))
10439        return false;
10440
10441    if (! bn128.F12.eq(
10442        bn128.pairing( full_pi_a , proof.pi_b  ),
10443        bn128.F12.mul(
10444            bn128.pairing( proof.pi_h , vk_verifier.vk_z ),
10445            bn128.pairing( proof.pi_c , G2.g  )
10446        )))
10447        return false;
10448
10449    return true;
10450};
10451
10452},{"ffjavascript":12}],51:[function(require,module,exports){
10453// Copyright Joyent, Inc. and other Node contributors.
10454//
10455// Permission is hereby granted, free of charge, to any person obtaining a
10456// copy of this software and associated documentation files (the
10457// "Software"), to deal in the Software without restriction, including
10458// without limitation the rights to use, copy, modify, merge, publish,
10459// distribute, sublicense, and/or sell copies of the Software, and to permit
10460// persons to whom the Software is furnished to do so, subject to the
10461// following conditions:
10462//
10463// The above copyright notice and this permission notice shall be included
10464// in all copies or substantial portions of the Software.
10465//
10466// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10467// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10468// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10469// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10470// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10471// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10472// USE OR OTHER DEALINGS IN THE SOFTWARE.
10473
10474module.exports = Stream;
10475
10476var EE = require('events').EventEmitter;
10477var inherits = require('inherits');
10478
10479inherits(Stream, EE);
10480Stream.Readable = require('readable-stream/readable.js');
10481Stream.Writable = require('readable-stream/writable.js');
10482Stream.Duplex = require('readable-stream/duplex.js');
10483Stream.Transform = require('readable-stream/transform.js');
10484Stream.PassThrough = require('readable-stream/passthrough.js');
10485
10486// Backwards-compat with node 0.4.x
10487Stream.Stream = Stream;
10488
10489
10490
10491// old-style streams.  Note that the pipe method (the only relevant
10492// part of this class) is overridden in the Readable class.
10493
10494function Stream() {
10495  EE.call(this);
10496}
10497
10498Stream.prototype.pipe = function(dest, options) {
10499  var source = this;
10500
10501  function ondata(chunk) {
10502    if (dest.writable) {
10503      if (false === dest.write(chunk) && source.pause) {
10504        source.pause();
10505      }
10506    }
10507  }
10508
10509  source.on('data', ondata);
10510
10511  function ondrain() {
10512    if (source.readable && source.resume) {
10513      source.resume();
10514    }
10515  }
10516
10517  dest.on('drain', ondrain);
10518
10519  // If the 'end' option is not supplied, dest.end() will be called when
10520  // source gets the 'end' or 'close' events.  Only dest.end() once.
10521  if (!dest._isStdio && (!options || options.end !== false)) {
10522    source.on('end', onend);
10523    source.on('close', onclose);
10524  }
10525
10526  var didOnEnd = false;
10527  function onend() {
10528    if (didOnEnd) return;
10529    didOnEnd = true;
10530
10531    dest.end();
10532  }
10533
10534
10535  function onclose() {
10536    if (didOnEnd) return;
10537    didOnEnd = true;
10538
10539    if (typeof dest.destroy === 'function') dest.destroy();
10540  }
10541
10542  // don't leave dangling pipes when there are errors.
10543  function onerror(er) {
10544    cleanup();
10545    if (EE.listenerCount(this, 'error') === 0) {
10546      throw er; // Unhandled stream error in pipe.
10547    }
10548  }
10549
10550  source.on('error', onerror);
10551  dest.on('error', onerror);
10552
10553  // remove all the event listeners that were added.
10554  function cleanup() {
10555    source.removeListener('data', ondata);
10556    dest.removeListener('drain', ondrain);
10557
10558    source.removeListener('end', onend);
10559    source.removeListener('close', onclose);
10560
10561    source.removeListener('error', onerror);
10562    dest.removeListener('error', onerror);
10563
10564    source.removeListener('end', cleanup);
10565    source.removeListener('close', cleanup);
10566
10567    dest.removeListener('close', cleanup);
10568  }
10569
10570  source.on('end', cleanup);
10571  source.on('close', cleanup);
10572
10573  dest.on('close', cleanup);
10574
10575  dest.emit('pipe', source);
10576
10577  // Allow for unix-like usage: A.pipe(B).pipe(C)
10578  return dest;
10579};
10580
10581},{"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){
10582module.exports = require('./lib/_stream_duplex.js');
10583
10584},{"./lib/_stream_duplex.js":53}],53:[function(require,module,exports){
10585// Copyright Joyent, Inc. and other Node contributors.
10586//
10587// Permission is hereby granted, free of charge, to any person obtaining a
10588// copy of this software and associated documentation files (the
10589// "Software"), to deal in the Software without restriction, including
10590// without limitation the rights to use, copy, modify, merge, publish,
10591// distribute, sublicense, and/or sell copies of the Software, and to permit
10592// persons to whom the Software is furnished to do so, subject to the
10593// following conditions:
10594//
10595// The above copyright notice and this permission notice shall be included
10596// in all copies or substantial portions of the Software.
10597//
10598// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10599// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10600// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10601// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10602// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10603// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10604// USE OR OTHER DEALINGS IN THE SOFTWARE.
10605
10606// a duplex stream is just a stream that is both readable and writable.
10607// Since JS doesn't have multiple prototypal inheritance, this class
10608// prototypally inherits from Readable, and then parasitically from
10609// Writable.
10610
10611'use strict';
10612
10613/*<replacement>*/
10614
10615var pna = require('process-nextick-args');
10616/*</replacement>*/
10617
10618/*<replacement>*/
10619var objectKeys = Object.keys || function (obj) {
10620  var keys = [];
10621  for (var key in obj) {
10622    keys.push(key);
10623  }return keys;
10624};
10625/*</replacement>*/
10626
10627module.exports = Duplex;
10628
10629/*<replacement>*/
10630var util = Object.create(require('core-util-is'));
10631util.inherits = require('inherits');
10632/*</replacement>*/
10633
10634var Readable = require('./_stream_readable');
10635var Writable = require('./_stream_writable');
10636
10637util.inherits(Duplex, Readable);
10638
10639{
10640  // avoid scope creep, the keys array can then be collected
10641  var keys = objectKeys(Writable.prototype);
10642  for (var v = 0; v < keys.length; v++) {
10643    var method = keys[v];
10644    if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
10645  }
10646}
10647
10648function Duplex(options) {
10649  if (!(this instanceof Duplex)) return new Duplex(options);
10650
10651  Readable.call(this, options);
10652  Writable.call(this, options);
10653
10654  if (options && options.readable === false) this.readable = false;
10655
10656  if (options && options.writable === false) this.writable = false;
10657
10658  this.allowHalfOpen = true;
10659  if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
10660
10661  this.once('end', onend);
10662}
10663
10664Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
10665  // making it explicit this property is not enumerable
10666  // because otherwise some prototype manipulation in
10667  // userland will fail
10668  enumerable: false,
10669  get: function () {
10670    return this._writableState.highWaterMark;
10671  }
10672});
10673
10674// the no-half-open enforcer
10675function onend() {
10676  // if we allow half-open state, or if the writable side ended,
10677  // then we're ok.
10678  if (this.allowHalfOpen || this._writableState.ended) return;
10679
10680  // no more data can be written.
10681  // But allow more writes to happen in this tick.
10682  pna.nextTick(onEndNT, this);
10683}
10684
10685function onEndNT(self) {
10686  self.end();
10687}
10688
10689Object.defineProperty(Duplex.prototype, 'destroyed', {
10690  get: function () {
10691    if (this._readableState === undefined || this._writableState === undefined) {
10692      return false;
10693    }
10694    return this._readableState.destroyed && this._writableState.destroyed;
10695  },
10696  set: function (value) {
10697    // we ignore the value if the stream
10698    // has not been initialized yet
10699    if (this._readableState === undefined || this._writableState === undefined) {
10700      return;
10701    }
10702
10703    // backward compatibility, the user is explicitly
10704    // managing destroyed
10705    this._readableState.destroyed = value;
10706    this._writableState.destroyed = value;
10707  }
10708});
10709
10710Duplex.prototype._destroy = function (err, cb) {
10711  this.push(null);
10712  this.end();
10713
10714  pna.nextTick(cb, err);
10715};
10716},{"./_stream_readable":55,"./_stream_writable":57,"core-util-is":10,"inherits":29,"process-nextick-args":39}],54:[function(require,module,exports){
10717// Copyright Joyent, Inc. and other Node contributors.
10718//
10719// Permission is hereby granted, free of charge, to any person obtaining a
10720// copy of this software and associated documentation files (the
10721// "Software"), to deal in the Software without restriction, including
10722// without limitation the rights to use, copy, modify, merge, publish,
10723// distribute, sublicense, and/or sell copies of the Software, and to permit
10724// persons to whom the Software is furnished to do so, subject to the
10725// following conditions:
10726//
10727// The above copyright notice and this permission notice shall be included
10728// in all copies or substantial portions of the Software.
10729//
10730// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10731// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10732// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10733// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10734// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10735// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10736// USE OR OTHER DEALINGS IN THE SOFTWARE.
10737
10738// a passthrough stream.
10739// basically just the most minimal sort of Transform stream.
10740// Every written chunk gets output as-is.
10741
10742'use strict';
10743
10744module.exports = PassThrough;
10745
10746var Transform = require('./_stream_transform');
10747
10748/*<replacement>*/
10749var util = Object.create(require('core-util-is'));
10750util.inherits = require('inherits');
10751/*</replacement>*/
10752
10753util.inherits(PassThrough, Transform);
10754
10755function PassThrough(options) {
10756  if (!(this instanceof PassThrough)) return new PassThrough(options);
10757
10758  Transform.call(this, options);
10759}
10760
10761PassThrough.prototype._transform = function (chunk, encoding, cb) {
10762  cb(null, chunk);
10763};
10764},{"./_stream_transform":56,"core-util-is":10,"inherits":29}],55:[function(require,module,exports){
10765(function (process,global){
10766// Copyright Joyent, Inc. and other Node contributors.
10767//
10768// Permission is hereby granted, free of charge, to any person obtaining a
10769// copy of this software and associated documentation files (the
10770// "Software"), to deal in the Software without restriction, including
10771// without limitation the rights to use, copy, modify, merge, publish,
10772// distribute, sublicense, and/or sell copies of the Software, and to permit
10773// persons to whom the Software is furnished to do so, subject to the
10774// following conditions:
10775//
10776// The above copyright notice and this permission notice shall be included
10777// in all copies or substantial portions of the Software.
10778//
10779// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
10780// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
10781// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
10782// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
10783// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
10784// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
10785// USE OR OTHER DEALINGS IN THE SOFTWARE.
10786
10787'use strict';
10788
10789/*<replacement>*/
10790
10791var pna = require('process-nextick-args');
10792/*</replacement>*/
10793
10794module.exports = Readable;
10795
10796/*<replacement>*/
10797var isArray = require('isarray');
10798/*</replacement>*/
10799
10800/*<replacement>*/
10801var Duplex;
10802/*</replacement>*/
10803
10804Readable.ReadableState = ReadableState;
10805
10806/*<replacement>*/
10807var EE = require('events').EventEmitter;
10808
10809var EElistenerCount = function (emitter, type) {
10810  return emitter.listeners(type).length;
10811};
10812/*</replacement>*/
10813
10814/*<replacement>*/
10815var Stream = require('./internal/streams/stream');
10816/*</replacement>*/
10817
10818/*<replacement>*/
10819
10820var Buffer = require('safe-buffer').Buffer;
10821var OurUint8Array = global.Uint8Array || function () {};
10822function _uint8ArrayToBuffer(chunk) {
10823  return Buffer.from(chunk);
10824}
10825function _isUint8Array(obj) {
10826  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
10827}
10828
10829/*</replacement>*/
10830
10831/*<replacement>*/
10832var util = Object.create(require('core-util-is'));
10833util.inherits = require('inherits');
10834/*</replacement>*/
10835
10836/*<replacement>*/
10837var debugUtil = require('util');
10838var debug = void 0;
10839if (debugUtil && debugUtil.debuglog) {
10840  debug = debugUtil.debuglog('stream');
10841} else {
10842  debug = function () {};
10843}
10844/*</replacement>*/
10845
10846var BufferList = require('./internal/streams/BufferList');
10847var destroyImpl = require('./internal/streams/destroy');
10848var StringDecoder;
10849
10850util.inherits(Readable, Stream);
10851
10852var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
10853
10854function prependListener(emitter, event, fn) {
10855  // Sadly this is not cacheable as some libraries bundle their own
10856  // event emitter implementation with them.
10857  if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
10858
10859  // This is a hack to make sure that our error handler is attached before any
10860  // userland ones.  NEVER DO THIS. This is here only because this code needs
10861  // to continue to work with older versions of Node.js that do not include
10862  // the prependListener() method. The goal is to eventually remove this hack.
10863  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]];
10864}
10865
10866function ReadableState(options, stream) {
10867  Duplex = Duplex || require('./_stream_duplex');
10868
10869  options = options || {};
10870
10871  // Duplex streams are both readable and writable, but share
10872  // the same options object.
10873  // However, some cases require setting options to different
10874  // values for the readable and the writable sides of the duplex stream.
10875  // These options can be provided separately as readableXXX and writableXXX.
10876  var isDuplex = stream instanceof Duplex;
10877
10878  // object stream flag. Used to make read(n) ignore n and to
10879  // make all the buffer merging and length checks go away
10880  this.objectMode = !!options.objectMode;
10881
10882  if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
10883
10884  // the point at which it stops calling _read() to fill the buffer
10885  // Note: 0 is a valid value, means "don't call _read preemptively ever"
10886  var hwm = options.highWaterMark;
10887  var readableHwm = options.readableHighWaterMark;
10888  var defaultHwm = this.objectMode ? 16 : 16 * 1024;
10889
10890  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
10891
10892  // cast to ints.
10893  this.highWaterMark = Math.floor(this.highWaterMark);
10894
10895  // A linked list is used to store data chunks instead of an array because the
10896  // linked list can remove elements from the beginning faster than
10897  // array.shift()
10898  this.buffer = new BufferList();
10899  this.length = 0;
10900  this.pipes = null;
10901  this.pipesCount = 0;
10902  this.flowing = null;
10903  this.ended = false;
10904  this.endEmitted = false;
10905  this.reading = false;
10906
10907  // a flag to be able to tell if the event 'readable'/'data' is emitted
10908  // immediately, or on a later tick.  We set this to true at first, because
10909  // any actions that shouldn't happen until "later" should generally also
10910  // not happen before the first read call.
10911  this.sync = true;
10912
10913  // whenever we return null, then we set a flag to say
10914  // that we're awaiting a 'readable' event emission.
10915  this.needReadable = false;
10916  this.emittedReadable = false;
10917  this.readableListening = false;
10918  this.resumeScheduled = false;
10919
10920  // has it been destroyed
10921  this.destroyed = false;
10922
10923  // Crypto is kind of old and crusty.  Historically, its default string
10924  // encoding is 'binary' so we have to make this configurable.
10925  // Everything else in the universe uses 'utf8', though.
10926  this.defaultEncoding = options.defaultEncoding || 'utf8';
10927
10928  // the number of writers that are awaiting a drain event in .pipe()s
10929  this.awaitDrain = 0;
10930
10931  // if true, a maybeReadMore has been scheduled
10932  this.readingMore = false;
10933
10934  this.decoder = null;
10935  this.encoding = null;
10936  if (options.encoding) {
10937    if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
10938    this.decoder = new StringDecoder(options.encoding);
10939    this.encoding = options.encoding;
10940  }
10941}
10942
10943function Readable(options) {
10944  Duplex = Duplex || require('./_stream_duplex');
10945
10946  if (!(this instanceof Readable)) return new Readable(options);
10947
10948  this._readableState = new ReadableState(options, this);
10949
10950  // legacy
10951  this.readable = true;
10952
10953  if (options) {
10954    if (typeof options.read === 'function') this._read = options.read;
10955
10956    if (typeof options.destroy === 'function') this._destroy = options.destroy;
10957  }
10958
10959  Stream.call(this);
10960}
10961
10962Object.defineProperty(Readable.prototype, 'destroyed', {
10963  get: function () {
10964    if (this._readableState === undefined) {
10965      return false;
10966    }
10967    return this._readableState.destroyed;
10968  },
10969  set: function (value) {
10970    // we ignore the value if the stream
10971    // has not been initialized yet
10972    if (!this._readableState) {
10973      return;
10974    }
10975
10976    // backward compatibility, the user is explicitly
10977    // managing destroyed
10978    this._readableState.destroyed = value;
10979  }
10980});
10981
10982Readable.prototype.destroy = destroyImpl.destroy;
10983Readable.prototype._undestroy = destroyImpl.undestroy;
10984Readable.prototype._destroy = function (err, cb) {
10985  this.push(null);
10986  cb(err);
10987};
10988
10989// Manually shove something into the read() buffer.
10990// This returns true if the highWaterMark has not been hit yet,
10991// similar to how Writable.write() returns true if you should
10992// write() some more.
10993Readable.prototype.push = function (chunk, encoding) {
10994  var state = this._readableState;
10995  var skipChunkCheck;
10996
10997  if (!state.objectMode) {
10998    if (typeof chunk === 'string') {
10999      encoding = encoding || state.defaultEncoding;
11000      if (encoding !== state.encoding) {
11001        chunk = Buffer.from(chunk, encoding);
11002        encoding = '';
11003      }
11004      skipChunkCheck = true;
11005    }
11006  } else {
11007    skipChunkCheck = true;
11008  }
11009
11010  return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
11011};
11012
11013// Unshift should *always* be something directly out of read()
11014Readable.prototype.unshift = function (chunk) {
11015  return readableAddChunk(this, chunk, null, true, false);
11016};
11017
11018function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
11019  var state = stream._readableState;
11020  if (chunk === null) {
11021    state.reading = false;
11022    onEofChunk(stream, state);
11023  } else {
11024    var er;
11025    if (!skipChunkCheck) er = chunkInvalid(state, chunk);
11026    if (er) {
11027      stream.emit('error', er);
11028    } else if (state.objectMode || chunk && chunk.length > 0) {
11029      if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
11030        chunk = _uint8ArrayToBuffer(chunk);
11031      }
11032
11033      if (addToFront) {
11034        if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
11035      } else if (state.ended) {
11036        stream.emit('error', new Error('stream.push() after EOF'));
11037      } else {
11038        state.reading = false;
11039        if (state.decoder && !encoding) {
11040          chunk = state.decoder.write(chunk);
11041          if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
11042        } else {
11043          addChunk(stream, state, chunk, false);
11044        }
11045      }
11046    } else if (!addToFront) {
11047      state.reading = false;
11048    }
11049  }
11050
11051  return needMoreData(state);
11052}
11053
11054function addChunk(stream, state, chunk, addToFront) {
11055  if (state.flowing && state.length === 0 && !state.sync) {
11056    stream.emit('data', chunk);
11057    stream.read(0);
11058  } else {
11059    // update the buffer info.
11060    state.length += state.objectMode ? 1 : chunk.length;
11061    if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
11062
11063    if (state.needReadable) emitReadable(stream);
11064  }
11065  maybeReadMore(stream, state);
11066}
11067
11068function chunkInvalid(state, chunk) {
11069  var er;
11070  if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
11071    er = new TypeError('Invalid non-string/buffer chunk');
11072  }
11073  return er;
11074}
11075
11076// if it's past the high water mark, we can push in some more.
11077// Also, if we have no data yet, we can stand some
11078// more bytes.  This is to work around cases where hwm=0,
11079// such as the repl.  Also, if the push() triggered a
11080// readable event, and the user called read(largeNumber) such that
11081// needReadable was set, then we ought to push more, so that another
11082// 'readable' event will be triggered.
11083function needMoreData(state) {
11084  return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
11085}
11086
11087Readable.prototype.isPaused = function () {
11088  return this._readableState.flowing === false;
11089};
11090
11091// backwards compatibility.
11092Readable.prototype.setEncoding = function (enc) {
11093  if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
11094  this._readableState.decoder = new StringDecoder(enc);
11095  this._readableState.encoding = enc;
11096  return this;
11097};
11098
11099// Don't raise the hwm > 8MB
11100var MAX_HWM = 0x800000;
11101function computeNewHighWaterMark(n) {
11102  if (n >= MAX_HWM) {
11103    n = MAX_HWM;
11104  } else {
11105    // Get the next highest power of 2 to prevent increasing hwm excessively in
11106    // tiny amounts
11107    n--;
11108    n |= n >>> 1;
11109    n |= n >>> 2;
11110    n |= n >>> 4;
11111    n |= n >>> 8;
11112    n |= n >>> 16;
11113    n++;
11114  }
11115  return n;
11116}
11117
11118// This function is designed to be inlinable, so please take care when making
11119// changes to the function body.
11120function howMuchToRead(n, state) {
11121  if (n <= 0 || state.length === 0 && state.ended) return 0;
11122  if (state.objectMode) return 1;
11123  if (n !== n) {
11124    // Only flow one buffer at a time
11125    if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
11126  }
11127  // If we're asking for more than the current hwm, then raise the hwm.
11128  if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
11129  if (n <= state.length) return n;
11130  // Don't have enough
11131  if (!state.ended) {
11132    state.needReadable = true;
11133    return 0;
11134  }
11135  return state.length;
11136}
11137
11138// you can override either this method, or the async _read(n) below.
11139Readable.prototype.read = function (n) {
11140  debug('read', n);
11141  n = parseInt(n, 10);
11142  var state = this._readableState;
11143  var nOrig = n;
11144
11145  if (n !== 0) state.emittedReadable = false;
11146
11147  // if we're doing read(0) to trigger a readable event, but we
11148  // already have a bunch of data in the buffer, then just trigger
11149  // the 'readable' event and move on.
11150  if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
11151    debug('read: emitReadable', state.length, state.ended);
11152    if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
11153    return null;
11154  }
11155
11156  n = howMuchToRead(n, state);
11157
11158  // if we've ended, and we're now clear, then finish it up.
11159  if (n === 0 && state.ended) {
11160    if (state.length === 0) endReadable(this);
11161    return null;
11162  }
11163
11164  // All the actual chunk generation logic needs to be
11165  // *below* the call to _read.  The reason is that in certain
11166  // synthetic stream cases, such as passthrough streams, _read
11167  // may be a completely synchronous operation which may change
11168  // the state of the read buffer, providing enough data when
11169  // before there was *not* enough.
11170  //
11171  // So, the steps are:
11172  // 1. Figure out what the state of things will be after we do
11173  // a read from the buffer.
11174  //
11175  // 2. If that resulting state will trigger a _read, then call _read.
11176  // Note that this may be asynchronous, or synchronous.  Yes, it is
11177  // deeply ugly to write APIs this way, but that still doesn't mean
11178  // that the Readable class should behave improperly, as streams are
11179  // designed to be sync/async agnostic.
11180  // Take note if the _read call is sync or async (ie, if the read call
11181  // has returned yet), so that we know whether or not it's safe to emit
11182  // 'readable' etc.
11183  //
11184  // 3. Actually pull the requested chunks out of the buffer and return.
11185
11186  // if we need a readable event, then we need to do some reading.
11187  var doRead = state.needReadable;
11188  debug('need readable', doRead);
11189
11190  // if we currently have less than the highWaterMark, then also read some
11191  if (state.length === 0 || state.length - n < state.highWaterMark) {
11192    doRead = true;
11193    debug('length less than watermark', doRead);
11194  }
11195
11196  // however, if we've ended, then there's no point, and if we're already
11197  // reading, then it's unnecessary.
11198  if (state.ended || state.reading) {
11199    doRead = false;
11200    debug('reading or ended', doRead);
11201  } else if (doRead) {
11202    debug('do read');
11203    state.reading = true;
11204    state.sync = true;
11205    // if the length is currently zero, then we *need* a readable event.
11206    if (state.length === 0) state.needReadable = true;
11207    // call internal read method
11208    this._read(state.highWaterMark);
11209    state.sync = false;
11210    // If _read pushed data synchronously, then `reading` will be false,
11211    // and we need to re-evaluate how much data we can return to the user.
11212    if (!state.reading) n = howMuchToRead(nOrig, state);
11213  }
11214
11215  var ret;
11216  if (n > 0) ret = fromList(n, state);else ret = null;
11217
11218  if (ret === null) {
11219    state.needReadable = true;
11220    n = 0;
11221  } else {
11222    state.length -= n;
11223  }
11224
11225  if (state.length === 0) {
11226    // If we have nothing in the buffer, then we want to know
11227    // as soon as we *do* get something into the buffer.
11228    if (!state.ended) state.needReadable = true;
11229
11230    // If we tried to read() past the EOF, then emit end on the next tick.
11231    if (nOrig !== n && state.ended) endReadable(this);
11232  }
11233
11234  if (ret !== null) this.emit('data', ret);
11235
11236  return ret;
11237};
11238
11239function onEofChunk(stream, state) {
11240  if (state.ended) return;
11241  if (state.decoder) {
11242    var chunk = state.decoder.end();
11243    if (chunk && chunk.length) {
11244      state.buffer.push(chunk);
11245      state.length += state.objectMode ? 1 : chunk.length;
11246    }
11247  }
11248  state.ended = true;
11249
11250  // emit 'readable' now to make sure it gets picked up.
11251  emitReadable(stream);
11252}
11253
11254// Don't emit readable right away in sync mode, because this can trigger
11255// another read() call => stack overflow.  This way, it might trigger
11256// a nextTick recursion warning, but that's not so bad.
11257function emitReadable(stream) {
11258  var state = stream._readableState;
11259  state.needReadable = false;
11260  if (!state.emittedReadable) {
11261    debug('emitReadable', state.flowing);
11262    state.emittedReadable = true;
11263    if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
11264  }
11265}
11266
11267function emitReadable_(stream) {
11268  debug('emit readable');
11269  stream.emit('readable');
11270  flow(stream);
11271}
11272
11273// at this point, the user has presumably seen the 'readable' event,
11274// and called read() to consume some data.  that may have triggered
11275// in turn another _read(n) call, in which case reading = true if
11276// it's in progress.
11277// However, if we're not ended, or reading, and the length < hwm,
11278// then go ahead and try to read some more preemptively.
11279function maybeReadMore(stream, state) {
11280  if (!state.readingMore) {
11281    state.readingMore = true;
11282    pna.nextTick(maybeReadMore_, stream, state);
11283  }
11284}
11285
11286function maybeReadMore_(stream, state) {
11287  var len = state.length;
11288  while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
11289    debug('maybeReadMore read 0');
11290    stream.read(0);
11291    if (len === state.length)
11292      // didn't get any data, stop spinning.
11293      break;else len = state.length;
11294  }
11295  state.readingMore = false;
11296}
11297
11298// abstract method.  to be overridden in specific implementation classes.
11299// call cb(er, data) where data is <= n in length.
11300// for virtual (non-string, non-buffer) streams, "length" is somewhat
11301// arbitrary, and perhaps not very meaningful.
11302Readable.prototype._read = function (n) {
11303  this.emit('error', new Error('_read() is not implemented'));
11304};
11305
11306Readable.prototype.pipe = function (dest, pipeOpts) {
11307  var src = this;
11308  var state = this._readableState;
11309
11310  switch (state.pipesCount) {
11311    case 0:
11312      state.pipes = dest;
11313      break;
11314    case 1:
11315      state.pipes = [state.pipes, dest];
11316      break;
11317    default:
11318      state.pipes.push(dest);
11319      break;
11320  }
11321  state.pipesCount += 1;
11322  debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
11323
11324  var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
11325
11326  var endFn = doEnd ? onend : unpipe;
11327  if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
11328
11329  dest.on('unpipe', onunpipe);
11330  function onunpipe(readable, unpipeInfo) {
11331    debug('onunpipe');
11332    if (readable === src) {
11333      if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
11334        unpipeInfo.hasUnpiped = true;
11335        cleanup();
11336      }
11337    }
11338  }
11339
11340  function onend() {
11341    debug('onend');
11342    dest.end();
11343  }
11344
11345  // when the dest drains, it reduces the awaitDrain counter
11346  // on the source.  This would be more elegant with a .once()
11347  // handler in flow(), but adding and removing repeatedly is
11348  // too slow.
11349  var ondrain = pipeOnDrain(src);
11350  dest.on('drain', ondrain);
11351
11352  var cleanedUp = false;
11353  function cleanup() {
11354    debug('cleanup');
11355    // cleanup event handlers once the pipe is broken
11356    dest.removeListener('close', onclose);
11357    dest.removeListener('finish', onfinish);
11358    dest.removeListener('drain', ondrain);
11359    dest.removeListener('error', onerror);
11360    dest.removeListener('unpipe', onunpipe);
11361    src.removeListener('end', onend);
11362    src.removeListener('end', unpipe);
11363    src.removeListener('data', ondata);
11364
11365    cleanedUp = true;
11366
11367    // if the reader is waiting for a drain event from this
11368    // specific writer, then it would cause it to never start
11369    // flowing again.
11370    // So, if this is awaiting a drain, then we just call it now.
11371    // If we don't know, then assume that we are waiting for one.
11372    if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
11373  }
11374
11375  // If the user pushes more data while we're writing to dest then we'll end up
11376  // in ondata again. However, we only want to increase awaitDrain once because
11377  // dest will only emit one 'drain' event for the multiple writes.
11378  // => Introduce a guard on increasing awaitDrain.
11379  var increasedAwaitDrain = false;
11380  src.on('data', ondata);
11381  function ondata(chunk) {
11382    debug('ondata');
11383    increasedAwaitDrain = false;
11384    var ret = dest.write(chunk);
11385    if (false === ret && !increasedAwaitDrain) {
11386      // If the user unpiped during `dest.write()`, it is possible
11387      // to get stuck in a permanently paused state if that write
11388      // also returned false.
11389      // => Check whether `dest` is still a piping destination.
11390      if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
11391        debug('false write response, pause', src._readableState.awaitDrain);
11392        src._readableState.awaitDrain++;
11393        increasedAwaitDrain = true;
11394      }
11395      src.pause();
11396    }
11397  }
11398
11399  // if the dest has an error, then stop piping into it.
11400  // however, don't suppress the throwing behavior for this.
11401  function onerror(er) {
11402    debug('onerror', er);
11403    unpipe();
11404    dest.removeListener('error', onerror);
11405    if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
11406  }
11407
11408  // Make sure our error handler is attached before userland ones.
11409  prependListener(dest, 'error', onerror);
11410
11411  // Both close and finish should trigger unpipe, but only once.
11412  function onclose() {
11413    dest.removeListener('finish', onfinish);
11414    unpipe();
11415  }
11416  dest.once('close', onclose);
11417  function onfinish() {
11418    debug('onfinish');
11419    dest.removeListener('close', onclose);
11420    unpipe();
11421  }
11422  dest.once('finish', onfinish);
11423
11424  function unpipe() {
11425    debug('unpipe');
11426    src.unpipe(dest);
11427  }
11428
11429  // tell the dest that it's being piped to
11430  dest.emit('pipe', src);
11431
11432  // start the flow if it hasn't been started already.
11433  if (!state.flowing) {
11434    debug('pipe resume');
11435    src.resume();
11436  }
11437
11438  return dest;
11439};
11440
11441function pipeOnDrain(src) {
11442  return function () {
11443    var state = src._readableState;
11444    debug('pipeOnDrain', state.awaitDrain);
11445    if (state.awaitDrain) state.awaitDrain--;
11446    if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
11447      state.flowing = true;
11448      flow(src);
11449    }
11450  };
11451}
11452
11453Readable.prototype.unpipe = function (dest) {
11454  var state = this._readableState;
11455  var unpipeInfo = { hasUnpiped: false };
11456
11457  // if we're not piping anywhere, then do nothing.
11458  if (state.pipesCount === 0) return this;
11459
11460  // just one destination.  most common case.
11461  if (state.pipesCount === 1) {
11462    // passed in one, but it's not the right one.
11463    if (dest && dest !== state.pipes) return this;
11464
11465    if (!dest) dest = state.pipes;
11466
11467    // got a match.
11468    state.pipes = null;
11469    state.pipesCount = 0;
11470    state.flowing = false;
11471    if (dest) dest.emit('unpipe', this, unpipeInfo);
11472    return this;
11473  }
11474
11475  // slow case. multiple pipe destinations.
11476
11477  if (!dest) {
11478    // remove all.
11479    var dests = state.pipes;
11480    var len = state.pipesCount;
11481    state.pipes = null;
11482    state.pipesCount = 0;
11483    state.flowing = false;
11484
11485    for (var i = 0; i < len; i++) {
11486      dests[i].emit('unpipe', this, unpipeInfo);
11487    }return this;
11488  }
11489
11490  // try to find the right one.
11491  var index = indexOf(state.pipes, dest);
11492  if (index === -1) return this;
11493
11494  state.pipes.splice(index, 1);
11495  state.pipesCount -= 1;
11496  if (state.pipesCount === 1) state.pipes = state.pipes[0];
11497
11498  dest.emit('unpipe', this, unpipeInfo);
11499
11500  return this;
11501};
11502
11503// set up data events if they are asked for
11504// Ensure readable listeners eventually get something
11505Readable.prototype.on = function (ev, fn) {
11506  var res = Stream.prototype.on.call(this, ev, fn);
11507
11508  if (ev === 'data') {
11509    // Start flowing on next tick if stream isn't explicitly paused
11510    if (this._readableState.flowing !== false) this.resume();
11511  } else if (ev === 'readable') {
11512    var state = this._readableState;
11513    if (!state.endEmitted && !state.readableListening) {
11514      state.readableListening = state.needReadable = true;
11515      state.emittedReadable = false;
11516      if (!state.reading) {
11517        pna.nextTick(nReadingNextTick, this);
11518      } else if (state.length) {
11519        emitReadable(this);
11520      }
11521    }
11522  }
11523
11524  return res;
11525};
11526Readable.prototype.addListener = Readable.prototype.on;
11527
11528function nReadingNextTick(self) {
11529  debug('readable nexttick read 0');
11530  self.read(0);
11531}
11532
11533// pause() and resume() are remnants of the legacy readable stream API
11534// If the user uses them, then switch into old mode.
11535Readable.prototype.resume = function () {
11536  var state = this._readableState;
11537  if (!state.flowing) {
11538    debug('resume');
11539    state.flowing = true;
11540    resume(this, state);
11541  }
11542  return this;
11543};
11544
11545function resume(stream, state) {
11546  if (!state.resumeScheduled) {
11547    state.resumeScheduled = true;
11548    pna.nextTick(resume_, stream, state);
11549  }
11550}
11551
11552function resume_(stream, state) {
11553  if (!state.reading) {
11554    debug('resume read 0');
11555    stream.read(0);
11556  }
11557
11558  state.resumeScheduled = false;
11559  state.awaitDrain = 0;
11560  stream.emit('resume');
11561  flow(stream);
11562  if (state.flowing && !state.reading) stream.read(0);
11563}
11564
11565Readable.prototype.pause = function () {
11566  debug('call pause flowing=%j', this._readableState.flowing);
11567  if (false !== this._readableState.flowing) {
11568    debug('pause');
11569    this._readableState.flowing = false;
11570    this.emit('pause');
11571  }
11572  return this;
11573};
11574
11575function flow(stream) {
11576  var state = stream._readableState;
11577  debug('flow', state.flowing);
11578  while (state.flowing && stream.read() !== null) {}
11579}
11580
11581// wrap an old-style stream as the async data source.
11582// This is *not* part of the readable stream interface.
11583// It is an ugly unfortunate mess of history.
11584Readable.prototype.wrap = function (stream) {
11585  var _this = this;
11586
11587  var state = this._readableState;
11588  var paused = false;
11589
11590  stream.on('end', function () {
11591    debug('wrapped end');
11592    if (state.decoder && !state.ended) {
11593      var chunk = state.decoder.end();
11594      if (chunk && chunk.length) _this.push(chunk);
11595    }
11596
11597    _this.push(null);
11598  });
11599
11600  stream.on('data', function (chunk) {
11601    debug('wrapped data');
11602    if (state.decoder) chunk = state.decoder.write(chunk);
11603
11604    // don't skip over falsy values in objectMode
11605    if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
11606
11607    var ret = _this.push(chunk);
11608    if (!ret) {
11609      paused = true;
11610      stream.pause();
11611    }
11612  });
11613
11614  // proxy all the other methods.
11615  // important when wrapping filters and duplexes.
11616  for (var i in stream) {
11617    if (this[i] === undefined && typeof stream[i] === 'function') {
11618      this[i] = function (method) {
11619        return function () {
11620          return stream[method].apply(stream, arguments);
11621        };
11622      }(i);
11623    }
11624  }
11625
11626  // proxy certain important events.
11627  for (var n = 0; n < kProxyEvents.length; n++) {
11628    stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
11629  }
11630
11631  // when we try to consume some more bytes, simply unpause the
11632  // underlying stream.
11633  this._read = function (n) {
11634    debug('wrapped _read', n);
11635    if (paused) {
11636      paused = false;
11637      stream.resume();
11638    }
11639  };
11640
11641  return this;
11642};
11643
11644Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
11645  // making it explicit this property is not enumerable
11646  // because otherwise some prototype manipulation in
11647  // userland will fail
11648  enumerable: false,
11649  get: function () {
11650    return this._readableState.highWaterMark;
11651  }
11652});
11653
11654// exposed for testing purposes only.
11655Readable._fromList = fromList;
11656
11657// Pluck off n bytes from an array of buffers.
11658// Length is the combined lengths of all the buffers in the list.
11659// This function is designed to be inlinable, so please take care when making
11660// changes to the function body.
11661function fromList(n, state) {
11662  // nothing buffered
11663  if (state.length === 0) return null;
11664
11665  var ret;
11666  if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
11667    // read it all, truncate the list
11668    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);
11669    state.buffer.clear();
11670  } else {
11671    // read part of list
11672    ret = fromListPartial(n, state.buffer, state.decoder);
11673  }
11674
11675  return ret;
11676}
11677
11678// Extracts only enough buffered data to satisfy the amount requested.
11679// This function is designed to be inlinable, so please take care when making
11680// changes to the function body.
11681function fromListPartial(n, list, hasStrings) {
11682  var ret;
11683  if (n < list.head.data.length) {
11684    // slice is the same for buffers and strings
11685    ret = list.head.data.slice(0, n);
11686    list.head.data = list.head.data.slice(n);
11687  } else if (n === list.head.data.length) {
11688    // first chunk is a perfect match
11689    ret = list.shift();
11690  } else {
11691    // result spans more than one buffer
11692    ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
11693  }
11694  return ret;
11695}
11696
11697// Copies a specified amount of characters from the list of buffered data
11698// chunks.
11699// This function is designed to be inlinable, so please take care when making
11700// changes to the function body.
11701function copyFromBufferString(n, list) {
11702  var p = list.head;
11703  var c = 1;
11704  var ret = p.data;
11705  n -= ret.length;
11706  while (p = p.next) {
11707    var str = p.data;
11708    var nb = n > str.length ? str.length : n;
11709    if (nb === str.length) ret += str;else ret += str.slice(0, n);
11710    n -= nb;
11711    if (n === 0) {
11712      if (nb === str.length) {
11713        ++c;
11714        if (p.next) list.head = p.next;else list.head = list.tail = null;
11715      } else {
11716        list.head = p;
11717        p.data = str.slice(nb);
11718      }
11719      break;
11720    }
11721    ++c;
11722  }
11723  list.length -= c;
11724  return ret;
11725}
11726
11727// Copies a specified amount of bytes from the list of buffered data chunks.
11728// This function is designed to be inlinable, so please take care when making
11729// changes to the function body.
11730function copyFromBuffer(n, list) {
11731  var ret = Buffer.allocUnsafe(n);
11732  var p = list.head;
11733  var c = 1;
11734  p.data.copy(ret);
11735  n -= p.data.length;
11736  while (p = p.next) {
11737    var buf = p.data;
11738    var nb = n > buf.length ? buf.length : n;
11739    buf.copy(ret, ret.length - n, 0, nb);
11740    n -= nb;
11741    if (n === 0) {
11742      if (nb === buf.length) {
11743        ++c;
11744        if (p.next) list.head = p.next;else list.head = list.tail = null;
11745      } else {
11746        list.head = p;
11747        p.data = buf.slice(nb);
11748      }
11749      break;
11750    }
11751    ++c;
11752  }
11753  list.length -= c;
11754  return ret;
11755}
11756
11757function endReadable(stream) {
11758  var state = stream._readableState;
11759
11760  // If we get here before consuming all the bytes, then that is a
11761  // bug in node.  Should never happen.
11762  if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
11763
11764  if (!state.endEmitted) {
11765    state.ended = true;
11766    pna.nextTick(endReadableNT, state, stream);
11767  }
11768}
11769
11770function endReadableNT(state, stream) {
11771  // Check that we didn't get one last unshift.
11772  if (!state.endEmitted && state.length === 0) {
11773    state.endEmitted = true;
11774    stream.readable = false;
11775    stream.emit('end');
11776  }
11777}
11778
11779function indexOf(xs, x) {
11780  for (var i = 0, l = xs.length; i < l; i++) {
11781    if (xs[i] === x) return i;
11782  }
11783  return -1;
11784}
11785}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
11786},{"./_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){
11787// Copyright Joyent, Inc. and other Node contributors.
11788//
11789// Permission is hereby granted, free of charge, to any person obtaining a
11790// copy of this software and associated documentation files (the
11791// "Software"), to deal in the Software without restriction, including
11792// without limitation the rights to use, copy, modify, merge, publish,
11793// distribute, sublicense, and/or sell copies of the Software, and to permit
11794// persons to whom the Software is furnished to do so, subject to the
11795// following conditions:
11796//
11797// The above copyright notice and this permission notice shall be included
11798// in all copies or substantial portions of the Software.
11799//
11800// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
11801// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
11802// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
11803// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
11804// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
11805// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
11806// USE OR OTHER DEALINGS IN THE SOFTWARE.
11807
11808// a transform stream is a readable/writable stream where you do
11809// something with the data.  Sometimes it's called a "filter",
11810// but that's not a great name for it, since that implies a thing where
11811// some bits pass through, and others are simply ignored.  (That would
11812// be a valid example of a transform, of course.)
11813//
11814// While the output is causally related to the input, it's not a
11815// necessarily symmetric or synchronous transformation.  For example,
11816// a zlib stream might take multiple plain-text writes(), and then
11817// emit a single compressed chunk some time in the future.
11818//
11819// Here's how this works:
11820//
11821// The Transform stream has all the aspects of the readable and writable
11822// stream classes.  When you write(chunk), that calls _write(chunk,cb)
11823// internally, and returns false if there's a lot of pending writes
11824// buffered up.  When you call read(), that calls _read(n) until
11825// there's enough pending readable data buffered up.
11826//
11827// In a transform stream, the written data is placed in a buffer.  When
11828// _read(n) is called, it transforms the queued up data, calling the
11829// buffered _write cb's as it consumes chunks.  If consuming a single
11830// written chunk would result in multiple output chunks, then the first
11831// outputted bit calls the readcb, and subsequent chunks just go into
11832// the read buffer, and will cause it to emit 'readable' if necessary.
11833//
11834// This way, back-pressure is actually determined by the reading side,
11835// since _read has to be called to start processing a new chunk.  However,
11836// a pathological inflate type of transform can cause excessive buffering
11837// here.  For example, imagine a stream where every byte of input is
11838// interpreted as an integer from 0-255, and then results in that many
11839// bytes of output.  Writing the 4 bytes {ff,ff,ff,ff} would result in
11840// 1kb of data being output.  In this case, you could write a very small
11841// amount of input, and end up with a very large amount of output.  In
11842// such a pathological inflating mechanism, there'd be no way to tell
11843// the system to stop doing the transform.  A single 4MB write could
11844// cause the system to run out of memory.
11845//
11846// However, even in such a pathological case, only a single written chunk
11847// would be consumed, and then the rest would wait (un-transformed) until
11848// the results of the previous transformed chunk were consumed.
11849
11850'use strict';
11851
11852module.exports = Transform;
11853
11854var Duplex = require('./_stream_duplex');
11855
11856/*<replacement>*/
11857var util = Object.create(require('core-util-is'));
11858util.inherits = require('inherits');
11859/*</replacement>*/
11860
11861util.inherits(Transform, Duplex);
11862
11863function afterTransform(er, data) {
11864  var ts = this._transformState;
11865  ts.transforming = false;
11866
11867  var cb = ts.writecb;
11868
11869  if (!cb) {
11870    return this.emit('error', new Error('write callback called multiple times'));
11871  }
11872
11873  ts.writechunk = null;
11874  ts.writecb = null;
11875
11876  if (data != null) // single equals check for both `null` and `undefined`
11877    this.push(data);
11878
11879  cb(er);
11880
11881  var rs = this._readableState;
11882  rs.reading = false;
11883  if (rs.needReadable || rs.length < rs.highWaterMark) {
11884    this._read(rs.highWaterMark);
11885  }
11886}
11887
11888function Transform(options) {
11889  if (!(this instanceof Transform)) return new Transform(options);
11890
11891  Duplex.call(this, options);
11892
11893  this._transformState = {
11894    afterTransform: afterTransform.bind(this),
11895    needTransform: false,
11896    transforming: false,
11897    writecb: null,
11898    writechunk: null,
11899    writeencoding: null
11900  };
11901
11902  // start out asking for a readable event once data is transformed.
11903  this._readableState.needReadable = true;
11904
11905  // we have implemented the _read method, and done the other things
11906  // that Readable wants before the first _read call, so unset the
11907  // sync guard flag.
11908  this._readableState.sync = false;
11909
11910  if (options) {
11911    if (typeof options.transform === 'function') this._transform = options.transform;
11912
11913    if (typeof options.flush === 'function') this._flush = options.flush;
11914  }
11915
11916  // When the writable side finishes, then flush out anything remaining.
11917  this.on('prefinish', prefinish);
11918}
11919
11920function prefinish() {
11921  var _this = this;
11922
11923  if (typeof this._flush === 'function') {
11924    this._flush(function (er, data) {
11925      done(_this, er, data);
11926    });
11927  } else {
11928    done(this, null, null);
11929  }
11930}
11931
11932Transform.prototype.push = function (chunk, encoding) {
11933  this._transformState.needTransform = false;
11934  return Duplex.prototype.push.call(this, chunk, encoding);
11935};
11936
11937// This is the part where you do stuff!
11938// override this function in implementation classes.
11939// 'chunk' is an input chunk.
11940//
11941// Call `push(newChunk)` to pass along transformed output
11942// to the readable side.  You may call 'push' zero or more times.
11943//
11944// Call `cb(err)` when you are done with this chunk.  If you pass
11945// an error, then that'll put the hurt on the whole operation.  If you
11946// never call cb(), then you'll never get another chunk.
11947Transform.prototype._transform = function (chunk, encoding, cb) {
11948  throw new Error('_transform() is not implemented');
11949};
11950
11951Transform.prototype._write = function (chunk, encoding, cb) {
11952  var ts = this._transformState;
11953  ts.writecb = cb;
11954  ts.writechunk = chunk;
11955  ts.writeencoding = encoding;
11956  if (!ts.transforming) {
11957    var rs = this._readableState;
11958    if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
11959  }
11960};
11961
11962// Doesn't matter what the args are here.
11963// _transform does all the work.
11964// That we got here means that the readable side wants more data.
11965Transform.prototype._read = function (n) {
11966  var ts = this._transformState;
11967
11968  if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
11969    ts.transforming = true;
11970    this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
11971  } else {
11972    // mark that we need a transform, so that any data that comes in
11973    // will get processed, now that we've asked for it.
11974    ts.needTransform = true;
11975  }
11976};
11977
11978Transform.prototype._destroy = function (err, cb) {
11979  var _this2 = this;
11980
11981  Duplex.prototype._destroy.call(this, err, function (err2) {
11982    cb(err2);
11983    _this2.emit('close');
11984  });
11985};
11986
11987function done(stream, er, data) {
11988  if (er) return stream.emit('error', er);
11989
11990  if (data != null) // single equals check for both `null` and `undefined`
11991    stream.push(data);
11992
11993  // if there's nothing in the write buffer, then that means
11994  // that nothing more will ever be provided
11995  if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
11996
11997  if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
11998
11999  return stream.push(null);
12000}
12001},{"./_stream_duplex":53,"core-util-is":10,"inherits":29}],57:[function(require,module,exports){
12002(function (process,global,setImmediate){
12003// Copyright Joyent, Inc. and other Node contributors.
12004//
12005// Permission is hereby granted, free of charge, to any person obtaining a
12006// copy of this software and associated documentation files (the
12007// "Software"), to deal in the Software without restriction, including
12008// without limitation the rights to use, copy, modify, merge, publish,
12009// distribute, sublicense, and/or sell copies of the Software, and to permit
12010// persons to whom the Software is furnished to do so, subject to the
12011// following conditions:
12012//
12013// The above copyright notice and this permission notice shall be included
12014// in all copies or substantial portions of the Software.
12015//
12016// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12017// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12018// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12019// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12020// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12021// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12022// USE OR OTHER DEALINGS IN THE SOFTWARE.
12023
12024// A bit simpler than readable streams.
12025// Implement an async ._write(chunk, encoding, cb), and it'll handle all
12026// the drain event emission and buffering.
12027
12028'use strict';
12029
12030/*<replacement>*/
12031
12032var pna = require('process-nextick-args');
12033/*</replacement>*/
12034
12035module.exports = Writable;
12036
12037/* <replacement> */
12038function WriteReq(chunk, encoding, cb) {
12039  this.chunk = chunk;
12040  this.encoding = encoding;
12041  this.callback = cb;
12042  this.next = null;
12043}
12044
12045// It seems a linked list but it is not
12046// there will be only 2 of these for each stream
12047function CorkedRequest(state) {
12048  var _this = this;
12049
12050  this.next = null;
12051  this.entry = null;
12052  this.finish = function () {
12053    onCorkedFinish(_this, state);
12054  };
12055}
12056/* </replacement> */
12057
12058/*<replacement>*/
12059var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
12060/*</replacement>*/
12061
12062/*<replacement>*/
12063var Duplex;
12064/*</replacement>*/
12065
12066Writable.WritableState = WritableState;
12067
12068/*<replacement>*/
12069var util = Object.create(require('core-util-is'));
12070util.inherits = require('inherits');
12071/*</replacement>*/
12072
12073/*<replacement>*/
12074var internalUtil = {
12075  deprecate: require('util-deprecate')
12076};
12077/*</replacement>*/
12078
12079/*<replacement>*/
12080var Stream = require('./internal/streams/stream');
12081/*</replacement>*/
12082
12083/*<replacement>*/
12084
12085var Buffer = require('safe-buffer').Buffer;
12086var OurUint8Array = global.Uint8Array || function () {};
12087function _uint8ArrayToBuffer(chunk) {
12088  return Buffer.from(chunk);
12089}
12090function _isUint8Array(obj) {
12091  return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
12092}
12093
12094/*</replacement>*/
12095
12096var destroyImpl = require('./internal/streams/destroy');
12097
12098util.inherits(Writable, Stream);
12099
12100function nop() {}
12101
12102function WritableState(options, stream) {
12103  Duplex = Duplex || require('./_stream_duplex');
12104
12105  options = options || {};
12106
12107  // Duplex streams are both readable and writable, but share
12108  // the same options object.
12109  // However, some cases require setting options to different
12110  // values for the readable and the writable sides of the duplex stream.
12111  // These options can be provided separately as readableXXX and writableXXX.
12112  var isDuplex = stream instanceof Duplex;
12113
12114  // object stream flag to indicate whether or not this stream
12115  // contains buffers or objects.
12116  this.objectMode = !!options.objectMode;
12117
12118  if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
12119
12120  // the point at which write() starts returning false
12121  // Note: 0 is a valid value, means that we always return false if
12122  // the entire buffer is not flushed immediately on write()
12123  var hwm = options.highWaterMark;
12124  var writableHwm = options.writableHighWaterMark;
12125  var defaultHwm = this.objectMode ? 16 : 16 * 1024;
12126
12127  if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
12128
12129  // cast to ints.
12130  this.highWaterMark = Math.floor(this.highWaterMark);
12131
12132  // if _final has been called
12133  this.finalCalled = false;
12134
12135  // drain event flag.
12136  this.needDrain = false;
12137  // at the start of calling end()
12138  this.ending = false;
12139  // when end() has been called, and returned
12140  this.ended = false;
12141  // when 'finish' is emitted
12142  this.finished = false;
12143
12144  // has it been destroyed
12145  this.destroyed = false;
12146
12147  // should we decode strings into buffers before passing to _write?
12148  // this is here so that some node-core streams can optimize string
12149  // handling at a lower level.
12150  var noDecode = options.decodeStrings === false;
12151  this.decodeStrings = !noDecode;
12152
12153  // Crypto is kind of old and crusty.  Historically, its default string
12154  // encoding is 'binary' so we have to make this configurable.
12155  // Everything else in the universe uses 'utf8', though.
12156  this.defaultEncoding = options.defaultEncoding || 'utf8';
12157
12158  // not an actual buffer we keep track of, but a measurement
12159  // of how much we're waiting to get pushed to some underlying
12160  // socket or file.
12161  this.length = 0;
12162
12163  // a flag to see when we're in the middle of a write.
12164  this.writing = false;
12165
12166  // when true all writes will be buffered until .uncork() call
12167  this.corked = 0;
12168
12169  // a flag to be able to tell if the onwrite cb is called immediately,
12170  // or on a later tick.  We set this to true at first, because any
12171  // actions that shouldn't happen until "later" should generally also
12172  // not happen before the first write call.
12173  this.sync = true;
12174
12175  // a flag to know if we're processing previously buffered items, which
12176  // may call the _write() callback in the same tick, so that we don't
12177  // end up in an overlapped onwrite situation.
12178  this.bufferProcessing = false;
12179
12180  // the callback that's passed to _write(chunk,cb)
12181  this.onwrite = function (er) {
12182    onwrite(stream, er);
12183  };
12184
12185  // the callback that the user supplies to write(chunk,encoding,cb)
12186  this.writecb = null;
12187
12188  // the amount that is being written when _write is called.
12189  this.writelen = 0;
12190
12191  this.bufferedRequest = null;
12192  this.lastBufferedRequest = null;
12193
12194  // number of pending user-supplied write callbacks
12195  // this must be 0 before 'finish' can be emitted
12196  this.pendingcb = 0;
12197
12198  // emit prefinish if the only thing we're waiting for is _write cbs
12199  // This is relevant for synchronous Transform streams
12200  this.prefinished = false;
12201
12202  // True if the error was already emitted and should not be thrown again
12203  this.errorEmitted = false;
12204
12205  // count buffered requests
12206  this.bufferedRequestCount = 0;
12207
12208  // allocate the first CorkedRequest, there is always
12209  // one allocated and free to use, and we maintain at most two
12210  this.corkedRequestsFree = new CorkedRequest(this);
12211}
12212
12213WritableState.prototype.getBuffer = function getBuffer() {
12214  var current = this.bufferedRequest;
12215  var out = [];
12216  while (current) {
12217    out.push(current);
12218    current = current.next;
12219  }
12220  return out;
12221};
12222
12223(function () {
12224  try {
12225    Object.defineProperty(WritableState.prototype, 'buffer', {
12226      get: internalUtil.deprecate(function () {
12227        return this.getBuffer();
12228      }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
12229    });
12230  } catch (_) {}
12231})();
12232
12233// Test _writableState for inheritance to account for Duplex streams,
12234// whose prototype chain only points to Readable.
12235var realHasInstance;
12236if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
12237  realHasInstance = Function.prototype[Symbol.hasInstance];
12238  Object.defineProperty(Writable, Symbol.hasInstance, {
12239    value: function (object) {
12240      if (realHasInstance.call(this, object)) return true;
12241      if (this !== Writable) return false;
12242
12243      return object && object._writableState instanceof WritableState;
12244    }
12245  });
12246} else {
12247  realHasInstance = function (object) {
12248    return object instanceof this;
12249  };
12250}
12251
12252function Writable(options) {
12253  Duplex = Duplex || require('./_stream_duplex');
12254
12255  // Writable ctor is applied to Duplexes, too.
12256  // `realHasInstance` is necessary because using plain `instanceof`
12257  // would return false, as no `_writableState` property is attached.
12258
12259  // Trying to use the custom `instanceof` for Writable here will also break the
12260  // Node.js LazyTransform implementation, which has a non-trivial getter for
12261  // `_writableState` that would lead to infinite recursion.
12262  if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
12263    return new Writable(options);
12264  }
12265
12266  this._writableState = new WritableState(options, this);
12267
12268  // legacy.
12269  this.writable = true;
12270
12271  if (options) {
12272    if (typeof options.write === 'function') this._write = options.write;
12273
12274    if (typeof options.writev === 'function') this._writev = options.writev;
12275
12276    if (typeof options.destroy === 'function') this._destroy = options.destroy;
12277
12278    if (typeof options.final === 'function') this._final = options.final;
12279  }
12280
12281  Stream.call(this);
12282}
12283
12284// Otherwise people can pipe Writable streams, which is just wrong.
12285Writable.prototype.pipe = function () {
12286  this.emit('error', new Error('Cannot pipe, not readable'));
12287};
12288
12289function writeAfterEnd(stream, cb) {
12290  var er = new Error('write after end');
12291  // TODO: defer error events consistently everywhere, not just the cb
12292  stream.emit('error', er);
12293  pna.nextTick(cb, er);
12294}
12295
12296// Checks that a user-supplied chunk is valid, especially for the particular
12297// mode the stream is in. Currently this means that `null` is never accepted
12298// and undefined/non-string values are only allowed in object mode.
12299function validChunk(stream, state, chunk, cb) {
12300  var valid = true;
12301  var er = false;
12302
12303  if (chunk === null) {
12304    er = new TypeError('May not write null values to stream');
12305  } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
12306    er = new TypeError('Invalid non-string/buffer chunk');
12307  }
12308  if (er) {
12309    stream.emit('error', er);
12310    pna.nextTick(cb, er);
12311    valid = false;
12312  }
12313  return valid;
12314}
12315
12316Writable.prototype.write = function (chunk, encoding, cb) {
12317  var state = this._writableState;
12318  var ret = false;
12319  var isBuf = !state.objectMode && _isUint8Array(chunk);
12320
12321  if (isBuf && !Buffer.isBuffer(chunk)) {
12322    chunk = _uint8ArrayToBuffer(chunk);
12323  }
12324
12325  if (typeof encoding === 'function') {
12326    cb = encoding;
12327    encoding = null;
12328  }
12329
12330  if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
12331
12332  if (typeof cb !== 'function') cb = nop;
12333
12334  if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
12335    state.pendingcb++;
12336    ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
12337  }
12338
12339  return ret;
12340};
12341
12342Writable.prototype.cork = function () {
12343  var state = this._writableState;
12344
12345  state.corked++;
12346};
12347
12348Writable.prototype.uncork = function () {
12349  var state = this._writableState;
12350
12351  if (state.corked) {
12352    state.corked--;
12353
12354    if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
12355  }
12356};
12357
12358Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
12359  // node::ParseEncoding() requires lower case.
12360  if (typeof encoding === 'string') encoding = encoding.toLowerCase();
12361  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);
12362  this._writableState.defaultEncoding = encoding;
12363  return this;
12364};
12365
12366function decodeChunk(state, chunk, encoding) {
12367  if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
12368    chunk = Buffer.from(chunk, encoding);
12369  }
12370  return chunk;
12371}
12372
12373Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
12374  // making it explicit this property is not enumerable
12375  // because otherwise some prototype manipulation in
12376  // userland will fail
12377  enumerable: false,
12378  get: function () {
12379    return this._writableState.highWaterMark;
12380  }
12381});
12382
12383// if we're already writing something, then just put this
12384// in the queue, and wait our turn.  Otherwise, call _write
12385// If we return false, then we need a drain event, so set that flag.
12386function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
12387  if (!isBuf) {
12388    var newChunk = decodeChunk(state, chunk, encoding);
12389    if (chunk !== newChunk) {
12390      isBuf = true;
12391      encoding = 'buffer';
12392      chunk = newChunk;
12393    }
12394  }
12395  var len = state.objectMode ? 1 : chunk.length;
12396
12397  state.length += len;
12398
12399  var ret = state.length < state.highWaterMark;
12400  // we must ensure that previous needDrain will not be reset to false.
12401  if (!ret) state.needDrain = true;
12402
12403  if (state.writing || state.corked) {
12404    var last = state.lastBufferedRequest;
12405    state.lastBufferedRequest = {
12406      chunk: chunk,
12407      encoding: encoding,
12408      isBuf: isBuf,
12409      callback: cb,
12410      next: null
12411    };
12412    if (last) {
12413      last.next = state.lastBufferedRequest;
12414    } else {
12415      state.bufferedRequest = state.lastBufferedRequest;
12416    }
12417    state.bufferedRequestCount += 1;
12418  } else {
12419    doWrite(stream, state, false, len, chunk, encoding, cb);
12420  }
12421
12422  return ret;
12423}
12424
12425function doWrite(stream, state, writev, len, chunk, encoding, cb) {
12426  state.writelen = len;
12427  state.writecb = cb;
12428  state.writing = true;
12429  state.sync = true;
12430  if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
12431  state.sync = false;
12432}
12433
12434function onwriteError(stream, state, sync, er, cb) {
12435  --state.pendingcb;
12436
12437  if (sync) {
12438    // defer the callback if we are being called synchronously
12439    // to avoid piling up things on the stack
12440    pna.nextTick(cb, er);
12441    // this can emit finish, and it will always happen
12442    // after error
12443    pna.nextTick(finishMaybe, stream, state);
12444    stream._writableState.errorEmitted = true;
12445    stream.emit('error', er);
12446  } else {
12447    // the caller expect this to happen before if
12448    // it is async
12449    cb(er);
12450    stream._writableState.errorEmitted = true;
12451    stream.emit('error', er);
12452    // this can emit finish, but finish must
12453    // always follow error
12454    finishMaybe(stream, state);
12455  }
12456}
12457
12458function onwriteStateUpdate(state) {
12459  state.writing = false;
12460  state.writecb = null;
12461  state.length -= state.writelen;
12462  state.writelen = 0;
12463}
12464
12465function onwrite(stream, er) {
12466  var state = stream._writableState;
12467  var sync = state.sync;
12468  var cb = state.writecb;
12469
12470  onwriteStateUpdate(state);
12471
12472  if (er) onwriteError(stream, state, sync, er, cb);else {
12473    // Check if we're actually ready to finish, but don't emit yet
12474    var finished = needFinish(state);
12475
12476    if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
12477      clearBuffer(stream, state);
12478    }
12479
12480    if (sync) {
12481      /*<replacement>*/
12482      asyncWrite(afterWrite, stream, state, finished, cb);
12483      /*</replacement>*/
12484    } else {
12485      afterWrite(stream, state, finished, cb);
12486    }
12487  }
12488}
12489
12490function afterWrite(stream, state, finished, cb) {
12491  if (!finished) onwriteDrain(stream, state);
12492  state.pendingcb--;
12493  cb();
12494  finishMaybe(stream, state);
12495}
12496
12497// Must force callback to be called on nextTick, so that we don't
12498// emit 'drain' before the write() consumer gets the 'false' return
12499// value, and has a chance to attach a 'drain' listener.
12500function onwriteDrain(stream, state) {
12501  if (state.length === 0 && state.needDrain) {
12502    state.needDrain = false;
12503    stream.emit('drain');
12504  }
12505}
12506
12507// if there's something in the buffer waiting, then process it
12508function clearBuffer(stream, state) {
12509  state.bufferProcessing = true;
12510  var entry = state.bufferedRequest;
12511
12512  if (stream._writev && entry && entry.next) {
12513    // Fast case, write everything using _writev()
12514    var l = state.bufferedRequestCount;
12515    var buffer = new Array(l);
12516    var holder = state.corkedRequestsFree;
12517    holder.entry = entry;
12518
12519    var count = 0;
12520    var allBuffers = true;
12521    while (entry) {
12522      buffer[count] = entry;
12523      if (!entry.isBuf) allBuffers = false;
12524      entry = entry.next;
12525      count += 1;
12526    }
12527    buffer.allBuffers = allBuffers;
12528
12529    doWrite(stream, state, true, state.length, buffer, '', holder.finish);
12530
12531    // doWrite is almost always async, defer these to save a bit of time
12532    // as the hot path ends with doWrite
12533    state.pendingcb++;
12534    state.lastBufferedRequest = null;
12535    if (holder.next) {
12536      state.corkedRequestsFree = holder.next;
12537      holder.next = null;
12538    } else {
12539      state.corkedRequestsFree = new CorkedRequest(state);
12540    }
12541    state.bufferedRequestCount = 0;
12542  } else {
12543    // Slow case, write chunks one-by-one
12544    while (entry) {
12545      var chunk = entry.chunk;
12546      var encoding = entry.encoding;
12547      var cb = entry.callback;
12548      var len = state.objectMode ? 1 : chunk.length;
12549
12550      doWrite(stream, state, false, len, chunk, encoding, cb);
12551      entry = entry.next;
12552      state.bufferedRequestCount--;
12553      // if we didn't call the onwrite immediately, then
12554      // it means that we need to wait until it does.
12555      // also, that means that the chunk and cb are currently
12556      // being processed, so move the buffer counter past them.
12557      if (state.writing) {
12558        break;
12559      }
12560    }
12561
12562    if (entry === null) state.lastBufferedRequest = null;
12563  }
12564
12565  state.bufferedRequest = entry;
12566  state.bufferProcessing = false;
12567}
12568
12569Writable.prototype._write = function (chunk, encoding, cb) {
12570  cb(new Error('_write() is not implemented'));
12571};
12572
12573Writable.prototype._writev = null;
12574
12575Writable.prototype.end = function (chunk, encoding, cb) {
12576  var state = this._writableState;
12577
12578  if (typeof chunk === 'function') {
12579    cb = chunk;
12580    chunk = null;
12581    encoding = null;
12582  } else if (typeof encoding === 'function') {
12583    cb = encoding;
12584    encoding = null;
12585  }
12586
12587  if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
12588
12589  // .end() fully uncorks
12590  if (state.corked) {
12591    state.corked = 1;
12592    this.uncork();
12593  }
12594
12595  // ignore unnecessary end() calls.
12596  if (!state.ending && !state.finished) endWritable(this, state, cb);
12597};
12598
12599function needFinish(state) {
12600  return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
12601}
12602function callFinal(stream, state) {
12603  stream._final(function (err) {
12604    state.pendingcb--;
12605    if (err) {
12606      stream.emit('error', err);
12607    }
12608    state.prefinished = true;
12609    stream.emit('prefinish');
12610    finishMaybe(stream, state);
12611  });
12612}
12613function prefinish(stream, state) {
12614  if (!state.prefinished && !state.finalCalled) {
12615    if (typeof stream._final === 'function') {
12616      state.pendingcb++;
12617      state.finalCalled = true;
12618      pna.nextTick(callFinal, stream, state);
12619    } else {
12620      state.prefinished = true;
12621      stream.emit('prefinish');
12622    }
12623  }
12624}
12625
12626function finishMaybe(stream, state) {
12627  var need = needFinish(state);
12628  if (need) {
12629    prefinish(stream, state);
12630    if (state.pendingcb === 0) {
12631      state.finished = true;
12632      stream.emit('finish');
12633    }
12634  }
12635  return need;
12636}
12637
12638function endWritable(stream, state, cb) {
12639  state.ending = true;
12640  finishMaybe(stream, state);
12641  if (cb) {
12642    if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
12643  }
12644  state.ended = true;
12645  stream.writable = false;
12646}
12647
12648function onCorkedFinish(corkReq, state, err) {
12649  var entry = corkReq.entry;
12650  corkReq.entry = null;
12651  while (entry) {
12652    var cb = entry.callback;
12653    state.pendingcb--;
12654    cb(err);
12655    entry = entry.next;
12656  }
12657  if (state.corkedRequestsFree) {
12658    state.corkedRequestsFree.next = corkReq;
12659  } else {
12660    state.corkedRequestsFree = corkReq;
12661  }
12662}
12663
12664Object.defineProperty(Writable.prototype, 'destroyed', {
12665  get: function () {
12666    if (this._writableState === undefined) {
12667      return false;
12668    }
12669    return this._writableState.destroyed;
12670  },
12671  set: function (value) {
12672    // we ignore the value if the stream
12673    // has not been initialized yet
12674    if (!this._writableState) {
12675      return;
12676    }
12677
12678    // backward compatibility, the user is explicitly
12679    // managing destroyed
12680    this._writableState.destroyed = value;
12681  }
12682});
12683
12684Writable.prototype.destroy = destroyImpl.destroy;
12685Writable.prototype._undestroy = destroyImpl.undestroy;
12686Writable.prototype._destroy = function (err, cb) {
12687  this.end();
12688  cb(err);
12689};
12690}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
12691},{"./_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){
12692'use strict';
12693
12694function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
12695
12696var Buffer = require('safe-buffer').Buffer;
12697var util = require('util');
12698
12699function copyBuffer(src, target, offset) {
12700  src.copy(target, offset);
12701}
12702
12703module.exports = function () {
12704  function BufferList() {
12705    _classCallCheck(this, BufferList);
12706
12707    this.head = null;
12708    this.tail = null;
12709    this.length = 0;
12710  }
12711
12712  BufferList.prototype.push = function push(v) {
12713    var entry = { data: v, next: null };
12714    if (this.length > 0) this.tail.next = entry;else this.head = entry;
12715    this.tail = entry;
12716    ++this.length;
12717  };
12718
12719  BufferList.prototype.unshift = function unshift(v) {
12720    var entry = { data: v, next: this.head };
12721    if (this.length === 0) this.tail = entry;
12722    this.head = entry;
12723    ++this.length;
12724  };
12725
12726  BufferList.prototype.shift = function shift() {
12727    if (this.length === 0) return;
12728    var ret = this.head.data;
12729    if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
12730    --this.length;
12731    return ret;
12732  };
12733
12734  BufferList.prototype.clear = function clear() {
12735    this.head = this.tail = null;
12736    this.length = 0;
12737  };
12738
12739  BufferList.prototype.join = function join(s) {
12740    if (this.length === 0) return '';
12741    var p = this.head;
12742    var ret = '' + p.data;
12743    while (p = p.next) {
12744      ret += s + p.data;
12745    }return ret;
12746  };
12747
12748  BufferList.prototype.concat = function concat(n) {
12749    if (this.length === 0) return Buffer.alloc(0);
12750    if (this.length === 1) return this.head.data;
12751    var ret = Buffer.allocUnsafe(n >>> 0);
12752    var p = this.head;
12753    var i = 0;
12754    while (p) {
12755      copyBuffer(p.data, ret, i);
12756      i += p.data.length;
12757      p = p.next;
12758    }
12759    return ret;
12760  };
12761
12762  return BufferList;
12763}();
12764
12765if (util && util.inspect && util.inspect.custom) {
12766  module.exports.prototype[util.inspect.custom] = function () {
12767    var obj = util.inspect({ length: this.length });
12768    return this.constructor.name + ' ' + obj;
12769  };
12770}
12771},{"safe-buffer":40,"util":7}],59:[function(require,module,exports){
12772'use strict';
12773
12774/*<replacement>*/
12775
12776var pna = require('process-nextick-args');
12777/*</replacement>*/
12778
12779// undocumented cb() API, needed for core, not for public API
12780function destroy(err, cb) {
12781  var _this = this;
12782
12783  var readableDestroyed = this._readableState && this._readableState.destroyed;
12784  var writableDestroyed = this._writableState && this._writableState.destroyed;
12785
12786  if (readableDestroyed || writableDestroyed) {
12787    if (cb) {
12788      cb(err);
12789    } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
12790      pna.nextTick(emitErrorNT, this, err);
12791    }
12792    return this;
12793  }
12794
12795  // we set destroyed to true before firing error callbacks in order
12796  // to make it re-entrance safe in case destroy() is called within callbacks
12797
12798  if (this._readableState) {
12799    this._readableState.destroyed = true;
12800  }
12801
12802  // if this is a duplex stream mark the writable part as destroyed as well
12803  if (this._writableState) {
12804    this._writableState.destroyed = true;
12805  }
12806
12807  this._destroy(err || null, function (err) {
12808    if (!cb && err) {
12809      pna.nextTick(emitErrorNT, _this, err);
12810      if (_this._writableState) {
12811        _this._writableState.errorEmitted = true;
12812      }
12813    } else if (cb) {
12814      cb(err);
12815    }
12816  });
12817
12818  return this;
12819}
12820
12821function undestroy() {
12822  if (this._readableState) {
12823    this._readableState.destroyed = false;
12824    this._readableState.reading = false;
12825    this._readableState.ended = false;
12826    this._readableState.endEmitted = false;
12827  }
12828
12829  if (this._writableState) {
12830    this._writableState.destroyed = false;
12831    this._writableState.ended = false;
12832    this._writableState.ending = false;
12833    this._writableState.finished = false;
12834    this._writableState.errorEmitted = false;
12835  }
12836}
12837
12838function emitErrorNT(self, err) {
12839  self.emit('error', err);
12840}
12841
12842module.exports = {
12843  destroy: destroy,
12844  undestroy: undestroy
12845};
12846},{"process-nextick-args":39}],60:[function(require,module,exports){
12847module.exports = require('events').EventEmitter;
12848
12849},{"events":11}],61:[function(require,module,exports){
12850module.exports = require('./readable').PassThrough
12851
12852},{"./readable":62}],62:[function(require,module,exports){
12853exports = module.exports = require('./lib/_stream_readable.js');
12854exports.Stream = exports;
12855exports.Readable = exports;
12856exports.Writable = require('./lib/_stream_writable.js');
12857exports.Duplex = require('./lib/_stream_duplex.js');
12858exports.Transform = require('./lib/_stream_transform.js');
12859exports.PassThrough = require('./lib/_stream_passthrough.js');
12860
12861},{"./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){
12862module.exports = require('./readable').Transform
12863
12864},{"./readable":62}],64:[function(require,module,exports){
12865module.exports = require('./lib/_stream_writable.js');
12866
12867},{"./lib/_stream_writable.js":57}],65:[function(require,module,exports){
12868// Copyright Joyent, Inc. and other Node contributors.
12869//
12870// Permission is hereby granted, free of charge, to any person obtaining a
12871// copy of this software and associated documentation files (the
12872// "Software"), to deal in the Software without restriction, including
12873// without limitation the rights to use, copy, modify, merge, publish,
12874// distribute, sublicense, and/or sell copies of the Software, and to permit
12875// persons to whom the Software is furnished to do so, subject to the
12876// following conditions:
12877//
12878// The above copyright notice and this permission notice shall be included
12879// in all copies or substantial portions of the Software.
12880//
12881// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
12882// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
12883// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
12884// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
12885// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
12886// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
12887// USE OR OTHER DEALINGS IN THE SOFTWARE.
12888
12889'use strict';
12890
12891/*<replacement>*/
12892
12893var Buffer = require('safe-buffer').Buffer;
12894/*</replacement>*/
12895
12896var isEncoding = Buffer.isEncoding || function (encoding) {
12897  encoding = '' + encoding;
12898  switch (encoding && encoding.toLowerCase()) {
12899    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':
12900      return true;
12901    default:
12902      return false;
12903  }
12904};
12905
12906function _normalizeEncoding(enc) {
12907  if (!enc) return 'utf8';
12908  var retried;
12909  while (true) {
12910    switch (enc) {
12911      case 'utf8':
12912      case 'utf-8':
12913        return 'utf8';
12914      case 'ucs2':
12915      case 'ucs-2':
12916      case 'utf16le':
12917      case 'utf-16le':
12918        return 'utf16le';
12919      case 'latin1':
12920      case 'binary':
12921        return 'latin1';
12922      case 'base64':
12923      case 'ascii':
12924      case 'hex':
12925        return enc;
12926      default:
12927        if (retried) return; // undefined
12928        enc = ('' + enc).toLowerCase();
12929        retried = true;
12930    }
12931  }
12932};
12933
12934// Do not cache `Buffer.isEncoding` when checking encoding names as some
12935// modules monkey-patch it to support additional encodings
12936function normalizeEncoding(enc) {
12937  var nenc = _normalizeEncoding(enc);
12938  if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
12939  return nenc || enc;
12940}
12941
12942// StringDecoder provides an interface for efficiently splitting a series of
12943// buffers into a series of JS strings without breaking apart multi-byte
12944// characters.
12945exports.StringDecoder = StringDecoder;
12946function StringDecoder(encoding) {
12947  this.encoding = normalizeEncoding(encoding);
12948  var nb;
12949  switch (this.encoding) {
12950    case 'utf16le':
12951      this.text = utf16Text;
12952      this.end = utf16End;
12953      nb = 4;
12954      break;
12955    case 'utf8':
12956      this.fillLast = utf8FillLast;
12957      nb = 4;
12958      break;
12959    case 'base64':
12960      this.text = base64Text;
12961      this.end = base64End;
12962      nb = 3;
12963      break;
12964    default:
12965      this.write = simpleWrite;
12966      this.end = simpleEnd;
12967      return;
12968  }
12969  this.lastNeed = 0;
12970  this.lastTotal = 0;
12971  this.lastChar = Buffer.allocUnsafe(nb);
12972}
12973
12974StringDecoder.prototype.write = function (buf) {
12975  if (buf.length === 0) return '';
12976  var r;
12977  var i;
12978  if (this.lastNeed) {
12979    r = this.fillLast(buf);
12980    if (r === undefined) return '';
12981    i = this.lastNeed;
12982    this.lastNeed = 0;
12983  } else {
12984    i = 0;
12985  }
12986  if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
12987  return r || '';
12988};
12989
12990StringDecoder.prototype.end = utf8End;
12991
12992// Returns only complete characters in a Buffer
12993StringDecoder.prototype.text = utf8Text;
12994
12995// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
12996StringDecoder.prototype.fillLast = function (buf) {
12997  if (this.lastNeed <= buf.length) {
12998    buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
12999    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
13000  }
13001  buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
13002  this.lastNeed -= buf.length;
13003};
13004
13005// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
13006// continuation byte. If an invalid byte is detected, -2 is returned.
13007function utf8CheckByte(byte) {
13008  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;
13009  return byte >> 6 === 0x02 ? -1 : -2;
13010}
13011
13012// Checks at most 3 bytes at the end of a Buffer in order to detect an
13013// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
13014// needed to complete the UTF-8 character (if applicable) are returned.
13015function utf8CheckIncomplete(self, buf, i) {
13016  var j = buf.length - 1;
13017  if (j < i) return 0;
13018  var nb = utf8CheckByte(buf[j]);
13019  if (nb >= 0) {
13020    if (nb > 0) self.lastNeed = nb - 1;
13021    return nb;
13022  }
13023  if (--j < i || nb === -2) return 0;
13024  nb = utf8CheckByte(buf[j]);
13025  if (nb >= 0) {
13026    if (nb > 0) self.lastNeed = nb - 2;
13027    return nb;
13028  }
13029  if (--j < i || nb === -2) return 0;
13030  nb = utf8CheckByte(buf[j]);
13031  if (nb >= 0) {
13032    if (nb > 0) {
13033      if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
13034    }
13035    return nb;
13036  }
13037  return 0;
13038}
13039
13040// Validates as many continuation bytes for a multi-byte UTF-8 character as
13041// needed or are available. If we see a non-continuation byte where we expect
13042// one, we "replace" the validated continuation bytes we've seen so far with
13043// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
13044// behavior. The continuation byte check is included three times in the case
13045// where all of the continuation bytes for a character exist in the same buffer.
13046// It is also done this way as a slight performance increase instead of using a
13047// loop.
13048function utf8CheckExtraBytes(self, buf, p) {
13049  if ((buf[0] & 0xC0) !== 0x80) {
13050    self.lastNeed = 0;
13051    return '\ufffd';
13052  }
13053  if (self.lastNeed > 1 && buf.length > 1) {
13054    if ((buf[1] & 0xC0) !== 0x80) {
13055      self.lastNeed = 1;
13056      return '\ufffd';
13057    }
13058    if (self.lastNeed > 2 && buf.length > 2) {
13059      if ((buf[2] & 0xC0) !== 0x80) {
13060        self.lastNeed = 2;
13061        return '\ufffd';
13062      }
13063    }
13064  }
13065}
13066
13067// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
13068function utf8FillLast(buf) {
13069  var p = this.lastTotal - this.lastNeed;
13070  var r = utf8CheckExtraBytes(this, buf, p);
13071  if (r !== undefined) return r;
13072  if (this.lastNeed <= buf.length) {
13073    buf.copy(this.lastChar, p, 0, this.lastNeed);
13074    return this.lastChar.toString(this.encoding, 0, this.lastTotal);
13075  }
13076  buf.copy(this.lastChar, p, 0, buf.length);
13077  this.lastNeed -= buf.length;
13078}
13079
13080// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
13081// partial character, the character's bytes are buffered until the required
13082// number of bytes are available.
13083function utf8Text(buf, i) {
13084  var total = utf8CheckIncomplete(this, buf, i);
13085  if (!this.lastNeed) return buf.toString('utf8', i);
13086  this.lastTotal = total;
13087  var end = buf.length - (total - this.lastNeed);
13088  buf.copy(this.lastChar, 0, end);
13089  return buf.toString('utf8', i, end);
13090}
13091
13092// For UTF-8, a replacement character is added when ending on a partial
13093// character.
13094function utf8End(buf) {
13095  var r = buf && buf.length ? this.write(buf) : '';
13096  if (this.lastNeed) return r + '\ufffd';
13097  return r;
13098}
13099
13100// UTF-16LE typically needs two bytes per character, but even if we have an even
13101// number of bytes available, we need to check if we end on a leading/high
13102// surrogate. In that case, we need to wait for the next two bytes in order to
13103// decode the last character properly.
13104function utf16Text(buf, i) {
13105  if ((buf.length - i) % 2 === 0) {
13106    var r = buf.toString('utf16le', i);
13107    if (r) {
13108      var c = r.charCodeAt(r.length - 1);
13109      if (c >= 0xD800 && c <= 0xDBFF) {
13110        this.lastNeed = 2;
13111        this.lastTotal = 4;
13112        this.lastChar[0] = buf[buf.length - 2];
13113        this.lastChar[1] = buf[buf.length - 1];
13114        return r.slice(0, -1);
13115      }
13116    }
13117    return r;
13118  }
13119  this.lastNeed = 1;
13120  this.lastTotal = 2;
13121  this.lastChar[0] = buf[buf.length - 1];
13122  return buf.toString('utf16le', i, buf.length - 1);
13123}
13124
13125// For UTF-16LE we do not explicitly append special replacement characters if we
13126// end on a partial character, we simply let v8 handle that.
13127function utf16End(buf) {
13128  var r = buf && buf.length ? this.write(buf) : '';
13129  if (this.lastNeed) {
13130    var end = this.lastTotal - this.lastNeed;
13131    return r + this.lastChar.toString('utf16le', 0, end);
13132  }
13133  return r;
13134}
13135
13136function base64Text(buf, i) {
13137  var n = (buf.length - i) % 3;
13138  if (n === 0) return buf.toString('base64', i);
13139  this.lastNeed = 3 - n;
13140  this.lastTotal = 3;
13141  if (n === 1) {
13142    this.lastChar[0] = buf[buf.length - 1];
13143  } else {
13144    this.lastChar[0] = buf[buf.length - 2];
13145    this.lastChar[1] = buf[buf.length - 1];
13146  }
13147  return buf.toString('base64', i, buf.length - n);
13148}
13149
13150function base64End(buf) {
13151  var r = buf && buf.length ? this.write(buf) : '';
13152  if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
13153  return r;
13154}
13155
13156// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
13157function simpleWrite(buf) {
13158  return buf.toString(this.encoding);
13159}
13160
13161function simpleEnd(buf) {
13162  return buf && buf.length ? this.write(buf) : '';
13163}
13164},{"safe-buffer":40}],66:[function(require,module,exports){
13165(function (setImmediate,clearImmediate){
13166var nextTick = require('process/browser.js').nextTick;
13167var apply = Function.prototype.apply;
13168var slice = Array.prototype.slice;
13169var immediateIds = {};
13170var nextImmediateId = 0;
13171
13172// DOM APIs, for completeness
13173
13174exports.setTimeout = function() {
13175  return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
13176};
13177exports.setInterval = function() {
13178  return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
13179};
13180exports.clearTimeout =
13181exports.clearInterval = function(timeout) { timeout.close(); };
13182
13183function Timeout(id, clearFn) {
13184  this._id = id;
13185  this._clearFn = clearFn;
13186}
13187Timeout.prototype.unref = Timeout.prototype.ref = function() {};
13188Timeout.prototype.close = function() {
13189  this._clearFn.call(window, this._id);
13190};
13191
13192// Does not start the time, just sets up the members needed.
13193exports.enroll = function(item, msecs) {
13194  clearTimeout(item._idleTimeoutId);
13195  item._idleTimeout = msecs;
13196};
13197
13198exports.unenroll = function(item) {
13199  clearTimeout(item._idleTimeoutId);
13200  item._idleTimeout = -1;
13201};
13202
13203exports._unrefActive = exports.active = function(item) {
13204  clearTimeout(item._idleTimeoutId);
13205
13206  var msecs = item._idleTimeout;
13207  if (msecs >= 0) {
13208    item._idleTimeoutId = setTimeout(function onTimeout() {
13209      if (item._onTimeout)
13210        item._onTimeout();
13211    }, msecs);
13212  }
13213};
13214
13215// That's not how node.js implements it but the exposed api is the same.
13216exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
13217  var id = nextImmediateId++;
13218  var args = arguments.length < 2 ? false : slice.call(arguments, 1);
13219
13220  immediateIds[id] = true;
13221
13222  nextTick(function onNextTick() {
13223    if (immediateIds[id]) {
13224      // fn.call() is faster so we optimize for the common use-case
13225      // @see http://jsperf.com/call-apply-segu
13226      if (args) {
13227        fn.apply(null, args);
13228      } else {
13229        fn.call(null);
13230      }
13231      // Prevent ids from leaking
13232      exports.clearImmediate(id);
13233    }
13234  });
13235
13236  return id;
13237};
13238
13239exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
13240  delete immediateIds[id];
13241};
13242}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
13243},{"process/browser.js":67,"timers":66}],67:[function(require,module,exports){
13244arguments[4][9][0].apply(exports,arguments)
13245},{"dup":9}],68:[function(require,module,exports){
13246(function (global){
13247
13248/**
13249 * Module exports.
13250 */
13251
13252module.exports = deprecate;
13253
13254/**
13255 * Mark that a method should not be used.
13256 * Returns a modified function which warns once by default.
13257 *
13258 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
13259 *
13260 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
13261 * will throw an Error when invoked.
13262 *
13263 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
13264 * will invoke `console.trace()` instead of `console.error()`.
13265 *
13266 * @param {Function} fn - the function to deprecate
13267 * @param {String} msg - the string to print to the console when `fn` is invoked
13268 * @returns {Function} a new "deprecated" version of `fn`
13269 * @api public
13270 */
13271
13272function deprecate (fn, msg) {
13273  if (config('noDeprecation')) {
13274    return fn;
13275  }
13276
13277  var warned = false;
13278  function deprecated() {
13279    if (!warned) {
13280      if (config('throwDeprecation')) {
13281        throw new Error(msg);
13282      } else if (config('traceDeprecation')) {
13283        console.trace(msg);
13284      } else {
13285        console.warn(msg);
13286      }
13287      warned = true;
13288    }
13289    return fn.apply(this, arguments);
13290  }
13291
13292  return deprecated;
13293}
13294
13295/**
13296 * Checks `localStorage` for boolean values for the given `name`.
13297 *
13298 * @param {String} name
13299 * @returns {Boolean}
13300 * @api private
13301 */
13302
13303function config (name) {
13304  // accessing global.localStorage can trigger a DOMException in sandboxed iframes
13305  try {
13306    if (!global.localStorage) return false;
13307  } catch (_) {
13308    return false;
13309  }
13310  var val = global.localStorage[name];
13311  if (null == val) return false;
13312  return String(val).toLowerCase() === 'true';
13313}
13314
13315}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
13316},{}]},{},[41])(41)
13317});