Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save intelliot/cc4628e7b81d1527be690dcdac6bf7f9 to your computer and use it in GitHub Desktop.
Save intelliot/cc4628e7b81d1527be690dcdac6bf7f9 to your computer and use it in GitHub Desktop.
ripple-lib-browser-client - bundle.js
This file has been truncated, but you can view the full file.
(function(){function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s}return e})()({1:[function(require,module,exports){
const RippleAPI = require('ripple-lib').RippleAPI;
let api = new RippleAPI({
server: 'wss://s1.ripple.com:443'
});
api.connect().then(() => {
api.getServerInfo().then(info => {
document.body.innerHTML = JSON.stringify(info);
api.disconnect();
});
});
},{"ripple-lib":2}],2:[function(require,module,exports){
var ripple =
/******/ (function(modules) { // webpackBootstrap
/******/ // The module cache
/******/ var installedModules = {};
/******/
/******/ // The require function
/******/ function __webpack_require__(moduleId) {
/******/
/******/ // Check if module is in cache
/******/ if(installedModules[moduleId]) {
/******/ return installedModules[moduleId].exports;
/******/ }
/******/ // Create a new module (and put it into the cache)
/******/ var module = installedModules[moduleId] = {
/******/ i: moduleId,
/******/ l: false,
/******/ exports: {}
/******/ };
/******/
/******/ // Execute the module function
/******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/ // Flag the module as loaded
/******/ module.l = true;
/******/
/******/ // Return the exports of the module
/******/ return module.exports;
/******/ }
/******/
/******/
/******/ // expose the modules object (__webpack_modules__)
/******/ __webpack_require__.m = modules;
/******/
/******/ // expose the module cache
/******/ __webpack_require__.c = installedModules;
/******/
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, {
/******/ configurable: false,
/******/ enumerable: true,
/******/ get: getter
/******/ });
/******/ }
/******/ };
/******/
/******/ // getDefaultExport function for compatibility with non-harmony modules
/******/ __webpack_require__.n = function(module) {
/******/ var getter = module && module.__esModule ?
/******/ function getDefault() { return module['default']; } :
/******/ function getModuleExports() { return module; };
/******/ __webpack_require__.d(getter, 'a', getter);
/******/ return getter;
/******/ };
/******/
/******/ // Object.prototype.hasOwnProperty.call
/******/ __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/ // __webpack_public_path__
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
/******/ return __webpack_require__(__webpack_require__.s = 98);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const constants = __webpack_require__(99);
exports.constants = constants;
const errors = __webpack_require__(39);
exports.errors = errors;
const validate = __webpack_require__(103);
exports.validate = validate;
const serverInfo = __webpack_require__(244);
exports.serverInfo = serverInfo;
var utils_1 = __webpack_require__(46);
exports.dropsToXrp = utils_1.dropsToXrp;
exports.xrpToDrops = utils_1.xrpToDrops;
exports.toRippledAmount = utils_1.toRippledAmount;
exports.removeUndefined = utils_1.removeUndefined;
exports.convertKeysFromSnakeCaseToCamelCase = utils_1.convertKeysFromSnakeCaseToCamelCase;
exports.iso8601ToRippleTime = utils_1.iso8601ToRippleTime;
exports.rippleTimeToISO8601 = utils_1.rippleTimeToISO8601;
var connection_1 = __webpack_require__(245);
exports.Connection = connection_1.default;
var txflags_1 = __webpack_require__(57);
exports.txFlags = txflags_1.txFlags;
/***/ }),
/* 1 */
/***/ (function(module, exports) {
module.exports = _;
/***/ }),
/* 2 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {
// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
// original notice:
/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
function compare(a, b) {
if (a === b) {
return 0;
}
var x = a.length;
var y = b.length;
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i];
y = b[i];
break;
}
}
if (x < y) {
return -1;
}
if (y < x) {
return 1;
}
return 0;
}
function isBuffer(b) {
if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
return global.Buffer.isBuffer(b);
}
return !!(b != null && b._isBuffer);
}
// based on node assert, original notice:
// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
//
// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
//
// Originally from narwhal.js (http://narwhaljs.org)
// Copyright (c) 2009 Thomas Robinson <280north.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the 'Software'), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
var util = __webpack_require__(26);
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
return function foo() {}.name === 'foo';
}());
function pToString (obj) {
return Object.prototype.toString.call(obj);
}
function isView(arrbuf) {
if (isBuffer(arrbuf)) {
return false;
}
if (typeof global.ArrayBuffer !== 'function') {
return false;
}
if (typeof ArrayBuffer.isView === 'function') {
return ArrayBuffer.isView(arrbuf);
}
if (!arrbuf) {
return false;
}
if (arrbuf instanceof DataView) {
return true;
}
if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
return true;
}
return false;
}
// 1. The assert module provides functions that throw
// AssertionError's when particular conditions are not met. The
// assert module must conform to the following interface.
var assert = module.exports = ok;
// 2. The AssertionError is defined in assert.
// new assert.AssertionError({ message: message,
// actual: actual,
// expected: expected })
var regex = /\s*function\s+([^\(\s]*)\s*/;
// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
function getName(func) {
if (!util.isFunction(func)) {
return;
}
if (functionsHaveNames) {
return func.name;
}
var str = func.toString();
var match = str.match(regex);
return match && match[1];
}
assert.AssertionError = function AssertionError(options) {
this.name = 'AssertionError';
this.actual = options.actual;
this.expected = options.expected;
this.operator = options.operator;
if (options.message) {
this.message = options.message;
this.generatedMessage = false;
} else {
this.message = getMessage(this);
this.generatedMessage = true;
}
var stackStartFunction = options.stackStartFunction || fail;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, stackStartFunction);
} else {
// non v8 browsers so we can have a stacktrace
var err = new Error();
if (err.stack) {
var out = err.stack;
// try to strip useless frames
var fn_name = getName(stackStartFunction);
var idx = out.indexOf('\n' + fn_name);
if (idx >= 0) {
// once we have located the function frame
// we need to strip out everything before it (and its line)
var next_line = out.indexOf('\n', idx + 1);
out = out.substring(next_line + 1);
}
this.stack = out;
}
}
};
// assert.AssertionError instanceof Error
util.inherits(assert.AssertionError, Error);
function truncate(s, n) {
if (typeof s === 'string') {
return s.length < n ? s : s.slice(0, n);
} else {
return s;
}
}
function inspect(something) {
if (functionsHaveNames || !util.isFunction(something)) {
return util.inspect(something);
}
var rawname = getName(something);
var name = rawname ? ': ' + rawname : '';
return '[Function' + name + ']';
}
function getMessage(self) {
return truncate(inspect(self.actual), 128) + ' ' +
self.operator + ' ' +
truncate(inspect(self.expected), 128);
}
// At present only the three keys mentioned above are used and
// understood by the spec. Implementations or sub modules can pass
// other keys to the AssertionError's constructor - they will be
// ignored.
// 3. All of the following functions must throw an AssertionError
// when a corresponding condition is not met, with a message that
// may be undefined if not provided. All assertion methods provide
// both the actual and expected values to the assertion error for
// display purposes.
function fail(actual, expected, message, operator, stackStartFunction) {
throw new assert.AssertionError({
message: message,
actual: actual,
expected: expected,
operator: operator,
stackStartFunction: stackStartFunction
});
}
// EXTENSION! allows for well behaved errors defined elsewhere.
assert.fail = fail;
// 4. Pure assertion tests whether a value is truthy, as determined
// by !!guard.
// assert.ok(guard, message_opt);
// This statement is equivalent to assert.equal(true, !!guard,
// message_opt);. To test strictly for the value true, use
// assert.strictEqual(true, guard, message_opt);.
function ok(value, message) {
if (!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
// 5. The equality assertion tests shallow, coercive equality with
// ==.
// assert.equal(actual, expected, message_opt);
assert.equal = function equal(actual, expected, message) {
if (actual != expected) fail(actual, expected, message, '==', assert.equal);
};
// 6. The non-equality assertion tests for whether two objects are not equal
// with != assert.notEqual(actual, expected, message_opt);
assert.notEqual = function notEqual(actual, expected, message) {
if (actual == expected) {
fail(actual, expected, message, '!=', assert.notEqual);
}
};
// 7. The equivalence assertion tests a deep equality relation.
// assert.deepEqual(actual, expected, message_opt);
assert.deepEqual = function deepEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'deepEqual', assert.deepEqual);
}
};
assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
if (!_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
}
};
function _deepEqual(actual, expected, strict, memos) {
// 7.1. All identical values are equivalent, as determined by ===.
if (actual === expected) {
return true;
} else if (isBuffer(actual) && isBuffer(expected)) {
return compare(actual, expected) === 0;
// 7.2. If the expected value is a Date object, the actual value is
// equivalent if it is also a Date object that refers to the same time.
} else if (util.isDate(actual) && util.isDate(expected)) {
return actual.getTime() === expected.getTime();
// 7.3 If the expected value is a RegExp object, the actual value is
// equivalent if it is also a RegExp object with the same source and
// properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
} else if (util.isRegExp(actual) && util.isRegExp(expected)) {
return actual.source === expected.source &&
actual.global === expected.global &&
actual.multiline === expected.multiline &&
actual.lastIndex === expected.lastIndex &&
actual.ignoreCase === expected.ignoreCase;
// 7.4. Other pairs that do not both pass typeof value == 'object',
// equivalence is determined by ==.
} else if ((actual === null || typeof actual !== 'object') &&
(expected === null || typeof expected !== 'object')) {
return strict ? actual === expected : actual == expected;
// If both values are instances of typed arrays, wrap their underlying
// ArrayBuffers in a Buffer each to increase performance
// This optimization requires the arrays to have the same type as checked by
// Object.prototype.toString (aka pToString). Never perform binary
// comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
// bit patterns are not identical.
} else if (isView(actual) && isView(expected) &&
pToString(actual) === pToString(expected) &&
!(actual instanceof Float32Array ||
actual instanceof Float64Array)) {
return compare(new Uint8Array(actual.buffer),
new Uint8Array(expected.buffer)) === 0;
// 7.5 For all other Object pairs, including Array objects, equivalence is
// determined by having the same number of owned properties (as verified
// with Object.prototype.hasOwnProperty.call), the same set of keys
// (although not necessarily the same order), equivalent values for every
// corresponding key, and an identical 'prototype' property. Note: this
// accounts for both named and indexed properties on Arrays.
} else if (isBuffer(actual) !== isBuffer(expected)) {
return false;
} else {
memos = memos || {actual: [], expected: []};
var actualIndex = memos.actual.indexOf(actual);
if (actualIndex !== -1) {
if (actualIndex === memos.expected.indexOf(expected)) {
return true;
}
}
memos.actual.push(actual);
memos.expected.push(expected);
return objEquiv(actual, expected, strict, memos);
}
}
function isArguments(object) {
return Object.prototype.toString.call(object) == '[object Arguments]';
}
function objEquiv(a, b, strict, actualVisitedObjects) {
if (a === null || a === undefined || b === null || b === undefined)
return false;
// if one is a primitive, the other must be same
if (util.isPrimitive(a) || util.isPrimitive(b))
return a === b;
if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
return false;
var aIsArgs = isArguments(a);
var bIsArgs = isArguments(b);
if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
return false;
if (aIsArgs) {
a = pSlice.call(a);
b = pSlice.call(b);
return _deepEqual(a, b, strict);
}
var ka = objectKeys(a);
var kb = objectKeys(b);
var key, i;
// having the same number of owned properties (keys incorporates
// hasOwnProperty)
if (ka.length !== kb.length)
return false;
//the same set of keys (although not necessarily the same order),
ka.sort();
kb.sort();
//~~~cheap key test
for (i = ka.length - 1; i >= 0; i--) {
if (ka[i] !== kb[i])
return false;
}
//equivalent values for every corresponding key, and
//~~~possibly expensive deep test
for (i = ka.length - 1; i >= 0; i--) {
key = ka[i];
if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
return false;
}
return true;
}
// 8. The non-equivalence assertion tests for any deep inequality.
// assert.notDeepEqual(actual, expected, message_opt);
assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
if (_deepEqual(actual, expected, false)) {
fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
}
};
assert.notDeepStrictEqual = notDeepStrictEqual;
function notDeepStrictEqual(actual, expected, message) {
if (_deepEqual(actual, expected, true)) {
fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
}
}
// 9. The strict equality assertion tests strict equality, as determined by ===.
// assert.strictEqual(actual, expected, message_opt);
assert.strictEqual = function strictEqual(actual, expected, message) {
if (actual !== expected) {
fail(actual, expected, message, '===', assert.strictEqual);
}
};
// 10. The strict non-equality assertion tests for strict inequality, as
// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
if (actual === expected) {
fail(actual, expected, message, '!==', assert.notStrictEqual);
}
};
function expectedException(actual, expected) {
if (!actual || !expected) {
return false;
}
if (Object.prototype.toString.call(expected) == '[object RegExp]') {
return expected.test(actual);
}
try {
if (actual instanceof expected) {
return true;
}
} catch (e) {
// Ignore. The instanceof check doesn't work for arrow functions.
}
if (Error.isPrototypeOf(expected)) {
return false;
}
return expected.call({}, actual) === true;
}
function _tryBlock(block) {
var error;
try {
block();
} catch (e) {
error = e;
}
return error;
}
function _throws(shouldThrow, block, expected, message) {
var actual;
if (typeof block !== 'function') {
throw new TypeError('"block" argument must be a function');
}
if (typeof expected === 'string') {
message = expected;
expected = null;
}
actual = _tryBlock(block);
message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
(message ? ' ' + message : '.');
if (shouldThrow && !actual) {
fail(actual, expected, 'Missing expected exception' + message);
}
var userProvidedMessage = typeof message === 'string';
var isUnwantedException = !shouldThrow && util.isError(actual);
var isUnexpectedException = !shouldThrow && actual && !expected;
if ((isUnwantedException &&
userProvidedMessage &&
expectedException(actual, expected)) ||
isUnexpectedException) {
fail(actual, expected, 'Got unwanted exception' + message);
}
if ((shouldThrow && actual && expected &&
!expectedException(actual, expected)) || (!shouldThrow && actual)) {
throw actual;
}
}
// 11. Expected to throw an error:
// assert.throws(block, Error_opt, message_opt);
assert.throws = function(block, /*optional*/error, /*optional*/message) {
_throws(true, block, error, message);
};
// EXTENSION! This is annoying to write outside this module.
assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
_throws(false, block, error, message);
};
assert.ifError = function(err) { if (err) throw err; };
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
if (hasOwn.call(obj, key)) keys.push(key);
}
return keys;
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ }),
/* 3 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 4 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _ = __webpack_require__(1);
var inherits = __webpack_require__(3);
function forEach(obj, func) {
Object.keys(obj || {}).forEach(function (k) {
func(obj[k], k);});}
function ensureArray(val) {
return Array.isArray(val) ? val : [val];}
module.exports = function makeClass(klass_, definition_) {
var definition = definition_ || klass_;
var klass = typeof klass_ === 'function' ? klass_ : null;
if (klass === null) {
for (var k in definition) {
if (k[0].match(/[A-Z]/)) {
klass = definition[k];
break;}}}
var parent = definition.inherits;
if (parent) {
if (klass === null) {
klass = function klass() {
parent.apply(this, arguments);};}
inherits(klass, parent);
_.defaults(klass, parent);}
if (klass === null) {
klass = function klass() {};}
var proto = klass.prototype;
function addFunc(original, name, wrapper) {
proto[name] = wrapper || original;}
(definition.getters || []).forEach(function (k) {
var key = '_' + k;
proto[k] = function () {
return this[key];};});
forEach(definition.virtuals, function (f, n) {
addFunc(f, n, function () {
throw new Error('unimplemented');});});
forEach(definition.methods, addFunc);
forEach(definition, function (f, n) {
if (_.isFunction(f) && f !== klass) {
addFunc(f, n);}});
_.assign(klass, definition.statics);
if (typeof klass.init === 'function') {
klass.init();}
forEach(definition.cached, function (f, n) {
var key = '_' + n;
addFunc(f, n, function () {
var value = this[key];
if (value === undefined) {
value = this[key] = f.call(this);}
return value;});});
if (definition.mixins) {(function () {
var mixins = {};
// Right-most in the list win
ensureArray(definition.mixins).reverse().forEach(function (o) {
_.defaults(mixins, o);});
_.defaults(proto, mixins);})();}
return klass;};
/***/ }),
/* 5 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global) {/*!
* The buffer module from node.js, for the browser.
*
* @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
* @license MIT
*/
/* eslint-disable no-proto */
var base64 = __webpack_require__(246)
var ieee754 = __webpack_require__(247)
var isArray = __webpack_require__(248)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
exports.INSPECT_MAX_BYTES = 50
/**
* If `Buffer.TYPED_ARRAY_SUPPORT`:
* === true Use Uint8Array implementation (fastest)
* === false Use Object implementation (most compatible, even IE6)
*
* Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
* Opera 11.6+, iOS 4.2+.
*
* Due to various browser bugs, sometimes the Object implementation will be used even
* when the browser supports typed arrays.
*
* Note:
*
* - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances,
* See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438.
*
* - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function.
*
* - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of
* incorrect length in some situations.
* We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they
* get the Object implementation, which is slower but behaves correctly.
*/
Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined
? global.TYPED_ARRAY_SUPPORT
: typedArraySupport()
/*
* Export kMaxLength after typed array support is determined.
*/
exports.kMaxLength = kMaxLength()
function typedArraySupport () {
try {
var arr = new Uint8Array(1)
arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
return arr.foo() === 42 && // typed array instances can be augmented
typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray`
arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray`
} catch (e) {
return false
}
}
function kMaxLength () {
return Buffer.TYPED_ARRAY_SUPPORT
? 0x7fffffff
: 0x3fffffff
}
function createBuffer (that, length) {
if (kMaxLength() < length) {
throw new RangeError('Invalid typed array length')
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = new Uint8Array(length)
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
if (that === null) {
that = new Buffer(length)
}
that.length = length
}
return that
}
/**
* The Buffer constructor returns instances of `Uint8Array` that have their
* prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
* `Uint8Array`, so the returned instances will have all the node `Buffer` methods
* and the `Uint8Array` methods. Square bracket notation works as expected -- it
* returns a single octet.
*
* The `Uint8Array` prototype remains unmodified.
*/
function Buffer (arg, encodingOrOffset, length) {
if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) {
return new Buffer(arg, encodingOrOffset, length)
}
// Common case.
if (typeof arg === 'number') {
if (typeof encodingOrOffset === 'string') {
throw new Error(
'If encoding is specified then the first argument must be a string'
)
}
return allocUnsafe(this, arg)
}
return from(this, arg, encodingOrOffset, length)
}
Buffer.poolSize = 8192 // not used by this implementation
// TODO: Legacy, not needed anymore. Remove in next major version.
Buffer._augment = function (arr) {
arr.__proto__ = Buffer.prototype
return arr
}
function from (that, value, encodingOrOffset, length) {
if (typeof value === 'number') {
throw new TypeError('"value" argument must not be a number')
}
if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) {
return fromArrayBuffer(that, value, encodingOrOffset, length)
}
if (typeof value === 'string') {
return fromString(that, value, encodingOrOffset)
}
return fromObject(that, value)
}
/**
* Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
* if value is a number.
* Buffer.from(str[, encoding])
* Buffer.from(array)
* Buffer.from(buffer)
* Buffer.from(arrayBuffer[, byteOffset[, length]])
**/
Buffer.from = function (value, encodingOrOffset, length) {
return from(null, value, encodingOrOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
Buffer.prototype.__proto__ = Uint8Array.prototype
Buffer.__proto__ = Uint8Array
if (typeof Symbol !== 'undefined' && Symbol.species &&
Buffer[Symbol.species] === Buffer) {
// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
Object.defineProperty(Buffer, Symbol.species, {
value: null,
configurable: true
})
}
}
function assertSize (size) {
if (typeof size !== 'number') {
throw new TypeError('"size" argument must be a number')
} else if (size < 0) {
throw new RangeError('"size" argument must not be negative')
}
}
function alloc (that, size, fill, encoding) {
assertSize(size)
if (size <= 0) {
return createBuffer(that, size)
}
if (fill !== undefined) {
// Only pay attention to encoding if it's a string. This
// prevents accidentally sending in a number that would
// be interpretted as a start offset.
return typeof encoding === 'string'
? createBuffer(that, size).fill(fill, encoding)
: createBuffer(that, size).fill(fill)
}
return createBuffer(that, size)
}
/**
* Creates a new filled Buffer instance.
* alloc(size[, fill[, encoding]])
**/
Buffer.alloc = function (size, fill, encoding) {
return alloc(null, size, fill, encoding)
}
function allocUnsafe (that, size) {
assertSize(size)
that = createBuffer(that, size < 0 ? 0 : checked(size) | 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) {
for (var i = 0; i < size; ++i) {
that[i] = 0
}
}
return that
}
/**
* Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
* */
Buffer.allocUnsafe = function (size) {
return allocUnsafe(null, size)
}
/**
* Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
*/
Buffer.allocUnsafeSlow = function (size) {
return allocUnsafe(null, size)
}
function fromString (that, string, encoding) {
if (typeof encoding !== 'string' || encoding === '') {
encoding = 'utf8'
}
if (!Buffer.isEncoding(encoding)) {
throw new TypeError('"encoding" must be a valid string encoding')
}
var length = byteLength(string, encoding) | 0
that = createBuffer(that, length)
var actual = that.write(string, encoding)
if (actual !== length) {
// Writing a hex string, for example, that contains invalid characters will
// cause everything after the first invalid character to be ignored. (e.g.
// 'abxxcd' will be treated as 'ab')
that = that.slice(0, actual)
}
return that
}
function fromArrayLike (that, array) {
var length = array.length < 0 ? 0 : checked(array.length) | 0
that = createBuffer(that, length)
for (var i = 0; i < length; i += 1) {
that[i] = array[i] & 255
}
return that
}
function fromArrayBuffer (that, array, byteOffset, length) {
array.byteLength // this throws if `array` is not a valid ArrayBuffer
if (byteOffset < 0 || array.byteLength < byteOffset) {
throw new RangeError('\'offset\' is out of bounds')
}
if (array.byteLength < byteOffset + (length || 0)) {
throw new RangeError('\'length\' is out of bounds')
}
if (byteOffset === undefined && length === undefined) {
array = new Uint8Array(array)
} else if (length === undefined) {
array = new Uint8Array(array, byteOffset)
} else {
array = new Uint8Array(array, byteOffset, length)
}
if (Buffer.TYPED_ARRAY_SUPPORT) {
// Return an augmented `Uint8Array` instance, for best performance
that = array
that.__proto__ = Buffer.prototype
} else {
// Fallback: Return an object instance of the Buffer class
that = fromArrayLike(that, array)
}
return that
}
function fromObject (that, obj) {
if (Buffer.isBuffer(obj)) {
var len = checked(obj.length) | 0
that = createBuffer(that, len)
if (that.length === 0) {
return that
}
obj.copy(that, 0, 0, len)
return that
}
if (obj) {
if ((typeof ArrayBuffer !== 'undefined' &&
obj.buffer instanceof ArrayBuffer) || 'length' in obj) {
if (typeof obj.length !== 'number' || isnan(obj.length)) {
return createBuffer(that, 0)
}
return fromArrayLike(that, obj)
}
if (obj.type === 'Buffer' && isArray(obj.data)) {
return fromArrayLike(that, obj.data)
}
}
throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
}
function checked (length) {
// Note: cannot use `length < kMaxLength()` here because that fails when
// length is NaN (which is otherwise coerced to zero.)
if (length >= kMaxLength()) {
throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
'size: 0x' + kMaxLength().toString(16) + ' bytes')
}
return length | 0
}
function SlowBuffer (length) {
if (+length != length) { // eslint-disable-line eqeqeq
length = 0
}
return Buffer.alloc(+length)
}
Buffer.isBuffer = function isBuffer (b) {
return !!(b != null && b._isBuffer)
}
Buffer.compare = function compare (a, b) {
if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
throw new TypeError('Arguments must be Buffers')
}
if (a === b) return 0
var x = a.length
var y = b.length
for (var i = 0, len = Math.min(x, y); i < len; ++i) {
if (a[i] !== b[i]) {
x = a[i]
y = b[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
Buffer.isEncoding = function isEncoding (encoding) {
switch (String(encoding).toLowerCase()) {
case 'hex':
case 'utf8':
case 'utf-8':
case 'ascii':
case 'latin1':
case 'binary':
case 'base64':
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return true
default:
return false
}
}
Buffer.concat = function concat (list, length) {
if (!isArray(list)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
if (list.length === 0) {
return Buffer.alloc(0)
}
var i
if (length === undefined) {
length = 0
for (i = 0; i < list.length; ++i) {
length += list[i].length
}
}
var buffer = Buffer.allocUnsafe(length)
var pos = 0
for (i = 0; i < list.length; ++i) {
var buf = list[i]
if (!Buffer.isBuffer(buf)) {
throw new TypeError('"list" argument must be an Array of Buffers')
}
buf.copy(buffer, pos)
pos += buf.length
}
return buffer
}
function byteLength (string, encoding) {
if (Buffer.isBuffer(string)) {
return string.length
}
if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' &&
(ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) {
return string.byteLength
}
if (typeof string !== 'string') {
string = '' + string
}
var len = string.length
if (len === 0) return 0
// Use a for loop to avoid recursion
var loweredCase = false
for (;;) {
switch (encoding) {
case 'ascii':
case 'latin1':
case 'binary':
return len
case 'utf8':
case 'utf-8':
case undefined:
return utf8ToBytes(string).length
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return len * 2
case 'hex':
return len >>> 1
case 'base64':
return base64ToBytes(string).length
default:
if (loweredCase) return utf8ToBytes(string).length // assume utf8
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.byteLength = byteLength
function slowToString (encoding, start, end) {
var loweredCase = false
// No need to verify that "this.length <= MAX_UINT32" since it's a read-only
// property of a typed array.
// This behaves neither like String nor Uint8Array in that we set start/end
// to their upper/lower bounds if the value passed is out of range.
// undefined is handled specially as per ECMA-262 6th Edition,
// Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
if (start === undefined || start < 0) {
start = 0
}
// Return early if start > this.length. Done here to prevent potential uint32
// coercion fail below.
if (start > this.length) {
return ''
}
if (end === undefined || end > this.length) {
end = this.length
}
if (end <= 0) {
return ''
}
// Force coersion to uint32. This will also coerce falsey/NaN values to 0.
end >>>= 0
start >>>= 0
if (end <= start) {
return ''
}
if (!encoding) encoding = 'utf8'
while (true) {
switch (encoding) {
case 'hex':
return hexSlice(this, start, end)
case 'utf8':
case 'utf-8':
return utf8Slice(this, start, end)
case 'ascii':
return asciiSlice(this, start, end)
case 'latin1':
case 'binary':
return latin1Slice(this, start, end)
case 'base64':
return base64Slice(this, start, end)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return utf16leSlice(this, start, end)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = (encoding + '').toLowerCase()
loweredCase = true
}
}
}
// The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect
// Buffer instances.
Buffer.prototype._isBuffer = true
function swap (b, n, m) {
var i = b[n]
b[n] = b[m]
b[m] = i
}
Buffer.prototype.swap16 = function swap16 () {
var len = this.length
if (len % 2 !== 0) {
throw new RangeError('Buffer size must be a multiple of 16-bits')
}
for (var i = 0; i < len; i += 2) {
swap(this, i, i + 1)
}
return this
}
Buffer.prototype.swap32 = function swap32 () {
var len = this.length
if (len % 4 !== 0) {
throw new RangeError('Buffer size must be a multiple of 32-bits')
}
for (var i = 0; i < len; i += 4) {
swap(this, i, i + 3)
swap(this, i + 1, i + 2)
}
return this
}
Buffer.prototype.swap64 = function swap64 () {
var len = this.length
if (len % 8 !== 0) {
throw new RangeError('Buffer size must be a multiple of 64-bits')
}
for (var i = 0; i < len; i += 8) {
swap(this, i, i + 7)
swap(this, i + 1, i + 6)
swap(this, i + 2, i + 5)
swap(this, i + 3, i + 4)
}
return this
}
Buffer.prototype.toString = function toString () {
var length = this.length | 0
if (length === 0) return ''
if (arguments.length === 0) return utf8Slice(this, 0, length)
return slowToString.apply(this, arguments)
}
Buffer.prototype.equals = function equals (b) {
if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
if (this === b) return true
return Buffer.compare(this, b) === 0
}
Buffer.prototype.inspect = function inspect () {
var str = ''
var max = exports.INSPECT_MAX_BYTES
if (this.length > 0) {
str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
if (this.length > max) str += ' ... '
}
return '<Buffer ' + str + '>'
}
Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
if (!Buffer.isBuffer(target)) {
throw new TypeError('Argument must be a Buffer')
}
if (start === undefined) {
start = 0
}
if (end === undefined) {
end = target ? target.length : 0
}
if (thisStart === undefined) {
thisStart = 0
}
if (thisEnd === undefined) {
thisEnd = this.length
}
if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
throw new RangeError('out of range index')
}
if (thisStart >= thisEnd && start >= end) {
return 0
}
if (thisStart >= thisEnd) {
return -1
}
if (start >= end) {
return 1
}
start >>>= 0
end >>>= 0
thisStart >>>= 0
thisEnd >>>= 0
if (this === target) return 0
var x = thisEnd - thisStart
var y = end - start
var len = Math.min(x, y)
var thisCopy = this.slice(thisStart, thisEnd)
var targetCopy = target.slice(start, end)
for (var i = 0; i < len; ++i) {
if (thisCopy[i] !== targetCopy[i]) {
x = thisCopy[i]
y = targetCopy[i]
break
}
}
if (x < y) return -1
if (y < x) return 1
return 0
}
// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
//
// Arguments:
// - buffer - a Buffer to search
// - val - a string, Buffer, or number
// - byteOffset - an index into `buffer`; will be clamped to an int32
// - encoding - an optional encoding, relevant is val is a string
// - dir - true for indexOf, false for lastIndexOf
function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
// Empty buffer means no match
if (buffer.length === 0) return -1
// Normalize byteOffset
if (typeof byteOffset === 'string') {
encoding = byteOffset
byteOffset = 0
} else if (byteOffset > 0x7fffffff) {
byteOffset = 0x7fffffff
} else if (byteOffset < -0x80000000) {
byteOffset = -0x80000000
}
byteOffset = +byteOffset // Coerce to Number.
if (isNaN(byteOffset)) {
// byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
byteOffset = dir ? 0 : (buffer.length - 1)
}
// Normalize byteOffset: negative offsets start from the end of the buffer
if (byteOffset < 0) byteOffset = buffer.length + byteOffset
if (byteOffset >= buffer.length) {
if (dir) return -1
else byteOffset = buffer.length - 1
} else if (byteOffset < 0) {
if (dir) byteOffset = 0
else return -1
}
// Normalize val
if (typeof val === 'string') {
val = Buffer.from(val, encoding)
}
// Finally, search either indexOf (if dir is true) or lastIndexOf
if (Buffer.isBuffer(val)) {
// Special case: looking for empty string/buffer always fails
if (val.length === 0) {
return -1
}
return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
} else if (typeof val === 'number') {
val = val & 0xFF // Search for a byte value [0-255]
if (Buffer.TYPED_ARRAY_SUPPORT &&
typeof Uint8Array.prototype.indexOf === 'function') {
if (dir) {
return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
} else {
return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
}
}
return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
}
throw new TypeError('val must be string, number or Buffer')
}
function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
var indexSize = 1
var arrLength = arr.length
var valLength = val.length
if (encoding !== undefined) {
encoding = String(encoding).toLowerCase()
if (encoding === 'ucs2' || encoding === 'ucs-2' ||
encoding === 'utf16le' || encoding === 'utf-16le') {
if (arr.length < 2 || val.length < 2) {
return -1
}
indexSize = 2
arrLength /= 2
valLength /= 2
byteOffset /= 2
}
}
function read (buf, i) {
if (indexSize === 1) {
return buf[i]
} else {
return buf.readUInt16BE(i * indexSize)
}
}
var i
if (dir) {
var foundIndex = -1
for (i = byteOffset; i < arrLength; i++) {
if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
if (foundIndex === -1) foundIndex = i
if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
} else {
if (foundIndex !== -1) i -= i - foundIndex
foundIndex = -1
}
}
} else {
if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
for (i = byteOffset; i >= 0; i--) {
var found = true
for (var j = 0; j < valLength; j++) {
if (read(arr, i + j) !== read(val, j)) {
found = false
break
}
}
if (found) return i
}
}
return -1
}
Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
return this.indexOf(val, byteOffset, encoding) !== -1
}
Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
}
Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
}
function hexWrite (buf, string, offset, length) {
offset = Number(offset) || 0
var remaining = buf.length - offset
if (!length) {
length = remaining
} else {
length = Number(length)
if (length > remaining) {
length = remaining
}
}
// must be an even number of digits
var strLen = string.length
if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
if (length > strLen / 2) {
length = strLen / 2
}
for (var i = 0; i < length; ++i) {
var parsed = parseInt(string.substr(i * 2, 2), 16)
if (isNaN(parsed)) return i
buf[offset + i] = parsed
}
return i
}
function utf8Write (buf, string, offset, length) {
return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
}
function asciiWrite (buf, string, offset, length) {
return blitBuffer(asciiToBytes(string), buf, offset, length)
}
function latin1Write (buf, string, offset, length) {
return asciiWrite(buf, string, offset, length)
}
function base64Write (buf, string, offset, length) {
return blitBuffer(base64ToBytes(string), buf, offset, length)
}
function ucs2Write (buf, string, offset, length) {
return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
}
Buffer.prototype.write = function write (string, offset, length, encoding) {
// Buffer#write(string)
if (offset === undefined) {
encoding = 'utf8'
length = this.length
offset = 0
// Buffer#write(string, encoding)
} else if (length === undefined && typeof offset === 'string') {
encoding = offset
length = this.length
offset = 0
// Buffer#write(string, offset[, length][, encoding])
} else if (isFinite(offset)) {
offset = offset | 0
if (isFinite(length)) {
length = length | 0
if (encoding === undefined) encoding = 'utf8'
} else {
encoding = length
length = undefined
}
// legacy write(string, encoding, offset, length) - remove in v0.13
} else {
throw new Error(
'Buffer.write(string, encoding, offset[, length]) is no longer supported'
)
}
var remaining = this.length - offset
if (length === undefined || length > remaining) length = remaining
if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
throw new RangeError('Attempt to write outside buffer bounds')
}
if (!encoding) encoding = 'utf8'
var loweredCase = false
for (;;) {
switch (encoding) {
case 'hex':
return hexWrite(this, string, offset, length)
case 'utf8':
case 'utf-8':
return utf8Write(this, string, offset, length)
case 'ascii':
return asciiWrite(this, string, offset, length)
case 'latin1':
case 'binary':
return latin1Write(this, string, offset, length)
case 'base64':
// Warning: maxLength not taken into account in base64Write
return base64Write(this, string, offset, length)
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return ucs2Write(this, string, offset, length)
default:
if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
encoding = ('' + encoding).toLowerCase()
loweredCase = true
}
}
}
Buffer.prototype.toJSON = function toJSON () {
return {
type: 'Buffer',
data: Array.prototype.slice.call(this._arr || this, 0)
}
}
function base64Slice (buf, start, end) {
if (start === 0 && end === buf.length) {
return base64.fromByteArray(buf)
} else {
return base64.fromByteArray(buf.slice(start, end))
}
}
function utf8Slice (buf, start, end) {
end = Math.min(buf.length, end)
var res = []
var i = start
while (i < end) {
var firstByte = buf[i]
var codePoint = null
var bytesPerSequence = (firstByte > 0xEF) ? 4
: (firstByte > 0xDF) ? 3
: (firstByte > 0xBF) ? 2
: 1
if (i + bytesPerSequence <= end) {
var secondByte, thirdByte, fourthByte, tempCodePoint
switch (bytesPerSequence) {
case 1:
if (firstByte < 0x80) {
codePoint = firstByte
}
break
case 2:
secondByte = buf[i + 1]
if ((secondByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
if (tempCodePoint > 0x7F) {
codePoint = tempCodePoint
}
}
break
case 3:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
codePoint = tempCodePoint
}
}
break
case 4:
secondByte = buf[i + 1]
thirdByte = buf[i + 2]
fourthByte = buf[i + 3]
if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
codePoint = tempCodePoint
}
}
}
}
if (codePoint === null) {
// we did not generate a valid codePoint so insert a
// replacement char (U+FFFD) and advance only 1 byte
codePoint = 0xFFFD
bytesPerSequence = 1
} else if (codePoint > 0xFFFF) {
// encode to utf16 (surrogate pair dance)
codePoint -= 0x10000
res.push(codePoint >>> 10 & 0x3FF | 0xD800)
codePoint = 0xDC00 | codePoint & 0x3FF
}
res.push(codePoint)
i += bytesPerSequence
}
return decodeCodePointsArray(res)
}
// Based on http://stackoverflow.com/a/22747272/680742, the browser with
// the lowest limit is Chrome, with 0x10000 args.
// We go 1 magnitude less, for safety
var MAX_ARGUMENTS_LENGTH = 0x1000
function decodeCodePointsArray (codePoints) {
var len = codePoints.length
if (len <= MAX_ARGUMENTS_LENGTH) {
return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
}
// Decode in chunks to avoid "call stack size exceeded".
var res = ''
var i = 0
while (i < len) {
res += String.fromCharCode.apply(
String,
codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
)
}
return res
}
function asciiSlice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i] & 0x7F)
}
return ret
}
function latin1Slice (buf, start, end) {
var ret = ''
end = Math.min(buf.length, end)
for (var i = start; i < end; ++i) {
ret += String.fromCharCode(buf[i])
}
return ret
}
function hexSlice (buf, start, end) {
var len = buf.length
if (!start || start < 0) start = 0
if (!end || end < 0 || end > len) end = len
var out = ''
for (var i = start; i < end; ++i) {
out += toHex(buf[i])
}
return out
}
function utf16leSlice (buf, start, end) {
var bytes = buf.slice(start, end)
var res = ''
for (var i = 0; i < bytes.length; i += 2) {
res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256)
}
return res
}
Buffer.prototype.slice = function slice (start, end) {
var len = this.length
start = ~~start
end = end === undefined ? len : ~~end
if (start < 0) {
start += len
if (start < 0) start = 0
} else if (start > len) {
start = len
}
if (end < 0) {
end += len
if (end < 0) end = 0
} else if (end > len) {
end = len
}
if (end < start) end = start
var newBuf
if (Buffer.TYPED_ARRAY_SUPPORT) {
newBuf = this.subarray(start, end)
newBuf.__proto__ = Buffer.prototype
} else {
var sliceLen = end - start
newBuf = new Buffer(sliceLen, undefined)
for (var i = 0; i < sliceLen; ++i) {
newBuf[i] = this[i + start]
}
}
return newBuf
}
/*
* Need to make sure that buffer isn't trying to write out of bounds.
*/
function checkOffset (offset, ext, length) {
if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
}
Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
return val
}
Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
checkOffset(offset, byteLength, this.length)
}
var val = this[offset + --byteLength]
var mul = 1
while (byteLength > 0 && (mul *= 0x100)) {
val += this[offset + --byteLength] * mul
}
return val
}
Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
return this[offset]
}
Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return this[offset] | (this[offset + 1] << 8)
}
Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
return (this[offset] << 8) | this[offset + 1]
}
Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ((this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16)) +
(this[offset + 3] * 0x1000000)
}
Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] * 0x1000000) +
((this[offset + 1] << 16) |
(this[offset + 2] << 8) |
this[offset + 3])
}
Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var val = this[offset]
var mul = 1
var i = 0
while (++i < byteLength && (mul *= 0x100)) {
val += this[offset + i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) checkOffset(offset, byteLength, this.length)
var i = byteLength
var mul = 1
var val = this[offset + --i]
while (i > 0 && (mul *= 0x100)) {
val += this[offset + --i] * mul
}
mul *= 0x80
if (val >= mul) val -= Math.pow(2, 8 * byteLength)
return val
}
Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
if (!noAssert) checkOffset(offset, 1, this.length)
if (!(this[offset] & 0x80)) return (this[offset])
return ((0xff - this[offset] + 1) * -1)
}
Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset] | (this[offset + 1] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 2, this.length)
var val = this[offset + 1] | (this[offset] << 8)
return (val & 0x8000) ? val | 0xFFFF0000 : val
}
Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset]) |
(this[offset + 1] << 8) |
(this[offset + 2] << 16) |
(this[offset + 3] << 24)
}
Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return (this[offset] << 24) |
(this[offset + 1] << 16) |
(this[offset + 2] << 8) |
(this[offset + 3])
}
Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, true, 23, 4)
}
Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 4, this.length)
return ieee754.read(this, offset, false, 23, 4)
}
Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, true, 52, 8)
}
Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
if (!noAssert) checkOffset(offset, 8, this.length)
return ieee754.read(this, offset, false, 52, 8)
}
function checkInt (buf, value, offset, ext, max, min) {
if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
if (offset + ext > buf.length) throw new RangeError('Index out of range')
}
Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var mul = 1
var i = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
byteLength = byteLength | 0
if (!noAssert) {
var maxBytes = Math.pow(2, 8 * byteLength) - 1
checkInt(this, value, offset, byteLength, maxBytes, 0)
}
var i = byteLength - 1
var mul = 1
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
this[offset + i] = (value / mul) & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
this[offset] = (value & 0xff)
return offset + 1
}
function objectWriteUInt16 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) {
buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>>
(littleEndian ? i : 1 - i) * 8
}
}
Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
function objectWriteUInt32 (buf, value, offset, littleEndian) {
if (value < 0) value = 0xffffffff + value + 1
for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) {
buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff
}
}
Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset + 3] = (value >>> 24)
this[offset + 2] = (value >>> 16)
this[offset + 1] = (value >>> 8)
this[offset] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = 0
var mul = 1
var sub = 0
this[offset] = value & 0xFF
while (++i < byteLength && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) {
var limit = Math.pow(2, 8 * byteLength - 1)
checkInt(this, value, offset, byteLength, limit - 1, -limit)
}
var i = byteLength - 1
var mul = 1
var sub = 0
this[offset + i] = value & 0xFF
while (--i >= 0 && (mul *= 0x100)) {
if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
sub = 1
}
this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
}
return offset + byteLength
}
Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value)
if (value < 0) value = 0xff + value + 1
this[offset] = (value & 0xff)
return offset + 1
}
Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
} else {
objectWriteUInt16(this, value, offset, true)
}
return offset + 2
}
Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 8)
this[offset + 1] = (value & 0xff)
} else {
objectWriteUInt16(this, value, offset, false)
}
return offset + 2
}
Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value & 0xff)
this[offset + 1] = (value >>> 8)
this[offset + 2] = (value >>> 16)
this[offset + 3] = (value >>> 24)
} else {
objectWriteUInt32(this, value, offset, true)
}
return offset + 4
}
Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
value = +value
offset = offset | 0
if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
if (value < 0) value = 0xffffffff + value + 1
if (Buffer.TYPED_ARRAY_SUPPORT) {
this[offset] = (value >>> 24)
this[offset + 1] = (value >>> 16)
this[offset + 2] = (value >>> 8)
this[offset + 3] = (value & 0xff)
} else {
objectWriteUInt32(this, value, offset, false)
}
return offset + 4
}
function checkIEEE754 (buf, value, offset, ext, max, min) {
if (offset + ext > buf.length) throw new RangeError('Index out of range')
if (offset < 0) throw new RangeError('Index out of range')
}
function writeFloat (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
}
ieee754.write(buf, value, offset, littleEndian, 23, 4)
return offset + 4
}
Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
return writeFloat(this, value, offset, true, noAssert)
}
Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
return writeFloat(this, value, offset, false, noAssert)
}
function writeDouble (buf, value, offset, littleEndian, noAssert) {
if (!noAssert) {
checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
}
ieee754.write(buf, value, offset, littleEndian, 52, 8)
return offset + 8
}
Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
return writeDouble(this, value, offset, true, noAssert)
}
Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
return writeDouble(this, value, offset, false, noAssert)
}
// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
Buffer.prototype.copy = function copy (target, targetStart, start, end) {
if (!start) start = 0
if (!end && end !== 0) end = this.length
if (targetStart >= target.length) targetStart = target.length
if (!targetStart) targetStart = 0
if (end > 0 && end < start) end = start
// Copy 0 bytes; we're done
if (end === start) return 0
if (target.length === 0 || this.length === 0) return 0
// Fatal error conditions
if (targetStart < 0) {
throw new RangeError('targetStart out of bounds')
}
if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
if (end < 0) throw new RangeError('sourceEnd out of bounds')
// Are we oob?
if (end > this.length) end = this.length
if (target.length - targetStart < end - start) {
end = target.length - targetStart + start
}
var len = end - start
var i
if (this === target && start < targetStart && targetStart < end) {
// descending copy from end
for (i = len - 1; i >= 0; --i) {
target[i + targetStart] = this[i + start]
}
} else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) {
// ascending copy from start
for (i = 0; i < len; ++i) {
target[i + targetStart] = this[i + start]
}
} else {
Uint8Array.prototype.set.call(
target,
this.subarray(start, start + len),
targetStart
)
}
return len
}
// Usage:
// buffer.fill(number[, offset[, end]])
// buffer.fill(buffer[, offset[, end]])
// buffer.fill(string[, offset[, end]][, encoding])
Buffer.prototype.fill = function fill (val, start, end, encoding) {
// Handle string cases:
if (typeof val === 'string') {
if (typeof start === 'string') {
encoding = start
start = 0
end = this.length
} else if (typeof end === 'string') {
encoding = end
end = this.length
}
if (val.length === 1) {
var code = val.charCodeAt(0)
if (code < 256) {
val = code
}
}
if (encoding !== undefined && typeof encoding !== 'string') {
throw new TypeError('encoding must be a string')
}
if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
throw new TypeError('Unknown encoding: ' + encoding)
}
} else if (typeof val === 'number') {
val = val & 255
}
// Invalid ranges are not set to a default, so can range check early.
if (start < 0 || this.length < start || this.length < end) {
throw new RangeError('Out of range index')
}
if (end <= start) {
return this
}
start = start >>> 0
end = end === undefined ? this.length : end >>> 0
if (!val) val = 0
var i
if (typeof val === 'number') {
for (i = start; i < end; ++i) {
this[i] = val
}
} else {
var bytes = Buffer.isBuffer(val)
? val
: utf8ToBytes(new Buffer(val, encoding).toString())
var len = bytes.length
for (i = 0; i < end - start; ++i) {
this[i + start] = bytes[i % len]
}
}
return this
}
// HELPER FUNCTIONS
// ================
var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g
function base64clean (str) {
// Node strips out invalid characters like \n and \t from the string, base64-js does not
str = stringtrim(str).replace(INVALID_BASE64_RE, '')
// Node converts strings with length < 2 to ''
if (str.length < 2) return ''
// Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
while (str.length % 4 !== 0) {
str = str + '='
}
return str
}
function stringtrim (str) {
if (str.trim) return str.trim()
return str.replace(/^\s+|\s+$/g, '')
}
function toHex (n) {
if (n < 16) return '0' + n.toString(16)
return n.toString(16)
}
function utf8ToBytes (string, units) {
units = units || Infinity
var codePoint
var length = string.length
var leadSurrogate = null
var bytes = []
for (var i = 0; i < length; ++i) {
codePoint = string.charCodeAt(i)
// is surrogate component
if (codePoint > 0xD7FF && codePoint < 0xE000) {
// last char was a lead
if (!leadSurrogate) {
// no lead yet
if (codePoint > 0xDBFF) {
// unexpected trail
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
} else if (i + 1 === length) {
// unpaired lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
continue
}
// valid lead
leadSurrogate = codePoint
continue
}
// 2 leads in a row
if (codePoint < 0xDC00) {
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
leadSurrogate = codePoint
continue
}
// valid surrogate pair
codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
} else if (leadSurrogate) {
// valid bmp char, but last char was a lead
if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
}
leadSurrogate = null
// encode utf8
if (codePoint < 0x80) {
if ((units -= 1) < 0) break
bytes.push(codePoint)
} else if (codePoint < 0x800) {
if ((units -= 2) < 0) break
bytes.push(
codePoint >> 0x6 | 0xC0,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x10000) {
if ((units -= 3) < 0) break
bytes.push(
codePoint >> 0xC | 0xE0,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else if (codePoint < 0x110000) {
if ((units -= 4) < 0) break
bytes.push(
codePoint >> 0x12 | 0xF0,
codePoint >> 0xC & 0x3F | 0x80,
codePoint >> 0x6 & 0x3F | 0x80,
codePoint & 0x3F | 0x80
)
} else {
throw new Error('Invalid code point')
}
}
return bytes
}
function asciiToBytes (str) {
var byteArray = []
for (var i = 0; i < str.length; ++i) {
// Node's code seems to be doing this and not & 0x7F..
byteArray.push(str.charCodeAt(i) & 0xFF)
}
return byteArray
}
function utf16leToBytes (str, units) {
var c, hi, lo
var byteArray = []
for (var i = 0; i < str.length; ++i) {
if ((units -= 2) < 0) break
c = str.charCodeAt(i)
hi = c >> 8
lo = c % 256
byteArray.push(lo)
byteArray.push(hi)
}
return byteArray
}
function base64ToBytes (str) {
return base64.toByteArray(base64clean(str))
}
function blitBuffer (src, dst, offset, length) {
for (var i = 0; i < length; ++i) {
if ((i + offset >= dst.length) || (i >= src.length)) break
dst[i + offset] = src[i]
}
return i
}
function isnan (val) {
return val !== val // eslint-disable-line no-self-compare
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ }),
/* 6 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*! bignumber.js v4.1.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
;(function (globalObj) {
'use strict';
/*
bignumber.js v4.1.0
A JavaScript library for arbitrary-precision arithmetic.
https://github.com/MikeMcl/bignumber.js
Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
MIT Expat Licence
*/
var BigNumber,
isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
mathceil = Math.ceil,
mathfloor = Math.floor,
notBool = ' not a boolean or binary digit',
roundingMode = 'rounding mode',
tooManyDigits = 'number type has more than 15 significant digits',
ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
BASE = 1e14,
LOG_BASE = 14,
MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1
// MAX_INT32 = 0x7fffffff, // 2^31 - 1
POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],
SQRT_BASE = 1e7,
/*
* The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
* the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
* exception is thrown (if ERRORS is true).
*/
MAX = 1E9; // 0 to MAX_INT32
/*
* Create and return a BigNumber constructor.
*/
function constructorFactory(config) {
var div, parseNumeric,
// id tracks the caller function, so its name can be included in error messages.
id = 0,
P = BigNumber.prototype,
ONE = new BigNumber(1),
/********************************* EDITABLE DEFAULTS **********************************/
/*
* The default values below must be integers within the inclusive ranges stated.
* The values can also be changed at run-time using BigNumber.config.
*/
// The maximum number of decimal places for operations involving division.
DECIMAL_PLACES = 20, // 0 to MAX
/*
* The rounding mode used when rounding to the above decimal places, and when using
* toExponential, toFixed, toFormat and toPrecision, and round (default value).
* UP 0 Away from zero.
* DOWN 1 Towards zero.
* CEIL 2 Towards +Infinity.
* FLOOR 3 Towards -Infinity.
* HALF_UP 4 Towards nearest neighbour. If equidistant, up.
* HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
* HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
* HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
* HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
*/
ROUNDING_MODE = 4, // 0 to 8
// EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
// The exponent value at and beneath which toString returns exponential notation.
// Number type: -7
TO_EXP_NEG = -7, // 0 to -MAX
// The exponent value at and above which toString returns exponential notation.
// Number type: 21
TO_EXP_POS = 21, // 0 to MAX
// RANGE : [MIN_EXP, MAX_EXP]
// The minimum exponent value, beneath which underflow to zero occurs.
// Number type: -324 (5e-324)
MIN_EXP = -1e7, // -1 to -MAX
// The maximum exponent value, above which overflow to Infinity occurs.
// Number type: 308 (1.7976931348623157e+308)
// For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
MAX_EXP = 1e7, // 1 to MAX
// Whether BigNumber Errors are ever thrown.
ERRORS = true, // true or false
// Change to intValidatorNoErrors if ERRORS is false.
isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors
// Whether to use cryptographically-secure random number generation, if available.
CRYPTO = false, // true or false
/*
* The modulo mode used when calculating the modulus: a mod n.
* The quotient (q = a / n) is calculated according to the corresponding rounding mode.
* The remainder (r) is calculated as: r = a - n * q.
*
* UP 0 The remainder is positive if the dividend is negative, else is negative.
* DOWN 1 The remainder has the same sign as the dividend.
* This modulo mode is commonly known as 'truncated division' and is
* equivalent to (a % n) in JavaScript.
* FLOOR 3 The remainder has the same sign as the divisor (Python %).
* HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
* EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
* The remainder is always positive.
*
* The truncated division, floored division, Euclidian division and IEEE 754 remainder
* modes are commonly used for the modulus operation.
* Although the other rounding modes can also be used, they may not give useful results.
*/
MODULO_MODE = 1, // 0 to 9
// The maximum number of significant digits of the result of the toPower operation.
// If POW_PRECISION is 0, there will be unlimited significant digits.
POW_PRECISION = 0, // 0 to MAX
// The format specification used by the BigNumber.prototype.toFormat method.
FORMAT = {
decimalSeparator: '.',
groupSeparator: ',',
groupSize: 3,
secondaryGroupSize: 0,
fractionGroupSeparator: '\xA0', // non-breaking space
fractionGroupSize: 0
};
/******************************************************************************************/
// CONSTRUCTOR
/*
* The BigNumber constructor and exported function.
* Create and return a new instance of a BigNumber object.
*
* n {number|string|BigNumber} A numeric value.
* [b] {number} The base of n. Integer, 2 to 64 inclusive.
*/
function BigNumber( n, b ) {
var c, e, i, num, len, str,
x = this;
// Enable constructor usage without new.
if ( !( x instanceof BigNumber ) ) {
// 'BigNumber() constructor call without new: {n}'
if (ERRORS) raise( 26, 'constructor call without new', n );
return new BigNumber( n, b );
}
// 'new BigNumber() base not an integer: {b}'
// 'new BigNumber() base out of range: {b}'
if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {
// Duplicate.
if ( n instanceof BigNumber ) {
x.s = n.s;
x.e = n.e;
x.c = ( n = n.c ) ? n.slice() : n;
id = 0;
return;
}
if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {
x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;
// Fast path for integers.
if ( n === ~~n ) {
for ( e = 0, i = n; i >= 10; i /= 10, e++ );
x.e = e;
x.c = [n];
id = 0;
return;
}
str = n + '';
} else {
if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
} else {
b = b | 0;
str = n + '';
// Ensure return value is rounded to DECIMAL_PLACES as with other bases.
// Allow exponential notation to be used with base 10 argument.
if ( b == 10 ) {
x = new BigNumber( n instanceof BigNumber ? n : str );
return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );
}
// Avoid potential interpretation of Infinity and NaN as base 44+ values.
// Any number in exponential form will fail due to the [Ee][+-].
if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||
!( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +
'(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {
return parseNumeric( x, str, num, b );
}
if (num) {
x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;
if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {
// 'new BigNumber() number type has more than 15 significant digits: {n}'
raise( id, tooManyDigits, n );
}
// Prevent later check for length on converted number.
num = false;
} else {
x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;
}
str = convertBase( str, 10, b, x.s );
}
// Decimal point?
if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );
// Exponential form?
if ( ( i = str.search( /e/i ) ) > 0 ) {
// Determine exponent.
if ( e < 0 ) e = i;
e += +str.slice( i + 1 );
str = str.substring( 0, i );
} else if ( e < 0 ) {
// Integer.
e = str.length;
}
// Determine leading zeros.
for ( i = 0; str.charCodeAt(i) === 48; i++ );
// Determine trailing zeros.
for ( len = str.length; str.charCodeAt(--len) === 48; );
str = str.slice( i, len + 1 );
if (str) {
len = str.length;
// Disallow numbers with over 15 significant digits if number type.
// 'new BigNumber() number type has more than 15 significant digits: {n}'
if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {
raise( id, tooManyDigits, x.s * n );
}
e = e - i - 1;
// Overflow?
if ( e > MAX_EXP ) {
// Infinity.
x.c = x.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
x.c = [ x.e = 0 ];
} else {
x.e = e;
x.c = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first element of the coefficient array.
i = ( e + 1 ) % LOG_BASE;
if ( e < 0 ) i += LOG_BASE;
if ( i < len ) {
if (i) x.c.push( +str.slice( 0, i ) );
for ( len -= LOG_BASE; i < len; ) {
x.c.push( +str.slice( i, i += LOG_BASE ) );
}
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for ( ; i--; str += '0' );
x.c.push( +str );
}
} else {
// Zero.
x.c = [ x.e = 0 ];
}
id = 0;
}
// CONSTRUCTOR PROPERTIES
BigNumber.another = constructorFactory;
BigNumber.ROUND_UP = 0;
BigNumber.ROUND_DOWN = 1;
BigNumber.ROUND_CEIL = 2;
BigNumber.ROUND_FLOOR = 3;
BigNumber.ROUND_HALF_UP = 4;
BigNumber.ROUND_HALF_DOWN = 5;
BigNumber.ROUND_HALF_EVEN = 6;
BigNumber.ROUND_HALF_CEIL = 7;
BigNumber.ROUND_HALF_FLOOR = 8;
BigNumber.EUCLID = 9;
/*
* Configure infrequently-changing library-wide settings.
*
* Accept an object or an argument list, with one or many of the following properties or
* parameters respectively:
*
* DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
* ROUNDING_MODE {number} Integer, 0 to 8 inclusive
* EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
* [integer -MAX to 0 incl., 0 to MAX incl.]
* RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
* [integer -MAX to -1 incl., integer 1 to MAX incl.]
* ERRORS {boolean|number} true, false, 1 or 0
* CRYPTO {boolean|number} true, false, 1 or 0
* MODULO_MODE {number} 0 to 9 inclusive
* POW_PRECISION {number} 0 to MAX inclusive
* FORMAT {object} See BigNumber.prototype.toFormat
* decimalSeparator {string}
* groupSeparator {string}
* groupSize {number}
* secondaryGroupSize {number}
* fractionGroupSeparator {string}
* fractionGroupSize {number}
*
* (The values assigned to the above FORMAT object properties are not checked for validity.)
*
* E.g.
* BigNumber.config(20, 4) is equivalent to
* BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
*
* Ignore properties/parameters set to null or undefined.
* Return an object with the properties current values.
*/
BigNumber.config = BigNumber.set = function () {
var v, p,
i = 0,
r = {},
a = arguments,
o = a[0],
has = o && typeof o == 'object'
? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }
: function () { if ( a.length > i ) return ( v = a[i++] ) != null; };
// DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
// 'config() DECIMAL_PLACES not an integer: {v}'
// 'config() DECIMAL_PLACES out of range: {v}'
if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {
DECIMAL_PLACES = v | 0;
}
r[p] = DECIMAL_PLACES;
// ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
// 'config() ROUNDING_MODE not an integer: {v}'
// 'config() ROUNDING_MODE out of range: {v}'
if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {
ROUNDING_MODE = v | 0;
}
r[p] = ROUNDING_MODE;
// EXPONENTIAL_AT {number|number[]}
// Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
// 'config() EXPONENTIAL_AT not an integer: {v}'
// 'config() EXPONENTIAL_AT out of range: {v}'
if ( has( p = 'EXPONENTIAL_AT' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {
TO_EXP_NEG = v[0] | 0;
TO_EXP_POS = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );
}
}
r[p] = [ TO_EXP_NEG, TO_EXP_POS ];
// RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
// [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
// 'config() RANGE not an integer: {v}'
// 'config() RANGE cannot be zero: {v}'
// 'config() RANGE out of range: {v}'
if ( has( p = 'RANGE' ) ) {
if ( isArray(v) ) {
if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {
MIN_EXP = v[0] | 0;
MAX_EXP = v[1] | 0;
}
} else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {
if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );
else if (ERRORS) raise( 2, p + ' cannot be zero', v );
}
}
r[p] = [ MIN_EXP, MAX_EXP ];
// ERRORS {boolean|number} true, false, 1 or 0.
// 'config() ERRORS not a boolean or binary digit: {v}'
if ( has( p = 'ERRORS' ) ) {
if ( v === !!v || v === 1 || v === 0 ) {
id = 0;
isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = ERRORS;
// CRYPTO {boolean|number} true, false, 1 or 0.
// 'config() CRYPTO not a boolean or binary digit: {v}'
// 'config() crypto unavailable: {crypto}'
if ( has( p = 'CRYPTO' ) ) {
if ( v === true || v === false || v === 1 || v === 0 ) {
if (v) {
v = typeof crypto == 'undefined';
if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {
CRYPTO = true;
} else if (ERRORS) {
raise( 2, 'crypto unavailable', v ? void 0 : crypto );
} else {
CRYPTO = false;
}
} else {
CRYPTO = false;
}
} else if (ERRORS) {
raise( 2, p + notBool, v );
}
}
r[p] = CRYPTO;
// MODULO_MODE {number} Integer, 0 to 9 inclusive.
// 'config() MODULO_MODE not an integer: {v}'
// 'config() MODULO_MODE out of range: {v}'
if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {
MODULO_MODE = v | 0;
}
r[p] = MODULO_MODE;
// POW_PRECISION {number} Integer, 0 to MAX inclusive.
// 'config() POW_PRECISION not an integer: {v}'
// 'config() POW_PRECISION out of range: {v}'
if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {
POW_PRECISION = v | 0;
}
r[p] = POW_PRECISION;
// FORMAT {object}
// 'config() FORMAT not an object: {v}'
if ( has( p = 'FORMAT' ) ) {
if ( typeof v == 'object' ) {
FORMAT = v;
} else if (ERRORS) {
raise( 2, p + ' not an object', v );
}
}
r[p] = FORMAT;
return r;
};
/*
* Return a new BigNumber whose value is the maximum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };
/*
* Return a new BigNumber whose value is the minimum of the arguments.
*
* arguments {number|string|BigNumber}
*/
BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };
/*
* Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
* and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
* zeros are produced).
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
*
* 'random() decimal places not an integer: {dp}'
* 'random() decimal places out of range: {dp}'
* 'random() crypto unavailable: {crypto}'
*/
BigNumber.random = (function () {
var pow2_53 = 0x20000000000000;
// Return a 53 bit integer n, where 0 <= n < 9007199254740992.
// Check if Math.random() produces more than 32 bits of randomness.
// If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
// 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
var random53bitInt = (Math.random() * pow2_53) & 0x1fffff
? function () { return mathfloor( Math.random() * pow2_53 ); }
: function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +
(Math.random() * 0x800000 | 0); };
return function (dp) {
var a, b, e, k, v,
i = 0,
c = [],
rand = new BigNumber(ONE);
dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;
k = mathceil( dp / LOG_BASE );
if (CRYPTO) {
// Browsers supporting crypto.getRandomValues.
if (crypto.getRandomValues) {
a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );
for ( ; i < k; ) {
// 53 bits:
// ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
// 11111 11111111 11111111 11111111 11100000 00000000 00000000
// ((Math.pow(2, 32) - 1) >>> 11).toString(2)
// 11111 11111111 11111111
// 0x20000 is 2^21.
v = a[i] * 0x20000 + (a[i + 1] >>> 11);
// Rejection sampling:
// 0 <= v < 9007199254740992
// Probability that v >= 9e15, is
// 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
if ( v >= 9e15 ) {
b = crypto.getRandomValues( new Uint32Array(2) );
a[i] = b[0];
a[i + 1] = b[1];
} else {
// 0 <= v <= 8999999999999999
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 2;
}
}
i = k / 2;
// Node.js supporting crypto.randomBytes.
} else if (crypto.randomBytes) {
// buffer
a = crypto.randomBytes( k *= 7 );
for ( ; i < k; ) {
// 0x1000000000000 is 2^48, 0x10000000000 is 2^40
// 0x100000000 is 2^32, 0x1000000 is 2^24
// 11111 11111111 11111111 11111111 11111111 11111111 11111111
// 0 <= v < 9007199254740992
v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +
( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +
( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];
if ( v >= 9e15 ) {
crypto.randomBytes(7).copy( a, i );
} else {
// 0 <= (v % 1e14) <= 99999999999999
c.push( v % 1e14 );
i += 7;
}
}
i = k / 7;
} else {
CRYPTO = false;
if (ERRORS) raise( 14, 'crypto unavailable', crypto );
}
}
// Use Math.random.
if (!CRYPTO) {
for ( ; i < k; ) {
v = random53bitInt();
if ( v < 9e15 ) c[i++] = v % 1e14;
}
}
k = c[--i];
dp %= LOG_BASE;
// Convert trailing digits to zeros according to dp.
if ( k && dp ) {
v = POWS_TEN[LOG_BASE - dp];
c[i] = mathfloor( k / v ) * v;
}
// Remove trailing elements which are zero.
for ( ; c[i] === 0; c.pop(), i-- );
// Zero?
if ( i < 0 ) {
c = [ e = 0 ];
} else {
// Remove leading elements which are zero and adjust exponent accordingly.
for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);
// Count the digits of the first element of c to determine leading zeros, and...
for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);
// adjust the exponent accordingly.
if ( i < LOG_BASE ) e -= LOG_BASE - i;
}
rand.e = e;
rand.c = c;
return rand;
};
})();
// PRIVATE FUNCTIONS
// Convert a numeric string of baseIn to a numeric string of baseOut.
function convertBase( str, baseOut, baseIn, sign ) {
var d, e, k, r, x, xc, y,
i = str.indexOf( '.' ),
dp = DECIMAL_PLACES,
rm = ROUNDING_MODE;
if ( baseIn < 37 ) str = str.toLowerCase();
// Non-integer.
if ( i >= 0 ) {
k = POW_PRECISION;
// Unlimited precision.
POW_PRECISION = 0;
str = str.replace( '.', '' );
y = new BigNumber(baseIn);
x = y.pow( str.length - i );
POW_PRECISION = k;
// Convert str as if an integer, then restore the fraction part by dividing the
// result by its base raised to a power.
y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );
y.e = y.c.length;
}
// Convert the number as integer.
xc = toBaseOut( str, baseIn, baseOut );
e = k = xc.length;
// Remove trailing zeros.
for ( ; xc[--k] == 0; xc.pop() );
if ( !xc[0] ) return '0';
if ( i < 0 ) {
--e;
} else {
x.c = xc;
x.e = e;
// sign is needed for correct rounding.
x.s = sign;
x = div( x, y, dp, rm, baseOut );
xc = x.c;
r = x.r;
e = x.e;
}
d = e + dp + 1;
// The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
i = xc[d];
k = baseOut / 2;
r = r || d < 0 || xc[d + 1] != null;
r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( d < 1 || !xc[0] ) {
// 1^-dp or 0.
str = r ? toFixedPoint( '1', -dp ) : '0';
} else {
xc.length = d;
if (r) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for ( --baseOut; ++xc[--d] > baseOut; ) {
xc[d] = 0;
if ( !d ) {
++e;
xc = [1].concat(xc);
}
}
}
// Determine trailing zeros.
for ( k = xc.length; !xc[--k]; );
// E.g. [4, 11, 15] becomes 4bf.
for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );
str = toFixedPoint( str, e );
}
// The caller will add the sign.
return str;
}
// Perform division in the specified base. Called by div and convertBase.
div = (function () {
// Assume non-zero x and k.
function multiply( x, k, base ) {
var m, temp, xlo, xhi,
carry = 0,
i = x.length,
klo = k % SQRT_BASE,
khi = k / SQRT_BASE | 0;
for ( x = x.slice(); i--; ) {
xlo = x[i] % SQRT_BASE;
xhi = x[i] / SQRT_BASE | 0;
m = khi * xlo + xhi * klo;
temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;
carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;
x[i] = temp % base;
}
if (carry) x = [carry].concat(x);
return x;
}
function compare( a, b, aL, bL ) {
var i, cmp;
if ( aL != bL ) {
cmp = aL > bL ? 1 : -1;
} else {
for ( i = cmp = 0; i < aL; i++ ) {
if ( a[i] != b[i] ) {
cmp = a[i] > b[i] ? 1 : -1;
break;
}
}
}
return cmp;
}
function subtract( a, b, aL, base ) {
var i = 0;
// Subtract b from a.
for ( ; aL--; ) {
a[aL] -= i;
i = a[aL] < b[aL] ? 1 : 0;
a[aL] = i * base + a[aL] - b[aL];
}
// Remove leading zeros.
for ( ; !a[0] && a.length > 1; a.splice(0, 1) );
}
// x: dividend, y: divisor.
return function ( x, y, dp, rm, base ) {
var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,
yL, yz,
s = x.s == y.s ? 1 : -1,
xc = x.c,
yc = y.c;
// Either NaN, Infinity or 0?
if ( !xc || !xc[0] || !yc || !yc[0] ) {
return new BigNumber(
// Return NaN if either NaN, or both Infinity or 0.
!x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :
// Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
xc && xc[0] == 0 || !yc ? s * 0 : s / 0
);
}
q = new BigNumber(s);
qc = q.c = [];
e = x.e - y.e;
s = dp + e + 1;
if ( !base ) {
base = BASE;
e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );
s = s / LOG_BASE | 0;
}
// Result exponent may be one less then the current value of e.
// The coefficients of the BigNumbers from convertBase may have trailing zeros.
for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );
if ( yc[i] > ( xc[i] || 0 ) ) e--;
if ( s < 0 ) {
qc.push(1);
more = true;
} else {
xL = xc.length;
yL = yc.length;
i = 0;
s += 2;
// Normalise xc and yc so highest order digit of yc is >= base / 2.
n = mathfloor( base / ( yc[0] + 1 ) );
// Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
// if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
if ( n > 1 ) {
yc = multiply( yc, n, base );
xc = multiply( xc, n, base );
yL = yc.length;
xL = xc.length;
}
xi = yL;
rem = xc.slice( 0, yL );
remL = rem.length;
// Add zeros to make remainder as long as divisor.
for ( ; remL < yL; rem[remL++] = 0 );
yz = yc.slice();
yz = [0].concat(yz);
yc0 = yc[0];
if ( yc[1] >= base / 2 ) yc0++;
// Not necessary, but to prevent trial digit n > base, when using base 3.
// else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
do {
n = 0;
// Compare divisor and remainder.
cmp = compare( yc, rem, yL, remL );
// If divisor < remainder.
if ( cmp < 0 ) {
// Calculate trial digit, n.
rem0 = rem[0];
if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );
// n is how many times the divisor goes into the current remainder.
n = mathfloor( rem0 / yc0 );
// Algorithm:
// 1. product = divisor * trial digit (n)
// 2. if product > remainder: product -= divisor, n--
// 3. remainder -= product
// 4. if product was < remainder at 2:
// 5. compare new remainder and divisor
// 6. If remainder > divisor: remainder -= divisor, n++
if ( n > 1 ) {
// n may be > base only when base is 3.
if (n >= base) n = base - 1;
// product = divisor * trial digit.
prod = multiply( yc, n, base );
prodL = prod.length;
remL = rem.length;
// Compare product and remainder.
// If product > remainder.
// Trial digit n too high.
// n is 1 too high about 5% of the time, and is not known to have
// ever been more than 1 too high.
while ( compare( prod, rem, prodL, remL ) == 1 ) {
n--;
// Subtract divisor from product.
subtract( prod, yL < prodL ? yz : yc, prodL, base );
prodL = prod.length;
cmp = 1;
}
} else {
// n is 0 or 1, cmp is -1.
// If n is 0, there is no need to compare yc and rem again below,
// so change cmp to 1 to avoid it.
// If n is 1, leave cmp as -1, so yc and rem are compared again.
if ( n == 0 ) {
// divisor < remainder, so n must be at least 1.
cmp = n = 1;
}
// product = divisor
prod = yc.slice();
prodL = prod.length;
}
if ( prodL < remL ) prod = [0].concat(prod);
// Subtract product from remainder.
subtract( rem, prod, remL, base );
remL = rem.length;
// If product was < remainder.
if ( cmp == -1 ) {
// Compare divisor and new remainder.
// If divisor < new remainder, subtract divisor from remainder.
// Trial digit n too low.
// n is 1 too low about 5% of the time, and very rarely 2 too low.
while ( compare( yc, rem, yL, remL ) < 1 ) {
n++;
// Subtract divisor from remainder.
subtract( rem, yL < remL ? yz : yc, remL, base );
remL = rem.length;
}
}
} else if ( cmp === 0 ) {
n++;
rem = [0];
} // else cmp === 1 and n will be 0
// Add the next digit, n, to the result array.
qc[i++] = n;
// Update the remainder.
if ( rem[0] ) {
rem[remL++] = xc[xi] || 0;
} else {
rem = [ xc[xi] ];
remL = 1;
}
} while ( ( xi++ < xL || rem[0] != null ) && s-- );
more = rem[0] != null;
// Leading zero?
if ( !qc[0] ) qc.splice(0, 1);
}
if ( base == BASE ) {
// To calculate q.e, first get the number of digits of qc[0].
for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );
round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );
// Caller is convertBase.
} else {
q.e = e;
q.r = +more;
}
return q;
};
})();
/*
* Return a string representing the value of BigNumber n in fixed-point or exponential
* notation rounded to the specified decimal places or significant digits.
*
* n is a BigNumber.
* i is the index of the last digit required (i.e. the digit that may be rounded up).
* rm is the rounding mode.
* caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
*/
function format( n, i, rm, caller ) {
var c0, e, ne, len, str;
rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )
? rm | 0 : ROUNDING_MODE;
if ( !n.c ) return n.toString();
c0 = n.c[0];
ne = n.e;
if ( i == null ) {
str = coeffToString( n.c );
str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG
? toExponential( str, ne )
: toFixedPoint( str, ne );
} else {
n = round( new BigNumber(n), i, rm );
// n.e may have changed if the value was rounded up.
e = n.e;
str = coeffToString( n.c );
len = str.length;
// toPrecision returns exponential notation if the number of significant digits
// specified is less than the number of digits necessary to represent the integer
// part of the value in fixed-point notation.
// Exponential notation.
if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {
// Append zeros?
for ( ; len < i; str += '0', len++ );
str = toExponential( str, e );
// Fixed-point notation.
} else {
i -= ne;
str = toFixedPoint( str, e );
// Append zeros?
if ( e + 1 > len ) {
if ( --i > 0 ) for ( str += '.'; i--; str += '0' );
} else {
i += e - len;
if ( i > 0 ) {
if ( e + 1 == len ) str += '.';
for ( ; i--; str += '0' );
}
}
}
}
return n.s < 0 && c0 ? '-' + str : str;
}
// Handle BigNumber.max and BigNumber.min.
function maxOrMin( args, method ) {
var m, n,
i = 0;
if ( isArray( args[0] ) ) args = args[0];
m = new BigNumber( args[0] );
for ( ; ++i < args.length; ) {
n = new BigNumber( args[i] );
// If any number is NaN, return NaN.
if ( !n.s ) {
m = n;
break;
} else if ( method.call( m, n ) ) {
m = n;
}
}
return m;
}
/*
* Return true if n is an integer in range, otherwise throw.
* Use for argument validation when ERRORS is true.
*/
function intValidatorWithErrors( n, min, max, caller, name ) {
if ( n < min || n > max || n != truncate(n) ) {
raise( caller, ( name || 'decimal places' ) +
( n < min || n > max ? ' out of range' : ' not an integer' ), n );
}
return true;
}
/*
* Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
* Called by minus, plus and times.
*/
function normalise( n, c, e ) {
var i = 1,
j = c.length;
// Remove trailing zeros.
for ( ; !c[--j]; c.pop() );
// Calculate the base 10 exponent. First get the number of digits of c[0].
for ( j = c[0]; j >= 10; j /= 10, i++ );
// Overflow?
if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {
// Infinity.
n.c = n.e = null;
// Underflow?
} else if ( e < MIN_EXP ) {
// Zero.
n.c = [ n.e = 0 ];
} else {
n.e = e;
n.c = c;
}
return n;
}
// Handle values that fail the validity test in BigNumber.
parseNumeric = (function () {
var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,
dotAfter = /^([^.]+)\.$/,
dotBefore = /^\.([^.]+)$/,
isInfinityOrNaN = /^-?(Infinity|NaN)$/,
whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;
return function ( x, str, num, b ) {
var base,
s = num ? str : str.replace( whitespaceOrPlus, '' );
// No exception on ±Infinity or NaN.
if ( isInfinityOrNaN.test(s) ) {
x.s = isNaN(s) ? null : s < 0 ? -1 : 1;
} else {
if ( !num ) {
// basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
s = s.replace( basePrefix, function ( m, p1, p2 ) {
base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;
return !b || b == base ? p1 : m;
});
if (b) {
base = b;
// E.g. '1.' to '1', '.1' to '0.1'
s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );
}
if ( str != s ) return new BigNumber( s, base );
}
// 'new BigNumber() not a number: {n}'
// 'new BigNumber() not a base {b} number: {n}'
if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );
x.s = null;
}
x.c = x.e = null;
id = 0;
}
})();
// Throw a BigNumber Error.
function raise( caller, msg, val ) {
var error = new Error( [
'new BigNumber', // 0
'cmp', // 1
'config', // 2
'div', // 3
'divToInt', // 4
'eq', // 5
'gt', // 6
'gte', // 7
'lt', // 8
'lte', // 9
'minus', // 10
'mod', // 11
'plus', // 12
'precision', // 13
'random', // 14
'round', // 15
'shift', // 16
'times', // 17
'toDigits', // 18
'toExponential', // 19
'toFixed', // 20
'toFormat', // 21
'toFraction', // 22
'pow', // 23
'toPrecision', // 24
'toString', // 25
'BigNumber' // 26
][caller] + '() ' + msg + ': ' + val );
error.name = 'BigNumber Error';
id = 0;
throw error;
}
/*
* Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
* If r is truthy, it is known that there are more digits after the rounding digit.
*/
function round( x, sd, rm, r ) {
var d, i, j, k, n, ni, rd,
xc = x.c,
pows10 = POWS_TEN;
// if x is not Infinity or NaN...
if (xc) {
// rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
// n is a base 1e14 number, the value of the element of array x.c containing rd.
// ni is the index of n within x.c.
// d is the number of digits of n.
// i is the index of rd within n including leading zeros.
// j is the actual index of rd within n (if < 0, rd is a leading zero).
out: {
// Get the number of digits of the first element of xc.
for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );
i = sd - d;
// If the rounding digit is in the first element of xc...
if ( i < 0 ) {
i += LOG_BASE;
j = sd;
n = xc[ ni = 0 ];
// Get the rounding digit at index j of n.
rd = n / pows10[ d - j - 1 ] % 10 | 0;
} else {
ni = mathceil( ( i + 1 ) / LOG_BASE );
if ( ni >= xc.length ) {
if (r) {
// Needed by sqrt.
for ( ; xc.length <= ni; xc.push(0) );
n = rd = 0;
d = 1;
i %= LOG_BASE;
j = i - LOG_BASE + 1;
} else {
break out;
}
} else {
n = k = xc[ni];
// Get the number of digits of n.
for ( d = 1; k >= 10; k /= 10, d++ );
// Get the index of rd within n.
i %= LOG_BASE;
// Get the index of rd within n, adjusted for leading zeros.
// The number of leading zeros of n is given by LOG_BASE - d.
j = i - LOG_BASE + d;
// Get the rounding digit at index j of n.
rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;
}
}
r = r || sd < 0 ||
// Are there any non-zero digits after the rounding digit?
// The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
// of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );
r = rm < 4
? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )
: rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&
// Check whether the digit to the left of the rounding digit is odd.
( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||
rm == ( x.s < 0 ? 8 : 7 ) );
if ( sd < 1 || !xc[0] ) {
xc.length = 0;
if (r) {
// Convert sd to decimal places.
sd -= x.e + 1;
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];
x.e = -sd || 0;
} else {
// Zero.
xc[0] = x.e = 0;
}
return x;
}
// Remove excess digits.
if ( i == 0 ) {
xc.length = ni;
k = 1;
ni--;
} else {
xc.length = ni + 1;
k = pows10[ LOG_BASE - i ];
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
// j > 0 means i > number of leading zeros of n.
xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;
}
// Round up?
if (r) {
for ( ; ; ) {
// If the digit to be rounded up is in the first element of xc...
if ( ni == 0 ) {
// i will be the length of xc[0] before k is added.
for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );
j = xc[0] += k;
for ( k = 1; j >= 10; j /= 10, k++ );
// if i != k the length has increased.
if ( i != k ) {
x.e++;
if ( xc[0] == BASE ) xc[0] = 1;
}
break;
} else {
xc[ni] += k;
if ( xc[ni] != BASE ) break;
xc[ni--] = 0;
k = 1;
}
}
}
// Remove trailing zeros.
for ( i = xc.length; xc[--i] === 0; xc.pop() );
}
// Overflow? Infinity.
if ( x.e > MAX_EXP ) {
x.c = x.e = null;
// Underflow? Zero.
} else if ( x.e < MIN_EXP ) {
x.c = [ x.e = 0 ];
}
}
return x;
}
// PROTOTYPE/INSTANCE METHODS
/*
* Return a new BigNumber whose value is the absolute value of this BigNumber.
*/
P.absoluteValue = P.abs = function () {
var x = new BigNumber(this);
if ( x.s < 0 ) x.s = 1;
return x;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of Infinity.
*/
P.ceil = function () {
return round( new BigNumber(this), this.e + 1, 2 );
};
/*
* Return
* 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
* -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
* 0 if they have the same value,
* or null if the value of either is NaN.
*/
P.comparedTo = P.cmp = function ( y, b ) {
id = 1;
return compare( this, new BigNumber( y, b ) );
};
/*
* Return the number of decimal places of the value of this BigNumber, or null if the value
* of this BigNumber is ±Infinity or NaN.
*/
P.decimalPlaces = P.dp = function () {
var n, v,
c = this.c;
if ( !c ) return null;
n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;
// Subtract the number of trailing zeros of the last number.
if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );
if ( n < 0 ) n = 0;
return n;
};
/*
* n / 0 = I
* n / N = N
* n / I = 0
* 0 / n = 0
* 0 / 0 = N
* 0 / N = N
* 0 / I = 0
* N / n = N
* N / 0 = N
* N / N = N
* N / I = N
* I / n = I
* I / 0 = I
* I / N = N
* I / I = N
*
* Return a new BigNumber whose value is the value of this BigNumber divided by the value of
* BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.dividedBy = P.div = function ( y, b ) {
id = 3;
return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );
};
/*
* Return a new BigNumber whose value is the integer part of dividing the value of this
* BigNumber by the value of BigNumber(y, b).
*/
P.dividedToIntegerBy = P.divToInt = function ( y, b ) {
id = 4;
return div( this, new BigNumber( y, b ), 0, 1 );
};
/*
* Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
* otherwise returns false.
*/
P.equals = P.eq = function ( y, b ) {
id = 5;
return compare( this, new BigNumber( y, b ) ) === 0;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
* number in the direction of -Infinity.
*/
P.floor = function () {
return round( new BigNumber(this), this.e + 1, 3 );
};
/*
* Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.greaterThan = P.gt = function ( y, b ) {
id = 6;
return compare( this, new BigNumber( y, b ) ) > 0;
};
/*
* Return true if the value of this BigNumber is greater than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.greaterThanOrEqualTo = P.gte = function ( y, b ) {
id = 7;
return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;
};
/*
* Return true if the value of this BigNumber is a finite number, otherwise returns false.
*/
P.isFinite = function () {
return !!this.c;
};
/*
* Return true if the value of this BigNumber is an integer, otherwise return false.
*/
P.isInteger = P.isInt = function () {
return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;
};
/*
* Return true if the value of this BigNumber is NaN, otherwise returns false.
*/
P.isNaN = function () {
return !this.s;
};
/*
* Return true if the value of this BigNumber is negative, otherwise returns false.
*/
P.isNegative = P.isNeg = function () {
return this.s < 0;
};
/*
* Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
*/
P.isZero = function () {
return !!this.c && this.c[0] == 0;
};
/*
* Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
* otherwise returns false.
*/
P.lessThan = P.lt = function ( y, b ) {
id = 8;
return compare( this, new BigNumber( y, b ) ) < 0;
};
/*
* Return true if the value of this BigNumber is less than or equal to the value of
* BigNumber(y, b), otherwise returns false.
*/
P.lessThanOrEqualTo = P.lte = function ( y, b ) {
id = 9;
return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;
};
/*
* n - 0 = n
* n - N = N
* n - I = -I
* 0 - n = -n
* 0 - 0 = 0
* 0 - N = N
* 0 - I = -I
* N - n = N
* N - 0 = N
* N - N = N
* N - I = N
* I - n = I
* I - 0 = I
* I - N = N
* I - I = N
*
* Return a new BigNumber whose value is the value of this BigNumber minus the value of
* BigNumber(y, b).
*/
P.minus = P.sub = function ( y, b ) {
var i, j, t, xLTy,
x = this,
a = x.s;
id = 10;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.plus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Either Infinity?
if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );
// Either zero?
if ( !xc[0] || !yc[0] ) {
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :
// IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
ROUNDING_MODE == 3 ? -0 : 0 );
}
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Determine which is the bigger number.
if ( a = xe - ye ) {
if ( xLTy = a < 0 ) {
a = -a;
t = xc;
} else {
ye = xe;
t = yc;
}
t.reverse();
// Prepend zeros to equalise exponents.
for ( b = a; b--; t.push(0) );
t.reverse();
} else {
// Exponents equal. Check digit by digit.
j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;
for ( a = b = 0; b < j; b++ ) {
if ( xc[b] != yc[b] ) {
xLTy = xc[b] < yc[b];
break;
}
}
}
// x < y? Point xc to the array of the bigger number.
if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;
b = ( j = yc.length ) - ( i = xc.length );
// Append zeros to xc if shorter.
// No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
if ( b > 0 ) for ( ; b--; xc[i++] = 0 );
b = BASE - 1;
// Subtract yc from xc.
for ( ; j > a; ) {
if ( xc[--j] < yc[j] ) {
for ( i = j; i && !xc[--i]; xc[i] = b );
--xc[i];
xc[j] += BASE;
}
xc[j] -= yc[j];
}
// Remove leading zeros and adjust exponent accordingly.
for ( ; xc[0] == 0; xc.splice(0, 1), --ye );
// Zero?
if ( !xc[0] ) {
// Following IEEE 754 (2008) 6.3,
// n - n = +0 but n - n = -0 when rounding towards -Infinity.
y.s = ROUNDING_MODE == 3 ? -1 : 1;
y.c = [ y.e = 0 ];
return y;
}
// No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
// for finite x and y.
return normalise( y, xc, ye );
};
/*
* n % 0 = N
* n % N = N
* n % I = n
* 0 % n = 0
* -0 % n = -0
* 0 % 0 = N
* 0 % N = N
* 0 % I = 0
* N % n = N
* N % 0 = N
* N % N = N
* N % I = N
* I % n = N
* I % 0 = N
* I % N = N
* I % I = N
*
* Return a new BigNumber whose value is the value of this BigNumber modulo the value of
* BigNumber(y, b). The result depends on the value of MODULO_MODE.
*/
P.modulo = P.mod = function ( y, b ) {
var q, s,
x = this;
id = 11;
y = new BigNumber( y, b );
// Return NaN if x is Infinity or NaN, or y is NaN or zero.
if ( !x.c || !y.s || y.c && !y.c[0] ) {
return new BigNumber(NaN);
// Return x if y is Infinity or x is zero.
} else if ( !y.c || x.c && !x.c[0] ) {
return new BigNumber(x);
}
if ( MODULO_MODE == 9 ) {
// Euclidian division: q = sign(y) * floor(x / abs(y))
// r = x - qy where 0 <= r < abs(y)
s = y.s;
y.s = 1;
q = div( x, y, 0, 3 );
y.s = s;
q.s *= s;
} else {
q = div( x, y, 0, MODULO_MODE );
}
return x.minus( q.times(y) );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber negated,
* i.e. multiplied by -1.
*/
P.negated = P.neg = function () {
var x = new BigNumber(this);
x.s = -x.s || null;
return x;
};
/*
* n + 0 = n
* n + N = N
* n + I = I
* 0 + n = n
* 0 + 0 = 0
* 0 + N = N
* 0 + I = I
* N + n = N
* N + 0 = N
* N + N = N
* N + I = N
* I + n = I
* I + 0 = I
* I + N = N
* I + I = I
*
* Return a new BigNumber whose value is the value of this BigNumber plus the value of
* BigNumber(y, b).
*/
P.plus = P.add = function ( y, b ) {
var t,
x = this,
a = x.s;
id = 12;
y = new BigNumber( y, b );
b = y.s;
// Either NaN?
if ( !a || !b ) return new BigNumber(NaN);
// Signs differ?
if ( a != b ) {
y.s = -b;
return x.minus(y);
}
var xe = x.e / LOG_BASE,
ye = y.e / LOG_BASE,
xc = x.c,
yc = y.c;
if ( !xe || !ye ) {
// Return ±Infinity if either ±Infinity.
if ( !xc || !yc ) return new BigNumber( a / 0 );
// Either zero?
// Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );
}
xe = bitFloor(xe);
ye = bitFloor(ye);
xc = xc.slice();
// Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
if ( a = xe - ye ) {
if ( a > 0 ) {
ye = xe;
t = yc;
} else {
a = -a;
t = xc;
}
t.reverse();
for ( ; a--; t.push(0) );
t.reverse();
}
a = xc.length;
b = yc.length;
// Point xc to the longer array, and b to the shorter length.
if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;
// Only start adding at yc.length - 1 as the further digits of xc can be ignored.
for ( a = 0; b; ) {
a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;
xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;
}
if (a) {
xc = [a].concat(xc);
++ye;
}
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
// ye = MAX_EXP + 1 possible
return normalise( y, xc, ye );
};
/*
* Return the number of significant digits of the value of this BigNumber.
*
* [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
*/
P.precision = P.sd = function (z) {
var n, v,
x = this,
c = x.c;
// 'precision() argument not a boolean or binary digit: {z}'
if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {
if (ERRORS) raise( 13, 'argument' + notBool, z );
if ( z != !!z ) z = null;
}
if ( !c ) return null;
v = c.length - 1;
n = v * LOG_BASE + 1;
if ( v = c[v] ) {
// Subtract the number of trailing zeros of the last element.
for ( ; v % 10 == 0; v /= 10, n-- );
// Add the number of digits of the first element.
for ( v = c[0]; v >= 10; v /= 10, n++ );
}
if ( z && x.e + 1 > n ) n = x.e + 1;
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
* omitted.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'round() decimal places out of range: {dp}'
* 'round() decimal places not an integer: {dp}'
* 'round() rounding mode not an integer: {rm}'
* 'round() rounding mode out of range: {rm}'
*/
P.round = function ( dp, rm ) {
var n = new BigNumber(this);
if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {
round( n, ~~dp + this.e + 1, rm == null ||
!isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );
}
return n;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber shifted by k places
* (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
*
* k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
*
* If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
* otherwise.
*
* 'shift() argument not an integer: {k}'
* 'shift() argument out of range: {k}'
*/
P.shift = function (k) {
var n = this;
return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )
// k < 1e+21, or truncate(k) will produce exponential notation.
? n.times( '1e' + truncate(k) )
: new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )
? n.s * ( k < 0 ? 0 : 1 / 0 )
: n );
};
/*
* sqrt(-n) = N
* sqrt( N) = N
* sqrt(-I) = N
* sqrt( I) = I
* sqrt( 0) = 0
* sqrt(-0) = -0
*
* Return a new BigNumber whose value is the square root of the value of this BigNumber,
* rounded according to DECIMAL_PLACES and ROUNDING_MODE.
*/
P.squareRoot = P.sqrt = function () {
var m, n, r, rep, t,
x = this,
c = x.c,
s = x.s,
e = x.e,
dp = DECIMAL_PLACES + 4,
half = new BigNumber('0.5');
// Negative/NaN/Infinity/zero?
if ( s !== 1 || !c || !c[0] ) {
return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );
}
// Initial estimate.
s = Math.sqrt( +x );
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if ( s == 0 || s == 1 / 0 ) {
n = coeffToString(c);
if ( ( n.length + e ) % 2 == 0 ) n += '0';
s = Math.sqrt(n);
e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );
if ( s == 1 / 0 ) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice( 0, n.indexOf('e') + 1 ) + e;
}
r = new BigNumber(n);
} else {
r = new BigNumber( s + '' );
}
// Check for zero.
// r could be zero if MIN_EXP is changed after the this value was created.
// This would cause a division by zero (x/t) and hence Infinity below, which would cause
// coeffToString to throw.
if ( r.c[0] ) {
e = r.e;
s = e + dp;
if ( s < 3 ) s = 0;
// Newton-Raphson iteration.
for ( ; ; ) {
t = r;
r = half.times( t.plus( div( x, t, dp, 1 ) ) );
if ( coeffToString( t.c ).slice( 0, s ) === ( n =
coeffToString( r.c ) ).slice( 0, s ) ) {
// The exponent of r may here be one less than the final result exponent,
// e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
// are indexed correctly.
if ( r.e < e ) --s;
n = n.slice( s - 3, s + 1 );
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits
// are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
// iteration.
if ( n == '9999' || !rep && n == '4999' ) {
// On the first iteration only, check to see if rounding up gives the
// exact result as the nines may infinitely repeat.
if ( !rep ) {
round( t, t.e + DECIMAL_PLACES + 2, 0 );
if ( t.times(t).eq(x) ) {
r = t;
break;
}
}
dp += 4;
s += 4;
rep = 1;
} else {
// If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
// result. If not, then there are further digits and m will be truthy.
if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {
// Truncate to the first rounding digit.
round( r, r.e + DECIMAL_PLACES + 2, 1 );
m = !r.times(r).eq(x);
}
break;
}
}
}
}
return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );
};
/*
* n * 0 = 0
* n * N = N
* n * I = I
* 0 * n = 0
* 0 * 0 = 0
* 0 * N = N
* 0 * I = N
* N * n = N
* N * 0 = N
* N * N = N
* N * I = N
* I * n = I
* I * 0 = N
* I * N = N
* I * I = I
*
* Return a new BigNumber whose value is the value of this BigNumber times the value of
* BigNumber(y, b).
*/
P.times = P.mul = function ( y, b ) {
var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,
base, sqrtBase,
x = this,
xc = x.c,
yc = ( id = 17, y = new BigNumber( y, b ) ).c;
// Either NaN, ±Infinity or ±0?
if ( !xc || !yc || !xc[0] || !yc[0] ) {
// Return NaN if either is NaN, or one is 0 and the other is Infinity.
if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {
y.c = y.e = y.s = null;
} else {
y.s *= x.s;
// Return ±Infinity if either is ±Infinity.
if ( !xc || !yc ) {
y.c = y.e = null;
// Return ±0 if either is ±0.
} else {
y.c = [0];
y.e = 0;
}
}
return y;
}
e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );
y.s *= x.s;
xcL = xc.length;
ycL = yc.length;
// Ensure xc points to longer array and xcL to its length.
if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;
// Initialise the result array with zeros.
for ( i = xcL + ycL, zc = []; i--; zc.push(0) );
base = BASE;
sqrtBase = SQRT_BASE;
for ( i = ycL; --i >= 0; ) {
c = 0;
ylo = yc[i] % sqrtBase;
yhi = yc[i] / sqrtBase | 0;
for ( k = xcL, j = i + k; j > i; ) {
xlo = xc[--k] % sqrtBase;
xhi = xc[k] / sqrtBase | 0;
m = yhi * xlo + xhi * ylo;
xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;
c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;
zc[j--] = xlo % base;
}
zc[j] = c;
}
if (c) {
++e;
} else {
zc.splice(0, 1);
}
return normalise( y, zc, e );
};
/*
* Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
* sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toDigits() precision out of range: {sd}'
* 'toDigits() precision not an integer: {sd}'
* 'toDigits() rounding mode not an integer: {rm}'
* 'toDigits() rounding mode out of range: {rm}'
*/
P.toDigits = function ( sd, rm ) {
var n = new BigNumber(this);
sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;
rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;
return sd ? round( n, sd, rm ) : n;
};
/*
* Return a string representing the value of this BigNumber in exponential notation and
* rounded using ROUNDING_MODE to dp fixed decimal places.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toExponential() decimal places not an integer: {dp}'
* 'toExponential() decimal places out of range: {dp}'
* 'toExponential() rounding mode not an integer: {rm}'
* 'toExponential() rounding mode out of range: {rm}'
*/
P.toExponential = function ( dp, rm ) {
return format( this,
dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounding
* to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
*
* Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
* but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFixed() decimal places not an integer: {dp}'
* 'toFixed() decimal places out of range: {dp}'
* 'toFixed() rounding mode not an integer: {rm}'
* 'toFixed() rounding mode out of range: {rm}'
*/
P.toFixed = function ( dp, rm ) {
return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )
? ~~dp + this.e + 1 : null, rm, 20 );
};
/*
* Return a string representing the value of this BigNumber in fixed-point notation rounded
* using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
* of the FORMAT object (see BigNumber.config).
*
* FORMAT = {
* decimalSeparator : '.',
* groupSeparator : ',',
* groupSize : 3,
* secondaryGroupSize : 0,
* fractionGroupSeparator : '\xA0', // non-breaking space
* fractionGroupSize : 0
* };
*
* [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toFormat() decimal places not an integer: {dp}'
* 'toFormat() decimal places out of range: {dp}'
* 'toFormat() rounding mode not an integer: {rm}'
* 'toFormat() rounding mode out of range: {rm}'
*/
P.toFormat = function ( dp, rm ) {
var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )
? ~~dp + this.e + 1 : null, rm, 21 );
if ( this.c ) {
var i,
arr = str.split('.'),
g1 = +FORMAT.groupSize,
g2 = +FORMAT.secondaryGroupSize,
groupSeparator = FORMAT.groupSeparator,
intPart = arr[0],
fractionPart = arr[1],
isNeg = this.s < 0,
intDigits = isNeg ? intPart.slice(1) : intPart,
len = intDigits.length;
if (g2) i = g1, g1 = g2, g2 = i, len -= i;
if ( g1 > 0 && len > 0 ) {
i = len % g1 || g1;
intPart = intDigits.substr( 0, i );
for ( ; i < len; i += g1 ) {
intPart += groupSeparator + intDigits.substr( i, g1 );
}
if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);
if (isNeg) intPart = '-' + intPart;
}
str = fractionPart
? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )
? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),
'$&' + FORMAT.fractionGroupSeparator )
: fractionPart )
: intPart;
}
return str;
};
/*
* Return a string array representing the value of this BigNumber as a simple fraction with
* an integer numerator and an integer denominator. The denominator will be a positive
* non-zero value less than or equal to the specified maximum denominator. If a maximum
* denominator is not specified, the denominator will be the lowest value necessary to
* represent the number exactly.
*
* [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
*
* 'toFraction() max denominator not an integer: {md}'
* 'toFraction() max denominator out of range: {md}'
*/
P.toFraction = function (md) {
var arr, d0, d2, e, exp, n, n0, q, s,
k = ERRORS,
x = this,
xc = x.c,
d = new BigNumber(ONE),
n1 = d0 = new BigNumber(ONE),
d1 = n0 = new BigNumber(ONE);
if ( md != null ) {
ERRORS = false;
n = new BigNumber(md);
ERRORS = k;
if ( !( k = n.isInt() ) || n.lt(ONE) ) {
if (ERRORS) {
raise( 22,
'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );
}
// ERRORS is false:
// If md is a finite non-integer >= 1, round it to an integer and use it.
md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;
}
}
if ( !xc ) return x.toString();
s = coeffToString(xc);
// Determine initial denominator.
// d is a power of 10 and the minimum max denominator that specifies the value exactly.
e = d.e = s.length - x.e - 1;
d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];
md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;
exp = MAX_EXP;
MAX_EXP = 1 / 0;
n = new BigNumber(s);
// n0 = d1 = 0
n0.c[0] = 0;
for ( ; ; ) {
q = div( n, d, 0, 1 );
d2 = d0.plus( q.times(d1) );
if ( d2.cmp(md) == 1 ) break;
d0 = d1;
d1 = d2;
n1 = n0.plus( q.times( d2 = n1 ) );
n0 = d2;
d = n.minus( q.times( d2 = d ) );
n = d2;
}
d2 = div( md.minus(d0), d1, 0, 1 );
n0 = n0.plus( d2.times(n1) );
d0 = d0.plus( d2.times(d1) );
n0.s = n1.s = x.s;
e *= 2;
// Determine which fraction is closer to x, n0/d0 or n1/d1
arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(
div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1
? [ n1.toString(), d1.toString() ]
: [ n0.toString(), d0.toString() ];
MAX_EXP = exp;
return arr;
};
/*
* Return the value of this BigNumber converted to a number primitive.
*/
P.toNumber = function () {
return +this;
};
/*
* Return a BigNumber whose value is the value of this BigNumber raised to the power n.
* If m is present, return the result modulo m.
* If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
* If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
* ROUNDING_MODE.
*
* The modular power operation works efficiently when x, n, and m are positive integers,
* otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
*
* n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
* [m] {number|string|BigNumber} The modulus.
*
* 'pow() exponent not an integer: {n}'
* 'pow() exponent out of range: {n}'
*
* Performs 54 loop iterations for n of 9007199254740991.
*/
P.toPower = P.pow = function ( n, m ) {
var k, y, z,
i = mathfloor( n < 0 ? -n : +n ),
x = this;
if ( m != null ) {
id = 23;
m = new BigNumber(m);
}
// Pass ±Infinity to Math.pow if exponent is out of range.
if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&
( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||
parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {
k = Math.pow( +x, n );
return new BigNumber( m ? k % m : k );
}
if (m) {
if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {
x = x.mod(m);
} else {
z = m;
// Nullify m so only a single mod operation is performed at the end.
m = null;
}
} else if (POW_PRECISION) {
// Truncating each coefficient array to a length of k after each multiplication
// equates to truncating significant digits to POW_PRECISION + [28, 41],
// i.e. there will be a minimum of 28 guard digits retained.
// (Using + 1.5 would give [9, 21] guard digits.)
k = mathceil( POW_PRECISION / LOG_BASE + 2 );
}
y = new BigNumber(ONE);
for ( ; ; ) {
if ( i % 2 ) {
y = y.times(x);
if ( !y.c ) break;
if (k) {
if ( y.c.length > k ) y.c.length = k;
} else if (m) {
y = y.mod(m);
}
}
i = mathfloor( i / 2 );
if ( !i ) break;
x = x.times(x);
if (k) {
if ( x.c && x.c.length > k ) x.c.length = k;
} else if (m) {
x = x.mod(m);
}
}
if (m) return y;
if ( n < 0 ) y = ONE.div(y);
return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;
};
/*
* Return a string representing the value of this BigNumber rounded to sd significant digits
* using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
* necessary to represent the integer part of the value in fixed-point notation, then use
* exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toPrecision() precision not an integer: {sd}'
* 'toPrecision() precision out of range: {sd}'
* 'toPrecision() rounding mode not an integer: {rm}'
* 'toPrecision() rounding mode out of range: {rm}'
*/
P.toPrecision = function ( sd, rm ) {
return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )
? sd | 0 : null, rm, 24 );
};
/*
* Return a string representing the value of this BigNumber in base b, or base 10 if b is
* omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
* ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
* that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
* TO_EXP_NEG, return exponential notation.
*
* [b] {number} Integer, 2 to 64 inclusive.
*
* 'toString() base not an integer: {b}'
* 'toString() base out of range: {b}'
*/
P.toString = function (b) {
var str,
n = this,
s = n.s,
e = n.e;
// Infinity or NaN?
if ( e === null ) {
if (s) {
str = 'Infinity';
if ( s < 0 ) str = '-' + str;
} else {
str = 'NaN';
}
} else {
str = coeffToString( n.c );
if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
} else {
str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );
}
if ( s < 0 && n.c[0] ) str = '-' + str;
}
return str;
};
/*
* Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
* number.
*/
P.truncated = P.trunc = function () {
return round( new BigNumber(this), this.e + 1, 1 );
};
/*
* Return as toString, but do not accept a base argument, and include the minus sign for
* negative zero.
*/
P.valueOf = P.toJSON = function () {
var str,
n = this,
e = n.e;
if ( e === null ) return n.toString();
str = coeffToString( n.c );
str = e <= TO_EXP_NEG || e >= TO_EXP_POS
? toExponential( str, e )
: toFixedPoint( str, e );
return n.s < 0 ? '-' + str : str;
};
P.isBigNumber = true;
if ( config != null ) BigNumber.config(config);
return BigNumber;
}
// PRIVATE HELPER FUNCTIONS
function bitFloor(n) {
var i = n | 0;
return n > 0 || n === i ? i : i - 1;
}
// Return a coefficient array as a string of base 10 digits.
function coeffToString(a) {
var s, z,
i = 1,
j = a.length,
r = a[0] + '';
for ( ; i < j; ) {
s = a[i++] + '';
z = LOG_BASE - s.length;
for ( ; z--; s = '0' + s );
r += s;
}
// Determine trailing zeros.
for ( j = r.length; r.charCodeAt(--j) === 48; );
return r.slice( 0, j + 1 || 1 );
}
// Compare the value of BigNumbers x and y.
function compare( x, y ) {
var a, b,
xc = x.c,
yc = y.c,
i = x.s,
j = y.s,
k = x.e,
l = y.e;
// Either NaN?
if ( !i || !j ) return null;
a = xc && !xc[0];
b = yc && !yc[0];
// Either zero?
if ( a || b ) return a ? b ? 0 : -j : i;
// Signs differ?
if ( i != j ) return i;
a = i < 0;
b = k == l;
// Either Infinity?
if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;
// Compare exponents.
if ( !b ) return k > l ^ a ? 1 : -1;
j = ( k = xc.length ) < ( l = yc.length ) ? k : l;
// Compare digit by digit.
for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;
// Compare lengths.
return k == l ? 0 : k > l ^ a ? 1 : -1;
}
/*
* Return true if n is a valid number in range, otherwise false.
* Use for argument validation when ERRORS is false.
* Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
*/
function intValidatorNoErrors( n, min, max ) {
return ( n = truncate(n) ) >= min && n <= max;
}
function isArray(obj) {
return Object.prototype.toString.call(obj) == '[object Array]';
}
/*
* Convert string of baseIn to an array of numbers of baseOut.
* Eg. convertBase('255', 10, 16) returns [15, 15].
* Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
*/
function toBaseOut( str, baseIn, baseOut ) {
var j,
arr = [0],
arrL,
i = 0,
len = str.length;
for ( ; i < len; ) {
for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );
arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );
for ( ; j < arr.length; j++ ) {
if ( arr[j] > baseOut - 1 ) {
if ( arr[j + 1] == null ) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
function toExponential( str, e ) {
return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +
( e < 0 ? 'e' : 'e+' ) + e;
}
function toFixedPoint( str, e ) {
var len, z;
// Negative exponent?
if ( e < 0 ) {
// Prepend zeros.
for ( z = '0.'; ++e; z += '0' );
str = z + str;
// Positive exponent
} else {
len = str.length;
// Append zeros.
if ( ++e > len ) {
for ( z = '0', e -= len; --e; z += '0' );
str += z;
} else if ( e < len ) {
str = str.slice( 0, e ) + '.' + str.slice(e);
}
}
return str;
}
function truncate(n) {
n = parseFloat(n);
return n < 0 ? mathceil(n) : mathfloor(n);
}
// EXPORT
BigNumber = constructorFactory();
BigNumber['default'] = BigNumber.BigNumber = BigNumber;
// AMD.
if ( true ) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () { return BigNumber; }).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
// Node.js and other environments that support module.exports.
} else if ( typeof module != 'undefined' && module.exports ) {
module.exports = BigNumber;
// Browser.
} else {
if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();
globalObj.BigNumber = BigNumber;
}
})(this);
/***/ }),
/* 7 */
/***/ (function(module, exports) {
var g;
// This works in non-strict mode
g = (function() {
return this;
})();
try {
// This works if eval is allowed (see CSP)
g = g || Function("return this")() || (1,eval)("this");
} catch(e) {
// This works if the window reference is available
if(typeof window === "object")
g = window;
}
// g can still be undefined, but nothing to do about it...
// We return undefined, instead of nothing here, so it's
// easier to handle this case. if(!global) { ...}
module.exports = g;
/***/ }),
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
/* eslint-disable node/no-deprecated-api */
var buffer = __webpack_require__(5)
var Buffer = buffer.Buffer
// alternative to using Object.keys for old browsers
function copyProps (src, dst) {
for (var key in src) {
dst[key] = src[key]
}
}
if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
module.exports = buffer
} else {
// Copy properties from require('buffer')
copyProps(buffer, exports)
exports.Buffer = SafeBuffer
}
function SafeBuffer (arg, encodingOrOffset, length) {
return Buffer(arg, encodingOrOffset, length)
}
// Copy static methods from Buffer
copyProps(Buffer, SafeBuffer)
SafeBuffer.from = function (arg, encodingOrOffset, length) {
if (typeof arg === 'number') {
throw new TypeError('Argument must not be a number')
}
return Buffer(arg, encodingOrOffset, length)
}
SafeBuffer.alloc = function (size, fill, encoding) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
var buf = Buffer(size)
if (fill !== undefined) {
if (typeof encoding === 'string') {
buf.fill(fill, encoding)
} else {
buf.fill(fill)
}
} else {
buf.fill(0)
}
return buf
}
SafeBuffer.allocUnsafe = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return Buffer(size)
}
SafeBuffer.allocUnsafeSlow = function (size) {
if (typeof size !== 'number') {
throw new TypeError('Argument must be a number')
}
return buffer.SlowBuffer(size)
}
/***/ }),
/* 9 */
/***/ (function(module, exports) {
// shim for using process in browser
var process = module.exports = {};
// cached from whatever global is present so that test runners that stub it
// don't break things. But we need to wrap it in a try catch in case it is
// wrapped in strict mode code which doesn't define any globals. It's inside a
// function because try/catches deoptimize in certain engines.
var cachedSetTimeout;
var cachedClearTimeout;
function defaultSetTimout() {
throw new Error('setTimeout has not been defined');
}
function defaultClearTimeout () {
throw new Error('clearTimeout has not been defined');
}
(function () {
try {
if (typeof setTimeout === 'function') {
cachedSetTimeout = setTimeout;
} else {
cachedSetTimeout = defaultSetTimout;
}
} catch (e) {
cachedSetTimeout = defaultSetTimout;
}
try {
if (typeof clearTimeout === 'function') {
cachedClearTimeout = clearTimeout;
} else {
cachedClearTimeout = defaultClearTimeout;
}
} catch (e) {
cachedClearTimeout = defaultClearTimeout;
}
} ())
function runTimeout(fun) {
if (cachedSetTimeout === setTimeout) {
//normal enviroments in sane situations
return setTimeout(fun, 0);
}
// if setTimeout wasn't available but was latter defined
if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
cachedSetTimeout = setTimeout;
return setTimeout(fun, 0);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedSetTimeout(fun, 0);
} catch(e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedSetTimeout.call(null, fun, 0);
} catch(e){
// 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
return cachedSetTimeout.call(this, fun, 0);
}
}
}
function runClearTimeout(marker) {
if (cachedClearTimeout === clearTimeout) {
//normal enviroments in sane situations
return clearTimeout(marker);
}
// if clearTimeout wasn't available but was latter defined
if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
cachedClearTimeout = clearTimeout;
return clearTimeout(marker);
}
try {
// when when somebody has screwed with setTimeout but no I.E. maddness
return cachedClearTimeout(marker);
} catch (e){
try {
// When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
return cachedClearTimeout.call(null, marker);
} catch (e){
// 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.
// Some versions of I.E. have different rules for clearTimeout vs setTimeout
return cachedClearTimeout.call(this, marker);
}
}
}
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
if (!draining || !currentQueue) {
return;
}
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = runTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
runClearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
runTimeout(drainQueue);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.prependListener = noop;
process.prependOnceListener = noop;
process.listeners = function (name) { return [] }
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
/***/ }),
/* 10 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assert = __webpack_require__(2);
function signum(a, b) {
return a < b ? -1 : a === b ? 0 : 1;}
var hexLookup = function () {
var res = {};
var reverse = res.reverse = new Array(256);
for (var i = 0; i < 16; i++) {
var char = i.toString(16).toUpperCase();
res[char] = i;
for (var j = 0; j < 16; j++) {
var char2 = j.toString(16).toUpperCase();
var byte = (i << 4) + j;
var byteHex = char + char2;
res[byteHex] = byte;
reverse[byte] = byteHex;}}
return res;}();
var reverseHexLookup = hexLookup.reverse;
function bytesToHex(sequence) {
var buf = Array(sequence.length);
for (var i = sequence.length - 1; i >= 0; i--) {
buf[i] = reverseHexLookup[sequence[i]];}
return buf.join('');}
function byteForHex(hex) {
var byte = hexLookup[hex];
if (byte === undefined) {
throw new Error('`' + hex + '` is not a valid hex representation of a byte');}
return byte;}
function parseBytes(val) {var Output = arguments.length <= 1 || arguments[1] === undefined ? Array : arguments[1];
if (!val || val.length === undefined) {
throw new Error(val + ' is not a sequence');}
if (typeof val === 'string') {
var start = val.length % 2;
var _res = new Output((val.length + start) / 2);
for (var i = val.length, to = _res.length - 1; to >= start; i -= 2, to--) {
_res[to] = byteForHex(val.slice(i - 2, i));}
if (start === 1) {
_res[0] = byteForHex(val[0]);}
return _res;} else
if (val instanceof Output) {
return val;} else
if (Output === Uint8Array) {
return new Output(val);}
var res = new Output(val.length);
for (var _i = val.length - 1; _i >= 0; _i--) {
res[_i] = val[_i];}
return res;}
function serializeUIntN(val, width) {
var newBytes = new Uint8Array(width);
var lastIx = width - 1;
for (var i = 0; i < width; i++) {
newBytes[lastIx - i] = val >>> i * 8 & 0xff;}
return newBytes;}
function compareBytes(a, b) {
assert(a.length === b.length);
for (var i = 0; i < a.length; i++) {
var cmp = signum(a[i], b[i]);
if (cmp !== 0) {
return cmp;}}
return 0;}
function slice(val) {var startIx = arguments.length <= 1 || arguments[1] === undefined ? 0 : arguments[1];var endIx = arguments.length <= 2 || arguments[2] === undefined ? val.length : arguments[2];var Output = arguments.length <= 3 || arguments[3] === undefined ? val.constructor : arguments[3];
/* eslint-disable no-param-reassign*/
if (startIx < 0) {
startIx += val.length;}
if (endIx < 0) {
endIx += val.length;}
/* eslint-enable no-param-reassign*/
var len = endIx - startIx;
var res = new Output(len);
for (var i = endIx - 1; i >= startIx; i--) {
res[i - startIx] = val[i];}
return res;}
module.exports = {
parseBytes: parseBytes,
bytesToHex: bytesToHex,
slice: slice,
compareBytes: compareBytes,
serializeUIntN: serializeUIntN };
/***/ }),
/* 11 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", { value: true });
const bignumber_js_1 = __webpack_require__(6);
const common = __webpack_require__(0);
exports.common = common;
const txFlags = common.txFlags;
function formatPrepareResponse(txJSON) {
const instructions = {
fee: common.dropsToXrp(txJSON.Fee),
sequence: txJSON.Sequence,
maxLedgerVersion: txJSON.LastLedgerSequence === undefined ?
null : txJSON.LastLedgerSequence
};
return {
txJSON: JSON.stringify(txJSON),
instructions
};
}
function setCanonicalFlag(txJSON) {
txJSON.Flags |= txFlags.Universal.FullyCanonicalSig;
// JavaScript converts operands to 32-bit signed ints before doing bitwise
// operations. We need to convert it back to an unsigned int.
txJSON.Flags = txJSON.Flags >>> 0;
}
function scaleValue(value, multiplier, extra = 0) {
return (new bignumber_js_1.default(value)).times(multiplier).plus(extra).toString();
}
function prepareTransaction(txJSON, api, instructions) {
common.validate.instructions(instructions);
const account = txJSON.Account;
setCanonicalFlag(txJSON);
function prepareMaxLedgerVersion() {
if (instructions.maxLedgerVersion !== undefined) {
if (instructions.maxLedgerVersion !== null) {
txJSON.LastLedgerSequence = instructions.maxLedgerVersion;
}
return Promise.resolve(txJSON);
}
const offset = instructions.maxLedgerVersionOffset !== undefined ?
instructions.maxLedgerVersionOffset : 3;
return api.connection.getLedgerVersion().then(ledgerVersion => {
txJSON.LastLedgerSequence = ledgerVersion + offset;
return txJSON;
});
}
function prepareFee() {
const multiplier = instructions.signersCount === undefined ? 1 :
instructions.signersCount + 1;
if (instructions.fee !== undefined) {
txJSON.Fee = scaleValue(common.xrpToDrops(instructions.fee), multiplier);
return Promise.resolve(txJSON);
}
const cushion = api._feeCushion;
return common.serverInfo.getFee(api.connection, cushion).then(fee => {
return api.connection.getFeeRef().then(feeRef => {
const extraFee = (txJSON.TransactionType !== 'EscrowFinish' ||
txJSON.Fulfillment === undefined) ? 0 :
(cushion * feeRef * (32 + Math.floor(new Buffer(txJSON.Fulfillment, 'hex').length / 16)));
const feeDrops = common.xrpToDrops(fee);
if (instructions.maxFee !== undefined) {
const maxFeeDrops = common.xrpToDrops(instructions.maxFee);
const normalFee = scaleValue(feeDrops, multiplier, extraFee);
txJSON.Fee = bignumber_js_1.default.min(normalFee, maxFeeDrops).toString();
}
else {
txJSON.Fee = scaleValue(feeDrops, multiplier, extraFee);
}
return txJSON;
});
});
}
function prepareSequence() {
if (instructions.sequence !== undefined) {
txJSON.Sequence = instructions.sequence;
return Promise.resolve(txJSON);
}
const request = {
command: 'account_info',
account: account
};
return api.connection.request(request).then(response => {
txJSON.Sequence = response.account_data.Sequence;
return txJSON;
});
}
return Promise.all([
prepareMaxLedgerVersion(),
prepareFee(),
prepareSequence()
]).then(() => formatPrepareResponse(txJSON));
}
exports.prepareTransaction = prepareTransaction;
function convertStringToHex(string) {
return new Buffer(string, 'utf8').toString('hex').toUpperCase();
}
exports.convertStringToHex = convertStringToHex;
function convertMemo(memo) {
return {
Memo: common.removeUndefined({
MemoData: memo.data ? convertStringToHex(memo.data) : undefined,
MemoType: memo.type ? convertStringToHex(memo.type) : undefined,
MemoFormat: memo.format ? convertStringToHex(memo.format) : undefined
})
};
}
exports.convertMemo = convertMemo;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 12 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var elliptic = exports;
elliptic.version = __webpack_require__(123).version;
elliptic.utils = __webpack_require__(124);
elliptic.rand = __webpack_require__(62);
elliptic.hmacDRBG = __webpack_require__(125);
elliptic.curve = __webpack_require__(41);
elliptic.curves = __webpack_require__(130);
// Protocols
elliptic.ec = __webpack_require__(132);
elliptic.eddsa = __webpack_require__(135);
/***/ }),
/* 13 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const transactionParser = __webpack_require__(268);
const bignumber_js_1 = __webpack_require__(6);
const common = __webpack_require__(0);
const amount_1 = __webpack_require__(16);
function adjustQualityForXRP(quality, takerGetsCurrency, takerPaysCurrency) {
// quality = takerPays.value/takerGets.value
// using drops (1e-6 XRP) for XRP values
const numeratorShift = (takerPaysCurrency === 'XRP' ? -6 : 0);
const denominatorShift = (takerGetsCurrency === 'XRP' ? -6 : 0);
const shift = numeratorShift - denominatorShift;
return shift === 0 ? quality :
(new bignumber_js_1.default(quality)).shift(shift).toString();
}
exports.adjustQualityForXRP = adjustQualityForXRP;
function parseQuality(quality) {
if (typeof quality !== 'number') {
return undefined;
}
return (new bignumber_js_1.default(quality)).shift(-9).toNumber();
}
exports.parseQuality = parseQuality;
function parseTimestamp(rippleTime) {
if (typeof rippleTime !== 'number') {
return undefined;
}
return common.rippleTimeToISO8601(rippleTime);
}
exports.parseTimestamp = parseTimestamp;
function removeEmptyCounterparty(amount) {
if (amount.counterparty === '') {
delete amount.counterparty;
}
}
function removeEmptyCounterpartyInBalanceChanges(balanceChanges) {
_.forEach(balanceChanges, changes => {
_.forEach(changes, removeEmptyCounterparty);
});
}
function removeEmptyCounterpartyInOrderbookChanges(orderbookChanges) {
_.forEach(orderbookChanges, changes => {
_.forEach(changes, change => {
_.forEach(change, removeEmptyCounterparty);
});
});
}
function isPartialPayment(tx) {
return (tx.Flags & common.txFlags.Payment.PartialPayment) !== 0;
}
exports.isPartialPayment = isPartialPayment;
function parseDeliveredAmount(tx) {
if (tx.TransactionType !== 'Payment' ||
tx.meta.TransactionResult !== 'tesSUCCESS') {
return undefined;
}
if (tx.meta.delivered_amount &&
tx.meta.delivered_amount === 'unavailable') {
return undefined;
}
// parsable delivered_amount
if (tx.meta.delivered_amount) {
return amount_1.default(tx.meta.delivered_amount);
}
// DeliveredAmount only present on partial payments
if (tx.meta.DeliveredAmount) {
return amount_1.default(tx.meta.DeliveredAmount);
}
// no partial payment flag, use tx.Amount
if (tx.Amount && !isPartialPayment(tx)) {
return amount_1.default(tx.Amount);
}
// DeliveredAmount field was introduced at
// ledger 4594095 - after that point its absence
// on a tx flagged as partial payment indicates
// the full amount was transferred. The amount
// transferred with a partial payment before
// that date must be derived from metadata.
if (tx.Amount && tx.ledger_index > 4594094) {
return amount_1.default(tx.Amount);
}
return undefined;
}
function parseOutcome(tx) {
const metadata = tx.meta || tx.metaData;
if (!metadata) {
return undefined;
}
const balanceChanges = transactionParser.parseBalanceChanges(metadata);
const orderbookChanges = transactionParser.parseOrderbookChanges(metadata);
removeEmptyCounterpartyInBalanceChanges(balanceChanges);
removeEmptyCounterpartyInOrderbookChanges(orderbookChanges);
return common.removeUndefined({
result: tx.meta.TransactionResult,
timestamp: parseTimestamp(tx.date),
fee: common.dropsToXrp(tx.Fee),
balanceChanges: balanceChanges,
orderbookChanges: orderbookChanges,
ledgerVersion: tx.ledger_index,
indexInLedger: tx.meta.TransactionIndex,
deliveredAmount: parseDeliveredAmount(tx)
});
}
exports.parseOutcome = parseOutcome;
function hexToString(hex) {
return hex ? new Buffer(hex, 'hex').toString('utf-8') : undefined;
}
exports.hexToString = hexToString;
function parseMemos(tx) {
if (!Array.isArray(tx.Memos) || tx.Memos.length === 0) {
return undefined;
}
return tx.Memos.map(m => {
return common.removeUndefined({
type: m.Memo.parsed_memo_type || hexToString(m.Memo.MemoType),
format: m.Memo.parsed_memo_format || hexToString(m.Memo.MemoFormat),
data: m.Memo.parsed_memo_data || hexToString(m.Memo.MemoData)
});
});
}
exports.parseMemos = parseMemos;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 14 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assert = __webpack_require__(34);
var inherits = __webpack_require__(3);
exports.inherits = inherits;
function toArray(msg, enc) {
if (Array.isArray(msg))
return msg.slice();
if (!msg)
return [];
var res = [];
if (typeof msg === 'string') {
if (!enc) {
for (var i = 0; i < msg.length; i++) {
var c = msg.charCodeAt(i);
var hi = c >> 8;
var lo = c & 0xff;
if (hi)
res.push(hi, lo);
else
res.push(lo);
}
} else if (enc === 'hex') {
msg = msg.replace(/[^a-z0-9]+/ig, '');
if (msg.length % 2 !== 0)
msg = '0' + msg;
for (i = 0; i < msg.length; i += 2)
res.push(parseInt(msg[i] + msg[i + 1], 16));
}
} else {
for (i = 0; i < msg.length; i++)
res[i] = msg[i] | 0;
}
return res;
}
exports.toArray = toArray;
function toHex(msg) {
var res = '';
for (var i = 0; i < msg.length; i++)
res += zero2(msg[i].toString(16));
return res;
}
exports.toHex = toHex;
function htonl(w) {
var res = (w >>> 24) |
((w >>> 8) & 0xff00) |
((w << 8) & 0xff0000) |
((w & 0xff) << 24);
return res >>> 0;
}
exports.htonl = htonl;
function toHex32(msg, endian) {
var res = '';
for (var i = 0; i < msg.length; i++) {
var w = msg[i];
if (endian === 'little')
w = htonl(w);
res += zero8(w.toString(16));
}
return res;
}
exports.toHex32 = toHex32;
function zero2(word) {
if (word.length === 1)
return '0' + word;
else
return word;
}
exports.zero2 = zero2;
function zero8(word) {
if (word.length === 7)
return '0' + word;
else if (word.length === 6)
return '00' + word;
else if (word.length === 5)
return '000' + word;
else if (word.length === 4)
return '0000' + word;
else if (word.length === 3)
return '00000' + word;
else if (word.length === 2)
return '000000' + word;
else if (word.length === 1)
return '0000000' + word;
else
return word;
}
exports.zero8 = zero8;
function join32(msg, start, end, endian) {
var len = end - start;
assert(len % 4 === 0);
var res = new Array(len / 4);
for (var i = 0, k = start; i < res.length; i++, k += 4) {
var w;
if (endian === 'big')
w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
else
w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
res[i] = w >>> 0;
}
return res;
}
exports.join32 = join32;
function split32(msg, endian) {
var res = new Array(msg.length * 4);
for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
var m = msg[i];
if (endian === 'big') {
res[k] = m >>> 24;
res[k + 1] = (m >>> 16) & 0xff;
res[k + 2] = (m >>> 8) & 0xff;
res[k + 3] = m & 0xff;
} else {
res[k + 3] = m >>> 24;
res[k + 2] = (m >>> 16) & 0xff;
res[k + 1] = (m >>> 8) & 0xff;
res[k] = m & 0xff;
}
}
return res;
}
exports.split32 = split32;
function rotr32(w, b) {
return (w >>> b) | (w << (32 - b));
}
exports.rotr32 = rotr32;
function rotl32(w, b) {
return (w << b) | (w >>> (32 - b));
}
exports.rotl32 = rotl32;
function sum32(a, b) {
return (a + b) >>> 0;
}
exports.sum32 = sum32;
function sum32_3(a, b, c) {
return (a + b + c) >>> 0;
}
exports.sum32_3 = sum32_3;
function sum32_4(a, b, c, d) {
return (a + b + c + d) >>> 0;
}
exports.sum32_4 = sum32_4;
function sum32_5(a, b, c, d, e) {
return (a + b + c + d + e) >>> 0;
}
exports.sum32_5 = sum32_5;
function sum64(buf, pos, ah, al) {
var bh = buf[pos];
var bl = buf[pos + 1];
var lo = (al + bl) >>> 0;
var hi = (lo < al ? 1 : 0) + ah + bh;
buf[pos] = hi >>> 0;
buf[pos + 1] = lo;
}
exports.sum64 = sum64;
function sum64_hi(ah, al, bh, bl) {
var lo = (al + bl) >>> 0;
var hi = (lo < al ? 1 : 0) + ah + bh;
return hi >>> 0;
}
exports.sum64_hi = sum64_hi;
function sum64_lo(ah, al, bh, bl) {
var lo = al + bl;
return lo >>> 0;
}
exports.sum64_lo = sum64_lo;
function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
var carry = 0;
var lo = al;
lo = (lo + bl) >>> 0;
carry += lo < al ? 1 : 0;
lo = (lo + cl) >>> 0;
carry += lo < cl ? 1 : 0;
lo = (lo + dl) >>> 0;
carry += lo < dl ? 1 : 0;
var hi = ah + bh + ch + dh + carry;
return hi >>> 0;
}
exports.sum64_4_hi = sum64_4_hi;
function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
var lo = al + bl + cl + dl;
return lo >>> 0;
}
exports.sum64_4_lo = sum64_4_lo;
function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
var carry = 0;
var lo = al;
lo = (lo + bl) >>> 0;
carry += lo < al ? 1 : 0;
lo = (lo + cl) >>> 0;
carry += lo < cl ? 1 : 0;
lo = (lo + dl) >>> 0;
carry += lo < dl ? 1 : 0;
lo = (lo + el) >>> 0;
carry += lo < el ? 1 : 0;
var hi = ah + bh + ch + dh + eh + carry;
return hi >>> 0;
}
exports.sum64_5_hi = sum64_5_hi;
function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
var lo = al + bl + cl + dl + el;
return lo >>> 0;
}
exports.sum64_5_lo = sum64_5_lo;
function rotr64_hi(ah, al, num) {
var r = (al << (32 - num)) | (ah >>> num);
return r >>> 0;
}
exports.rotr64_hi = rotr64_hi;
function rotr64_lo(ah, al, num) {
var r = (ah << (32 - num)) | (al >>> num);
return r >>> 0;
}
exports.rotr64_lo = rotr64_lo;
function shr64_hi(ah, al, num) {
return ah >>> num;
}
exports.shr64_hi = shr64_hi;
function shr64_lo(ah, al, num) {
var r = (ah << (32 - num)) | (al >>> num);
return r >>> 0;
}
exports.shr64_lo = shr64_lo;
/***/ }),
/* 15 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(arg) {
if (Array.isArray) {
return Array.isArray(arg);
}
return objectToString(arg) === '[object Array]';
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return (objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = Buffer.isBuffer;
function objectToString(o) {
return Object.prototype.toString.call(o);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 16 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const common = __webpack_require__(0);
function parseAmount(amount) {
if (typeof amount === 'string') {
return {
currency: 'XRP',
value: common.dropsToXrp(amount)
};
}
return {
currency: amount.currency,
value: amount.value,
counterparty: amount.issuer
};
}
exports.default = parseAmount;
/***/ }),
/* 17 */
/***/ (function(module, exports) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
function EventEmitter() {
this._events = this._events || {};
this._maxListeners = this._maxListeners || undefined;
}
module.exports = EventEmitter;
// Backwards-compat with node 0.10.x
EventEmitter.EventEmitter = EventEmitter;
EventEmitter.prototype._events = undefined;
EventEmitter.prototype._maxListeners = undefined;
// By default EventEmitters will print a warning if more than 10 listeners are
// added to it. This is a useful default which helps finding memory leaks.
EventEmitter.defaultMaxListeners = 10;
// Obviously not all Emitters should be limited to 10. This function allows
// that to be increased. Set to zero for unlimited.
EventEmitter.prototype.setMaxListeners = function(n) {
if (!isNumber(n) || n < 0 || isNaN(n))
throw TypeError('n must be a positive number');
this._maxListeners = n;
return this;
};
EventEmitter.prototype.emit = function(type) {
var er, handler, len, args, i, listeners;
if (!this._events)
this._events = {};
// If there is no 'error' event listener then throw.
if (type === 'error') {
if (!this._events.error ||
(isObject(this._events.error) && !this._events.error.length)) {
er = arguments[1];
if (er instanceof Error) {
throw er; // Unhandled 'error' event
} else {
// At least give some kind of context to the user
var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
err.context = er;
throw err;
}
}
}
handler = this._events[type];
if (isUndefined(handler))
return false;
if (isFunction(handler)) {
switch (arguments.length) {
// fast cases
case 1:
handler.call(this);
break;
case 2:
handler.call(this, arguments[1]);
break;
case 3:
handler.call(this, arguments[1], arguments[2]);
break;
// slower
default:
args = Array.prototype.slice.call(arguments, 1);
handler.apply(this, args);
}
} else if (isObject(handler)) {
args = Array.prototype.slice.call(arguments, 1);
listeners = handler.slice();
len = listeners.length;
for (i = 0; i < len; i++)
listeners[i].apply(this, args);
}
return true;
};
EventEmitter.prototype.addListener = function(type, listener) {
var m;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events)
this._events = {};
// To avoid recursion in the case that type === "newListener"! Before
// adding it to the listeners, first emit "newListener".
if (this._events.newListener)
this.emit('newListener', type,
isFunction(listener.listener) ?
listener.listener : listener);
if (!this._events[type])
// Optimize the case of one listener. Don't need the extra array object.
this._events[type] = listener;
else if (isObject(this._events[type]))
// If we've already got an array, just append.
this._events[type].push(listener);
else
// Adding the second element, need to change to array.
this._events[type] = [this._events[type], listener];
// Check for listener leak
if (isObject(this._events[type]) && !this._events[type].warned) {
if (!isUndefined(this._maxListeners)) {
m = this._maxListeners;
} else {
m = EventEmitter.defaultMaxListeners;
}
if (m && m > 0 && this._events[type].length > m) {
this._events[type].warned = true;
console.error('(node) warning: possible EventEmitter memory ' +
'leak detected. %d listeners added. ' +
'Use emitter.setMaxListeners() to increase limit.',
this._events[type].length);
if (typeof console.trace === 'function') {
// not supported in IE 10
console.trace();
}
}
}
return this;
};
EventEmitter.prototype.on = EventEmitter.prototype.addListener;
EventEmitter.prototype.once = function(type, listener) {
if (!isFunction(listener))
throw TypeError('listener must be a function');
var fired = false;
function g() {
this.removeListener(type, g);
if (!fired) {
fired = true;
listener.apply(this, arguments);
}
}
g.listener = listener;
this.on(type, g);
return this;
};
// emits a 'removeListener' event iff the listener was removed
EventEmitter.prototype.removeListener = function(type, listener) {
var list, position, length, i;
if (!isFunction(listener))
throw TypeError('listener must be a function');
if (!this._events || !this._events[type])
return this;
list = this._events[type];
length = list.length;
position = -1;
if (list === listener ||
(isFunction(list.listener) && list.listener === listener)) {
delete this._events[type];
if (this._events.removeListener)
this.emit('removeListener', type, listener);
} else if (isObject(list)) {
for (i = length; i-- > 0;) {
if (list[i] === listener ||
(list[i].listener && list[i].listener === listener)) {
position = i;
break;
}
}
if (position < 0)
return this;
if (list.length === 1) {
list.length = 0;
delete this._events[type];
} else {
list.splice(position, 1);
}
if (this._events.removeListener)
this.emit('removeListener', type, listener);
}
return this;
};
EventEmitter.prototype.removeAllListeners = function(type) {
var key, listeners;
if (!this._events)
return this;
// not listening for removeListener, no need to emit
if (!this._events.removeListener) {
if (arguments.length === 0)
this._events = {};
else if (this._events[type])
delete this._events[type];
return this;
}
// emit removeListener for all listeners on all events
if (arguments.length === 0) {
for (key in this._events) {
if (key === 'removeListener') continue;
this.removeAllListeners(key);
}
this.removeAllListeners('removeListener');
this._events = {};
return this;
}
listeners = this._events[type];
if (isFunction(listeners)) {
this.removeListener(type, listeners);
} else if (listeners) {
// LIFO order
while (listeners.length)
this.removeListener(type, listeners[listeners.length - 1]);
}
delete this._events[type];
return this;
};
EventEmitter.prototype.listeners = function(type) {
var ret;
if (!this._events || !this._events[type])
ret = [];
else if (isFunction(this._events[type]))
ret = [this._events[type]];
else
ret = this._events[type].slice();
return ret;
};
EventEmitter.prototype.listenerCount = function(type) {
if (this._events) {
var evlistener = this._events[type];
if (isFunction(evlistener))
return 1;
else if (evlistener)
return evlistener.length;
}
return 0;
};
EventEmitter.listenerCount = function(emitter, type) {
return emitter.listenerCount(type);
};
function isFunction(arg) {
return typeof arg === 'function';
}
function isNumber(arg) {
return typeof arg === 'number';
}
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
function isUndefined(arg) {
return arg === void 0;
}
/***/ }),
/* 18 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) {
'use strict';
// Utils
function assert(val, msg) {
if (!val)
throw new Error(msg || 'Assertion failed');
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN(number, base, endian) {
// May be `new BN(bn)` ?
if (number !== null &&
typeof number === 'object' &&
Array.isArray(number.words)) {
return number;
}
this.sign = false;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (base === 'le' || base === 'be') {
endian = base;
base = 10;
}
if (number !== null)
this._init(number || 0, base || 10, endian || 'be');
}
if (typeof module === 'object')
module.exports = BN;
else
exports.BN = BN;
BN.BN = BN;
BN.wordSize = 26;
BN.max = function max(left, right) {
if (left.cmp(right) > 0)
return left;
else
return right;
};
BN.min = function min(left, right) {
if (left.cmp(right) < 0)
return left;
else
return right;
};
BN.prototype._init = function init(number, base, endian) {
if (typeof number === 'number') {
return this._initNumber(number, base, endian);
} else if (typeof number === 'object') {
return this._initArray(number, base, endian);
}
if (base === 'hex')
base = 16;
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, '');
var start = 0;
if (number[0] === '-')
start++;
if (base === 16)
this._parseHex(number, start);
else
this._parseBase(number, base, start);
if (number[0] === '-')
this.sign = true;
this.strip();
if (endian !== 'le')
return;
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initNumber = function _initNumber(number, base, endian) {
if (number < 0) {
this.sign = true;
number = -number;
}
if (number < 0x4000000) {
this.words = [ number & 0x3ffffff ];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== 'le')
return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray(number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === 'number');
if (number.length <= 0) {
this.words = [ 0 ];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++)
this.words[i] = 0;
var off = 0;
if (endian === 'be') {
for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
} else if (endian === 'le') {
for (var i = 0, j = 0; i < number.length; i += 3) {
var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
}
return this.strip();
};
function parseHex(str, start, end) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r <<= 4;
// 'a' - 'f'
if (c >= 49 && c <= 54)
r |= c - 49 + 0xa;
// 'A' - 'F'
else if (c >= 17 && c <= 22)
r |= c - 17 + 0xa;
// '0' - '9'
else
r |= c & 0xf;
}
return r;
}
BN.prototype._parseHex = function _parseHex(number, start) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++)
this.words[i] = 0;
// Scan 24-bit chunks and add them to the number
var off = 0;
for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
var w = parseHex(number, i, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
if (i + 6 !== start) {
var w = parseHex(number, start, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
}
this.strip();
};
function parseBase(str, start, end, mul) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49)
r += c - 49 + 0xa;
// 'A'
else if (c >= 17)
r += c - 17 + 0xa;
// '0' - '9'
else
r += c;
}
return r;
}
BN.prototype._parseBase = function _parseBase(number, base, start) {
// Initialize as zero
this.words = [ 0 ];
this.length = 1;
// Find length of limb in base
for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
limbLen++;
limbLen--;
limbPow = (limbPow / base) | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for (var i = start; i < end; i += limbLen) {
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000)
this.words[0] += word;
else
this._iaddn(word);
}
if (mod !== 0) {
var pow = 1;
var word = parseBase(number, i, number.length, base);
for (var i = 0; i < mod; i++)
pow *= base;
this.imuln(pow);
if (this.words[0] + word < 0x4000000)
this.words[0] += word;
else
this._iaddn(word);
}
};
BN.prototype.copy = function copy(dest) {
dest.words = new Array(this.length);
for (var i = 0; i < this.length; i++)
dest.words[i] = this.words[i];
dest.length = this.length;
dest.sign = this.sign;
dest.red = this.red;
};
BN.prototype.clone = function clone() {
var r = new BN(null);
this.copy(r);
return r;
};
// Remove leading `0` from `this`
BN.prototype.strip = function strip() {
while (this.length > 1 && this.words[this.length - 1] === 0)
this.length--;
return this._normSign();
};
BN.prototype._normSign = function _normSign() {
// -0 = 0
if (this.length === 1 && this.words[0] === 0)
this.sign = false;
return this;
};
BN.prototype.inspect = function inspect() {
return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
};
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/
var zeros = [
'',
'0',
'00',
'000',
'0000',
'00000',
'000000',
'0000000',
'00000000',
'000000000',
'0000000000',
'00000000000',
'000000000000',
'0000000000000',
'00000000000000',
'000000000000000',
'0000000000000000',
'00000000000000000',
'000000000000000000',
'0000000000000000000',
'00000000000000000000',
'000000000000000000000',
'0000000000000000000000',
'00000000000000000000000',
'000000000000000000000000',
'0000000000000000000000000'
];
var groupSizes = [
0, 0,
25, 16, 12, 11, 10, 9, 8,
8, 7, 7, 7, 7, 6, 6,
6, 6, 6, 6, 6, 5, 5,
5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5
];
var groupBases = [
0, 0,
33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
];
BN.prototype.toString = function toString(base, padding) {
base = base || 10;
var padding = padding | 0 || 1;
if (base === 16 || base === 'hex') {
var out = '';
var off = 0;
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i];
var word = (((w << off) | carry) & 0xffffff).toString(16);
carry = (w >>> (24 - off)) & 0xffffff;
if (carry !== 0 || i !== this.length - 1)
out = zeros[6 - word.length] + word + out;
else
out = word + out;
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
}
if (carry !== 0)
out = carry.toString(16) + out;
while (out.length % padding !== 0)
out = '0' + out;
if (this.sign)
out = '-' + out;
return out;
} else if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
var out = '';
var c = this.clone();
c.sign = false;
while (c.cmpn(0) !== 0) {
var r = c.modn(groupBase).toString(base);
c = c.idivn(groupBase);
if (c.cmpn(0) !== 0)
out = zeros[groupSize - r.length] + r + out;
else
out = r + out;
}
if (this.cmpn(0) === 0)
out = '0' + out;
while (out.length % padding !== 0)
out = '0' + out;
if (this.sign)
out = '-' + out;
return out;
} else {
assert(false, 'Base should be between 2 and 36');
}
};
BN.prototype.toJSON = function toJSON() {
return this.toString(16);
};
BN.prototype.toArray = function toArray(endian, length) {
this.strip();
var littleEndian = endian === 'le';
var res = new Array(this.byteLength());
res[0] = 0;
var q = this.clone();
if (!littleEndian) {
// Assume big-endian
for (var i = 0; q.cmpn(0) !== 0; i++) {
var b = q.andln(0xff);
q.iushrn(8);
res[res.length - i - 1] = b;
}
} else {
for (var i = 0; q.cmpn(0) !== 0; i++) {
var b = q.andln(0xff);
q.iushrn(8);
res[i] = b;
}
}
if (length) {
assert(res.length <= length, 'byte array longer than desired length');
while (res.length < length) {
if (littleEndian)
res.push(0);
else
res.unshift(0);
}
}
return res;
};
if (Math.clz32) {
BN.prototype._countBits = function _countBits(w) {
return 32 - Math.clz32(w);
};
} else {
BN.prototype._countBits = function _countBits(w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
}
BN.prototype._zeroBits = function _zeroBits(w) {
// Short-cut
if (w === 0)
return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0)
r++;
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength() {
var hi = 0;
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray(num) {
var w = new Array(num.bitLength());
for (var bit = 0; bit < w.length; bit++) {
var off = (bit / 26) | 0;
var wbit = bit % 26;
w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits() {
if (this.cmpn(0) === 0)
return 0;
var r = 0;
for (var i = 0; i < this.length; i++) {
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26)
break;
}
return r;
};
BN.prototype.byteLength = function byteLength() {
return Math.ceil(this.bitLength() / 8);
};
// Return negative clone of `this`
BN.prototype.neg = function neg() {
if (this.cmpn(0) === 0)
return this.clone();
var r = this.clone();
r.sign = !this.sign;
return r;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor(num) {
while (this.length < num.length)
this.words[this.length++] = 0;
for (var i = 0; i < num.length; i++)
this.words[i] = this.words[i] | num.words[i];
return this.strip();
};
BN.prototype.ior = function ior(num) {
assert(!this.sign && !num.sign);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or(num) {
if (this.length > num.length)
return this.clone().ior(num);
else
return num.clone().ior(this);
};
BN.prototype.uor = function uor(num) {
if (this.length > num.length)
return this.clone().iuor(num);
else
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand(num) {
// b = min-length(num, this)
var b;
if (this.length > num.length)
b = num;
else
b = this;
for (var i = 0; i < b.length; i++)
this.words[i] = this.words[i] & num.words[i];
this.length = b.length;
return this.strip();
};
BN.prototype.iand = function iand(num) {
assert(!this.sign && !num.sign);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and(num) {
if (this.length > num.length)
return this.clone().iand(num);
else
return num.clone().iand(this);
};
BN.prototype.uand = function uand(num) {
if (this.length > num.length)
return this.clone().iuand(num);
else
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor(num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for (var i = 0; i < b.length; i++)
this.words[i] = a.words[i] ^ b.words[i];
if (this !== a)
for (; i < a.length; i++)
this.words[i] = a.words[i];
this.length = a.length;
return this.strip();
};
BN.prototype.ixor = function ixor(num) {
assert(!this.sign && !num.sign);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor(num) {
if (this.length > num.length)
return this.clone().ixor(num);
else
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor(num) {
if (this.length > num.length)
return this.clone().iuxor(num);
else
return num.clone().iuxor(this);
};
// Set `bit` of `this`
BN.prototype.setn = function setn(bit, val) {
assert(typeof bit === 'number' && bit >= 0);
var off = (bit / 26) | 0;
var wbit = bit % 26;
while (this.length <= off)
this.words[this.length++] = 0;
if (val)
this.words[off] = this.words[off] | (1 << wbit);
else
this.words[off] = this.words[off] & ~(1 << wbit);
return this.strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd(num) {
// negative + positive
if (this.sign && !num.sign) {
this.sign = false;
var r = this.isub(num);
this.sign = !this.sign;
return this._normSign();
// positive + negative
} else if (!this.sign && num.sign) {
num.sign = false;
var r = this.isub(num);
num.sign = true;
return r._normSign();
}
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
var r = a.words[i] + b.words[i] + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for (; carry !== 0 && i < a.length; i++) {
var r = a.words[i] + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) {
for (; i < a.length; i++)
this.words[i] = a.words[i];
}
return this;
};
// Add `num` to `this`
BN.prototype.add = function add(num) {
if (num.sign && !this.sign) {
num.sign = false;
var res = this.sub(num);
num.sign = true;
return res;
} else if (!num.sign && this.sign) {
this.sign = false;
var res = num.sub(this);
this.sign = true;
return res;
}
if (this.length > num.length)
return this.clone().iadd(num);
else
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub(num) {
// this - (-num) = this + num
if (num.sign) {
num.sign = false;
var r = this.iadd(num);
num.sign = true;
return r._normSign();
// -this - num = -(this + num)
} else if (this.sign) {
this.sign = false;
this.iadd(num);
this.sign = true;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.sign = false;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a;
var b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
var r = a.words[i] - b.words[i] + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for (; carry !== 0 && i < a.length; i++) {
var r = a.words[i] + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this)
for (; i < a.length; i++)
this.words[i] = a.words[i];
this.length = Math.max(this.length, i);
if (a !== this)
this.sign = true;
return this.strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub(num) {
return this.clone().isub(num);
};
/*
// NOTE: This could be potentionally used to generate loop-less multiplications
function _genCombMulTo(alen, blen) {
var len = alen + blen - 1;
var src = [
'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
'mask = 0x3ffffff, shift = 0x4000000;',
'out.length = ' + len + ';'
];
for (var k = 0; k < len; k++) {
var minJ = Math.max(0, k - alen + 1);
var maxJ = Math.min(k, blen - 1);
for (var j = minJ; j <= maxJ; j++) {
var i = k - j;
var mul = 'a[' + i + '] * b[' + j + ']';
if (j === minJ) {
src.push('w = ' + mul + ' + c;');
src.push('c = (w / shift) | 0;');
} else {
src.push('w += ' + mul + ';');
src.push('c += (w / shift) | 0;');
}
src.push('w &= mask;');
}
src.push('o[' + k + '] = w;');
}
src.push('if (c !== 0) {',
' o[' + k + '] = c;',
' out.length++;',
'}',
'return out;');
return src.join('\n');
}
*/
BN.prototype._smallMulTo = function _smallMulTo(num, out) {
out.sign = num.sign !== this.sign;
out.length = this.length + num.length;
var carry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = this.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
}
out.words[k] = rword;
carry = ncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out.strip();
};
BN.prototype._bigMulTo = function _bigMulTo(num, out) {
out.sign = num.sign !== this.sign;
out.length = this.length + num.length;
var carry = 0;
var hncarry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = this.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out.strip();
};
BN.prototype.mulTo = function mulTo(num, out) {
var res;
if (this.length + num.length < 63)
res = this._smallMulTo(num, out);
else
res = this._bigMulTo(num, out);
return res;
};
// Multiply `this` by `num`
BN.prototype.mul = function mul(num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul(num) {
if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
this.words[0] = 0;
this.length = 1;
return this;
}
var tlen = this.length;
var nlen = num.length;
this.sign = num.sign !== this.sign;
this.length = this.length + num.length;
this.words[this.length - 1] = 0;
for (var k = this.length - 2; k >= 0; k--) {
// Sum all words with the same `i + j = k` and accumulate `carry`,
// note that carry could be >= 0x3ffffff
var carry = 0;
var rword = 0;
var maxJ = Math.min(k, nlen - 1);
for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
var i = k - j;
var a = this.words[i];
var b = num.words[j];
var r = a * b;
var lo = r & 0x3ffffff;
carry += (r / 0x4000000) | 0;
lo += rword;
rword = lo & 0x3ffffff;
carry += lo >>> 26;
}
this.words[k] = rword;
this.words[k + 1] += carry;
carry = 0;
}
// Propagate overflows
var carry = 0;
for (var i = 1; i < this.length; i++) {
var w = this.words[i] + carry;
this.words[i] = w & 0x3ffffff;
carry = w >>> 26;
}
return this.strip();
};
BN.prototype.imuln = function imuln(num) {
assert(typeof num === 'number');
// Carry
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i] * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += (w / 0x4000000) | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.muln = function muln(num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr() {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr() {
return this.mul(this);
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow(num) {
var w = toBitArray(num);
if (w.length === 0)
return new BN(1);
// Skip leading zeroes
var res = this;
for (var i = 0; i < w.length; i++, res = res.sqr())
if (w[i] !== 0)
break;
if (++i < w.length) {
for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
if (w[i] === 0)
continue;
res = res.mul(q);
}
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln(bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
if (r !== 0) {
var carry = 0;
for (var i = 0; i < this.length; i++) {
var newCarry = this.words[i] & carryMask;
var c = (this.words[i] - newCarry) << r;
this.words[i] = c | carry;
carry = newCarry >>> (26 - r);
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for (var i = this.length - 1; i >= 0; i--)
this.words[i + s] = this.words[i];
for (var i = 0; i < s; i++)
this.words[i] = 0;
this.length += s;
}
return this.strip();
};
BN.prototype.ishln = function ishln(bits) {
// TODO(indutny): implement me
assert(!this.sign);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn(bits, hint, extended) {
assert(typeof bits === 'number' && bits >= 0);
var h;
if (hint)
h = (hint - (hint % 26)) / 26;
else
h = 0;
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for (var i = 0; i < s; i++)
maskedWords.words[i] = this.words[i];
maskedWords.length = s;
}
if (s === 0) {
// No-op, we should not move anything at all
} else if (this.length > s) {
this.length -= s;
for (var i = 0; i < this.length; i++)
this.words[i] = this.words[i + s];
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
var word = this.words[i];
this.words[i] = (carry << (26 - r)) | (word >>> r);
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0)
maskedWords.words[maskedWords.length++] = carry;
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
this.strip();
return this;
};
BN.prototype.ishrn = function ishrn(bits, hint, extended) {
// TODO(indutny): implement me
assert(!this.sign);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln(bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln(bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn(bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn(bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn(bit) {
assert(typeof bit === 'number' && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
return false;
}
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn(bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(!this.sign, 'imaskn works only with positive numbers');
if (r !== 0)
s++;
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
this.words[this.length - 1] &= mask;
}
return this.strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn(bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn(num) {
assert(typeof num === 'number');
if (num < 0)
return this.isubn(-num);
// Possible sign change
if (this.sign) {
if (this.length === 1 && this.words[0] < num) {
this.words[0] = num - this.words[0];
this.sign = false;
return this;
}
this.sign = false;
this.isubn(num);
this.sign = true;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn(num) {
this.words[0] += num;
// Carry
for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
this.words[i] -= 0x4000000;
if (i === this.length - 1)
this.words[i + 1] = 1;
else
this.words[i + 1]++;
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn(num) {
assert(typeof num === 'number');
if (num < 0)
return this.iaddn(-num);
if (this.sign) {
this.sign = false;
this.iaddn(num);
this.sign = true;
return this;
}
this.words[0] -= num;
// Carry
for (var i = 0; i < this.length && this.words[i] < 0; i++) {
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
return this.strip();
};
BN.prototype.addn = function addn(num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn(num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs() {
this.sign = false;
return this;
};
BN.prototype.abs = function abs() {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
// Bigger storage is needed
var len = num.length + shift;
var i;
if (this.words.length < len) {
var t = new Array(len);
for (var i = 0; i < this.length; i++)
t[i] = this.words[i];
this.words = t;
} else {
i = this.length;
}
// Zeroify rest
this.length = Math.max(this.length, len);
for (; i < this.length; i++)
this.words[i] = 0;
var carry = 0;
for (var i = 0; i < num.length; i++) {
var w = this.words[i + shift] + carry;
var right = num.words[i] * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - ((right / 0x4000000) | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for (; i < this.length - shift; i++) {
var w = this.words[i + shift] + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0)
return this.strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for (var i = 0; i < this.length; i++) {
var w = -this.words[i] + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.sign = true;
return this.strip();
};
BN.prototype._wordDiv = function _wordDiv(num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1];
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1];
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== 'mod') {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for (var i = 0; i < q.length; i++)
q.words[i] = 0;
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (!diff.sign) {
a = diff;
if (q)
q.words[m] = 1;
}
for (var j = m - 1; j >= 0; j--) {
var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min((qj / bhi) | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while (a.sign) {
qj--;
a.sign = false;
a._ishlnsubmul(b, 1, j);
if (a.cmpn(0) !== 0)
a.sign = !a.sign;
}
if (q)
q.words[j] = qj;
}
if (q)
q.strip();
a.strip();
// Denormalize
if (mode !== 'div' && shift !== 0)
a.iushrn(shift);
return { div: q ? q : null, mod: a };
};
BN.prototype.divmod = function divmod(num, mode, positive) {
assert(num.cmpn(0) !== 0);
if (this.sign && !num.sign) {
var res = this.neg().divmod(num, mode);
var div;
var mod;
if (mode !== 'mod')
div = res.div.neg();
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.neg)
mod = mod.add(num);
}
return {
div: div,
mod: mod
};
} else if (!this.sign && num.sign) {
var res = this.divmod(num.neg(), mode);
var div;
if (mode !== 'mod')
div = res.div.neg();
return { div: div, mod: res.mod };
} else if (this.sign && num.sign) {
var res = this.neg().divmod(num.neg(), mode);
var mod;
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.neg)
mod = mod.isub(num);
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0)
return { div: new BN(0), mod: this };
// Very short reduction
if (num.length === 1) {
if (mode === 'div')
return { div: this.divn(num.words[0]), mod: null };
else if (mode === 'mod')
return { div: null, mod: new BN(this.modn(num.words[0])) };
return {
div: this.divn(num.words[0]),
mod: new BN(this.modn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div(num) {
return this.divmod(num, 'div', false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod(num) {
return this.divmod(num, 'mod', false).mod;
};
BN.prototype.umod = function umod(num) {
return this.divmod(num, 'mod', true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound(num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.cmpn(0) === 0)
return dm.div;
var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || r2 === 1 && cmp === 0)
return dm.div;
// Round up
return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modn = function modn(num) {
assert(num <= 0x3ffffff);
var p = (1 << 26) % num;
var acc = 0;
for (var i = this.length - 1; i >= 0; i--)
acc = (p * acc + this.words[i]) % num;
return acc;
};
// In-place division by number
BN.prototype.idivn = function idivn(num) {
assert(num <= 0x3ffffff);
var carry = 0;
for (var i = this.length - 1; i >= 0; i--) {
var w = this.words[i] + carry * 0x4000000;
this.words[i] = (w / num) | 0;
carry = w % num;
}
return this.strip();
};
BN.prototype.divn = function divn(num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd(p) {
assert(!p.sign);
assert(p.cmpn(0) !== 0);
var x = this;
var y = p.clone();
if (x.sign)
x = x.umod(p);
else
x = x.clone();
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while (x.isEven() && y.isEven()) {
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while (x.cmpn(0) !== 0) {
while (x.isEven()) {
x.iushrn(1);
if (A.isEven() && B.isEven()) {
A.iushrn(1);
B.iushrn(1);
} else {
A.iadd(yp).iushrn(1);
B.isub(xp).iushrn(1);
}
}
while (y.isEven()) {
y.iushrn(1);
if (C.isEven() && D.isEven()) {
C.iushrn(1);
D.iushrn(1);
} else {
C.iadd(yp).iushrn(1);
D.isub(xp).iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp(p) {
assert(!p.sign);
assert(p.cmpn(0) !== 0);
var a = this;
var b = p.clone();
if (a.sign)
a = a.umod(p);
else
a = a.clone();
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
while (a.isEven()) {
a.iushrn(1);
if (x1.isEven())
x1.iushrn(1);
else
x1.iadd(delta).iushrn(1);
}
while (b.isEven()) {
b.iushrn(1);
if (x2.isEven())
x2.iushrn(1);
else
x2.iadd(delta).iushrn(1);
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0)
res = x1;
else
res = x2;
if (res.cmpn(0) < 0)
res.iadd(p);
return res;
};
BN.prototype.gcd = function gcd(num) {
if (this.cmpn(0) === 0)
return num.clone();
if (num.cmpn(0) === 0)
return this.clone();
var a = this.clone();
var b = num.clone();
a.sign = false;
b.sign = false;
// Remove common factor of two
for (var shift = 0; a.isEven() && b.isEven(); shift++) {
a.iushrn(1);
b.iushrn(1);
}
do {
while (a.isEven())
a.iushrn(1);
while (b.isEven())
b.iushrn(1);
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) {
break;
}
a.isub(b);
} while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm(num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven() {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd() {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln(num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn(bit) {
assert(typeof bit === 'number');
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
for (var i = this.length; i < s + 1; i++)
this.words[i] = 0;
this.words[s] |= q;
this.length = s + 1;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for (var i = s; carry !== 0 && i < this.length; i++) {
var w = this.words[i];
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.cmpn = function cmpn(num) {
var sign = num < 0;
if (sign)
num = -num;
if (this.sign && !sign)
return -1;
else if (!this.sign && sign)
return 1;
num &= 0x3ffffff;
this.strip();
var res;
if (this.length > 1) {
res = 1;
} else {
var w = this.words[0];
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.sign)
res = -res;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp(num) {
if (this.sign && !num.sign)
return -1;
else if (!this.sign && num.sign)
return 1;
var res = this.ucmp(num);
if (this.sign)
return -res;
else
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp(num) {
// At this point both numbers have the same sign
if (this.length > num.length)
return 1;
else if (this.length < num.length)
return -1;
var res = 0;
for (var i = this.length - 1; i >= 0; i--) {
var a = this.words[i];
var b = num.words[i];
if (a === b)
continue;
if (a < b)
res = -1;
else if (a > b)
res = 1;
break;
}
return res;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red(num) {
return new Red(num);
};
BN.prototype.toRed = function toRed(ctx) {
assert(!this.red, 'Already a number in reduction context');
assert(!this.sign, 'red works only with positives');
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed() {
assert(this.red, 'fromRed works only with numbers in reduction context');
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed(ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed(ctx) {
assert(!this.red, 'Already a number in reduction context');
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd(num) {
assert(this.red, 'redAdd works only with red numbers');
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd(num) {
assert(this.red, 'redIAdd works only with red numbers');
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub(num) {
assert(this.red, 'redSub works only with red numbers');
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub(num) {
assert(this.red, 'redISub works only with red numbers');
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl(num) {
assert(this.red, 'redShl works only with red numbers');
return this.red.ushl(this, num);
};
BN.prototype.redMul = function redMul(num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul(num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr() {
assert(this.red, 'redSqr works only with red numbers');
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr() {
assert(this.red, 'redISqr works only with red numbers');
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt() {
assert(this.red, 'redSqrt works only with red numbers');
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm() {
assert(this.red, 'redInvm works only with red numbers');
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg() {
assert(this.red, 'redNeg works only with red numbers');
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow(num) {
assert(this.red && !num.red, 'redPow(normalNum)');
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime(name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp() {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce(num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
} while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) {
r.isub(this.p);
} else {
r.strip();
}
return r;
};
MPrime.prototype.split = function split(input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK(num) {
return num.imul(this.k);
};
function K256() {
MPrime.call(
this,
'k256',
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
}
inherits(K256, MPrime);
K256.prototype.split = function split(input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for (var i = 0; i < outLen; i++)
output.words[i] = input.words[i];
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for (var i = 10; i < input.length; i++) {
var next = input.words[i];
input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
prev = next;
}
input.words[i - 10] = prev >>> 22;
input.length -= 9;
};
K256.prototype.imulK = function imulK(num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var hi;
var lo = 0;
for (var i = 0; i < num.length; i++) {
var w = num.words[i];
hi = w * 0x40;
lo += w * 0x3d1;
hi += (lo / 0x4000000) | 0;
lo &= 0x3ffffff;
num.words[i] = lo;
lo = hi;
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0)
num.length--;
}
return num;
};
function P224() {
MPrime.call(
this,
'p224',
'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
}
inherits(P224, MPrime);
function P192() {
MPrime.call(
this,
'p192',
'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
}
inherits(P192, MPrime);
function P25519() {
// 2 ^ 255 - 19
MPrime.call(
this,
'25519',
'7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK(num) {
// K = 0x13
var carry = 0;
for (var i = 0; i < num.length; i++) {
var hi = num.words[i] * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0)
num.words[num.length++] = carry;
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime(name) {
// Cached version of prime
if (primes[name])
return primes[name];
var prime;
if (name === 'k256')
prime = new K256();
else if (name === 'p224')
prime = new P224();
else if (name === 'p192')
prime = new P192();
else if (name === 'p25519')
prime = new P25519();
else
throw new Error('Unknown prime ' + name);
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red(m) {
if (typeof m === 'string') {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1(a) {
assert(!a.sign, 'red works only with positives');
assert(a.red, 'red works only with red numbers');
};
Red.prototype._verify2 = function _verify2(a, b) {
assert(!a.sign && !b.sign, 'red works only with positives');
assert(a.red && a.red === b.red,
'red works only with red numbers');
};
Red.prototype.imod = function imod(a) {
if (this.prime)
return this.prime.ireduce(a)._forceRed(this);
return a.umod(this.m)._forceRed(this);
};
Red.prototype.neg = function neg(a) {
var r = a.clone();
r.sign = !r.sign;
return r.iadd(this.m)._forceRed(this);
};
Red.prototype.add = function add(a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0)
res.isub(this.m);
return res._forceRed(this);
};
Red.prototype.iadd = function iadd(a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0)
res.isub(this.m);
return res;
};
Red.prototype.sub = function sub(a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0)
res.iadd(this.m);
return res._forceRed(this);
};
Red.prototype.isub = function isub(a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0)
res.iadd(this.m);
return res;
};
Red.prototype.shl = function shl(a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul(a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul(a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr(a) {
return this.imul(a, a);
};
Red.prototype.sqr = function sqr(a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt(a) {
if (a.cmpn(0) === 0)
return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
var r = this.pow(a, pow);
return r;
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
s++;
q.iushrn(1);
}
assert(q.cmpn(0) !== 0);
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while (this.pow(z, lpow).cmp(nOne) !== 0)
z.redIAdd(nOne);
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while (t.cmp(one) !== 0) {
var tmp = t;
for (var i = 0; tmp.cmp(one) !== 0; i++)
tmp = tmp.redSqr();
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm(a) {
var inv = a._invmp(this.m);
if (inv.sign) {
inv.sign = false;
return this.imod(inv).redNeg();
} else {
return this.imod(inv);
}
};
Red.prototype.pow = function pow(a, num) {
var w = toBitArray(num);
if (w.length === 0)
return new BN(1);
// Skip leading zeroes
var res = a;
for (var i = 0; i < w.length; i++, res = this.sqr(res))
if (w[i] !== 0)
break;
if (++i < w.length) {
for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
if (w[i] === 0)
continue;
res = this.mul(res, q);
}
}
return res;
};
Red.prototype.convertTo = function convertTo(num) {
var r = num.umod(this.m);
if (r === num)
return r.clone();
else
return r;
};
Red.prototype.convertFrom = function convertFrom(num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont(num) {
return new Mont(num);
};
function Mont(m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0)
this.shift += 26 - (this.shift % 26);
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo(num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom(num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul(a, b) {
if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0)
res = u.isub(this.m);
else if (u.cmpn(0) < 0)
res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.mul = function mul(a, b) {
if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0)
res = u.isub(this.m);
else if (u.cmpn(0) < 0)
res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.invm = function invm(a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})(typeof module === 'undefined' || module, this);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(40)(module)))
/***/ }),
/* 19 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const assert = __webpack_require__(2);
const common = __webpack_require__(0);
exports.common = common;
function clamp(value, min, max) {
assert(min <= max, 'Illegal clamp bounds');
return Math.min(Math.max(value, min), max);
}
exports.clamp = clamp;
function getXRPBalance(connection, address, ledgerVersion) {
const request = {
command: 'account_info',
account: address,
ledger_index: ledgerVersion
};
return connection.request(request).then(data => common.dropsToXrp(data.account_data.Balance));
}
exports.getXRPBalance = getXRPBalance;
// If the marker is omitted from a response, you have reached the end
function getRecursiveRecur(getter, marker, limit) {
return getter(marker, limit).then(data => {
const remaining = limit - data.results.length;
if (remaining > 0 && data.marker !== undefined) {
return getRecursiveRecur(getter, data.marker, remaining).then(results => data.results.concat(results));
}
return data.results.slice(0, limit);
});
}
function getRecursive(getter, limit) {
return getRecursiveRecur(getter, undefined, limit || Infinity);
}
exports.getRecursive = getRecursive;
function renameCounterpartyToIssuer(obj) {
const issuer = (obj.counterparty !== undefined) ?
obj.counterparty :
((obj.issuer !== undefined) ? obj.issuer : undefined);
const withIssuer = Object.assign({}, obj, { issuer });
delete withIssuer.counterparty;
return withIssuer;
}
exports.renameCounterpartyToIssuer = renameCounterpartyToIssuer;
function renameCounterpartyToIssuerInOrder(order) {
const taker_gets = renameCounterpartyToIssuer(order.taker_gets);
const taker_pays = renameCounterpartyToIssuer(order.taker_pays);
const changes = { taker_gets, taker_pays };
return _.assign({}, order, _.omitBy(changes, _.isUndefined));
}
exports.renameCounterpartyToIssuerInOrder = renameCounterpartyToIssuerInOrder;
function signum(num) {
return (num === 0) ? 0 : (num > 0 ? 1 : -1);
}
/**
* Order two rippled transactions based on their ledger_index.
* If two transactions took place in the same ledger, sort
* them based on TransactionIndex
* See: https://ripple.com/build/transactions/
*/
function compareTransactions(first, second) {
if (!first.outcome || !second.outcome) {
return 0;
}
if (first.outcome.ledgerVersion === second.outcome.ledgerVersion) {
return signum(first.outcome.indexInLedger - second.outcome.indexInLedger);
}
return first.outcome.ledgerVersion < second.outcome.ledgerVersion ? -1 : 1;
}
exports.compareTransactions = compareTransactions;
function hasCompleteLedgerRange(connection, minLedgerVersion, maxLedgerVersion) {
const firstLedgerVersion = 32570; // earlier versions have been lost
return connection.hasLedgerVersions(minLedgerVersion || firstLedgerVersion, maxLedgerVersion);
}
exports.hasCompleteLedgerRange = hasCompleteLedgerRange;
function isPendingLedgerVersion(connection, maxLedgerVersion) {
return connection.getLedgerVersion().then(ledgerVersion => ledgerVersion < (maxLedgerVersion || 0));
}
exports.isPendingLedgerVersion = isPendingLedgerVersion;
function ensureLedgerVersion(options) {
if (Boolean(options) && options.ledgerVersion !== undefined &&
options.ledgerVersion !== null) {
return Promise.resolve(options);
}
return this.getLedgerVersion().then(ledgerVersion => _.assign({}, options, { ledgerVersion }));
}
exports.ensureLedgerVersion = ensureLedgerVersion;
/***/ }),
/* 20 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process) {
if (!process.version ||
process.version.indexOf('v0.') === 0 ||
process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
module.exports = nextTick;
} else {
module.exports = process.nextTick;
}
function nextTick(fn, arg1, arg2, arg3) {
if (typeof fn !== 'function') {
throw new TypeError('"callback" argument must be a function');
}
var len = arguments.length;
var args, i;
switch (len) {
case 0:
case 1:
return process.nextTick(fn);
case 2:
return process.nextTick(function afterTickOne() {
fn.call(null, arg1);
});
case 3:
return process.nextTick(function afterTickTwo() {
fn.call(null, arg1, arg2);
});
case 4:
return process.nextTick(function afterTickThree() {
fn.call(null, arg1, arg2, arg3);
});
default:
args = new Array(len - 1);
i = 0;
while (i < args.length) {
args[i++] = arguments[i];
}
return process.nextTick(function afterTick() {
fn.apply(null, args);
});
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9)))
/***/ }),
/* 21 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _require = __webpack_require__(10);var bytesToHex = _require.bytesToHex;var slice = _require.slice;var _require2 =
__webpack_require__(51);var BytesList = _require2.BytesList;
var Comparable = {
lt: function lt(other) {
return this.compareTo(other) < 0;},
eq: function eq(other) {
return this.compareTo(other) === 0;},
gt: function gt(other) {
return this.compareTo(other) > 0;},
gte: function gte(other) {
return this.compareTo(other) > -1;},
lte: function lte(other) {
return this.compareTo(other) < 1;} };
var SerializedType = {
toBytesSink: function toBytesSink(sink) {
sink.put(this._bytes);},
toHex: function toHex() {
return bytesToHex(this.toBytes());},
toBytes: function toBytes() {
if (this._bytes) {
return slice(this._bytes);}
var bl = new BytesList();
this.toBytesSink(bl);
return bl.toBytes();},
toJSON: function toJSON() {
return this.toHex();},
toString: function toString() {
return this.toHex();} };
function ensureArrayLikeIs(Type, arrayLike) {
return {
withChildren: function withChildren(Child) {
if (arrayLike instanceof Type) {
return arrayLike;}
var obj = new Type();
for (var i = 0; i < arrayLike.length; i++) {
obj.push(Child.from(arrayLike[i]));}
return obj;} };}
module.exports = {
ensureArrayLikeIs: ensureArrayLikeIs,
SerializedType: SerializedType,
Comparable: Comparable };
/***/ }),
/* 22 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var punycode = __webpack_require__(106);
var util = __webpack_require__(107);
exports.parse = urlParse;
exports.resolve = urlResolve;
exports.resolveObject = urlResolveObject;
exports.format = urlFormat;
exports.Url = Url;
function Url() {
this.protocol = null;
this.slashes = null;
this.auth = null;
this.host = null;
this.port = null;
this.hostname = null;
this.hash = null;
this.search = null;
this.query = null;
this.pathname = null;
this.path = null;
this.href = null;
}
// Reference: RFC 3986, RFC 1808, RFC 2396
// define these here so at least they only have to be
// compiled once on the first module load.
var protocolPattern = /^([a-z0-9.+-]+:)/i,
portPattern = /:[0-9]*$/,
// Special case for a simple path URL
simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
// RFC 2396: characters reserved for delimiting URLs.
// We actually just auto-escape these.
delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
// RFC 2396: characters not allowed for various reasons.
unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
// Allowed by RFCs, but cause of XSS attacks. Always escape these.
autoEscape = ['\''].concat(unwise),
// Characters that are never ever allowed in a hostname.
// Note that any invalid chars are also handled, but these
// are the ones that are *expected* to be seen, so we fast-path
// them.
nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
hostEndingChars = ['/', '?', '#'],
hostnameMaxLen = 255,
hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
// protocols that can allow "unsafe" and "unwise" chars.
unsafeProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that never have a hostname.
hostlessProtocol = {
'javascript': true,
'javascript:': true
},
// protocols that always contain a // bit.
slashedProtocol = {
'http': true,
'https': true,
'ftp': true,
'gopher': true,
'file': true,
'http:': true,
'https:': true,
'ftp:': true,
'gopher:': true,
'file:': true
},
querystring = __webpack_require__(108);
function urlParse(url, parseQueryString, slashesDenoteHost) {
if (url && util.isObject(url) && url instanceof Url) return url;
var u = new Url;
u.parse(url, parseQueryString, slashesDenoteHost);
return u;
}
Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
if (!util.isString(url)) {
throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
}
// Copy chrome, IE, opera backslash-handling behavior.
// Back slashes before the query string get converted to forward slashes
// See: https://code.google.com/p/chromium/issues/detail?id=25916
var queryIndex = url.indexOf('?'),
splitter =
(queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
uSplit = url.split(splitter),
slashRegex = /\\/g;
uSplit[0] = uSplit[0].replace(slashRegex, '/');
url = uSplit.join(splitter);
var rest = url;
// trim before proceeding.
// This is to support parse stuff like " http://foo.com \n"
rest = rest.trim();
if (!slashesDenoteHost && url.split('#').length === 1) {
// Try fast path regexp
var simplePath = simplePathPattern.exec(rest);
if (simplePath) {
this.path = rest;
this.href = rest;
this.pathname = simplePath[1];
if (simplePath[2]) {
this.search = simplePath[2];
if (parseQueryString) {
this.query = querystring.parse(this.search.substr(1));
} else {
this.query = this.search.substr(1);
}
} else if (parseQueryString) {
this.search = '';
this.query = {};
}
return this;
}
}
var proto = protocolPattern.exec(rest);
if (proto) {
proto = proto[0];
var lowerProto = proto.toLowerCase();
this.protocol = lowerProto;
rest = rest.substr(proto.length);
}
// figure out if it's got a host
// user@server is *always* interpreted as a hostname, and url
// resolution will treat //foo/bar as host=foo,path=bar because that's
// how the browser resolves relative URLs.
if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
var slashes = rest.substr(0, 2) === '//';
if (slashes && !(proto && hostlessProtocol[proto])) {
rest = rest.substr(2);
this.slashes = true;
}
}
if (!hostlessProtocol[proto] &&
(slashes || (proto && !slashedProtocol[proto]))) {
// there's a hostname.
// the first instance of /, ?, ;, or # ends the host.
//
// If there is an @ in the hostname, then non-host chars *are* allowed
// to the left of the last @ sign, unless some host-ending character
// comes *before* the @-sign.
// URLs are obnoxious.
//
// ex:
// http://a@b@c/ => user:a@b host:c
// http://a@b?@c => user:a host:c path:/?@c
// v0.12 TODO(isaacs): This is not quite how Chrome does things.
// Review our test case against browsers more comprehensively.
// find the first instance of any hostEndingChars
var hostEnd = -1;
for (var i = 0; i < hostEndingChars.length; i++) {
var hec = rest.indexOf(hostEndingChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// at this point, either we have an explicit point where the
// auth portion cannot go past, or the last @ char is the decider.
var auth, atSign;
if (hostEnd === -1) {
// atSign can be anywhere.
atSign = rest.lastIndexOf('@');
} else {
// atSign must be in auth portion.
// http://a@b/c@d => host:b auth:a path:/c@d
atSign = rest.lastIndexOf('@', hostEnd);
}
// Now we have a portion which is definitely the auth.
// Pull that off.
if (atSign !== -1) {
auth = rest.slice(0, atSign);
rest = rest.slice(atSign + 1);
this.auth = decodeURIComponent(auth);
}
// the host is the remaining to the left of the first non-host char
hostEnd = -1;
for (var i = 0; i < nonHostChars.length; i++) {
var hec = rest.indexOf(nonHostChars[i]);
if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
hostEnd = hec;
}
// if we still have not hit it, then the entire thing is a host.
if (hostEnd === -1)
hostEnd = rest.length;
this.host = rest.slice(0, hostEnd);
rest = rest.slice(hostEnd);
// pull out port.
this.parseHost();
// we've indicated that there is a hostname,
// so even if it's empty, it has to be present.
this.hostname = this.hostname || '';
// if hostname begins with [ and ends with ]
// assume that it's an IPv6 address.
var ipv6Hostname = this.hostname[0] === '[' &&
this.hostname[this.hostname.length - 1] === ']';
// validate a little.
if (!ipv6Hostname) {
var hostparts = this.hostname.split(/\./);
for (var i = 0, l = hostparts.length; i < l; i++) {
var part = hostparts[i];
if (!part) continue;
if (!part.match(hostnamePartPattern)) {
var newpart = '';
for (var j = 0, k = part.length; j < k; j++) {
if (part.charCodeAt(j) > 127) {
// we replace non-ASCII char with a temporary placeholder
// we need this to make sure size of hostname is not
// broken by replacing non-ASCII by nothing
newpart += 'x';
} else {
newpart += part[j];
}
}
// we test again with ASCII char only
if (!newpart.match(hostnamePartPattern)) {
var validParts = hostparts.slice(0, i);
var notHost = hostparts.slice(i + 1);
var bit = part.match(hostnamePartStart);
if (bit) {
validParts.push(bit[1]);
notHost.unshift(bit[2]);
}
if (notHost.length) {
rest = '/' + notHost.join('.') + rest;
}
this.hostname = validParts.join('.');
break;
}
}
}
}
if (this.hostname.length > hostnameMaxLen) {
this.hostname = '';
} else {
// hostnames are always lower case.
this.hostname = this.hostname.toLowerCase();
}
if (!ipv6Hostname) {
// IDNA Support: Returns a punycoded representation of "domain".
// It only converts parts of the domain name that
// have non-ASCII characters, i.e. it doesn't matter if
// you call it with a domain that already is ASCII-only.
this.hostname = punycode.toASCII(this.hostname);
}
var p = this.port ? ':' + this.port : '';
var h = this.hostname || '';
this.host = h + p;
this.href += this.host;
// strip [ and ] from the hostname
// the host field still retains them, though
if (ipv6Hostname) {
this.hostname = this.hostname.substr(1, this.hostname.length - 2);
if (rest[0] !== '/') {
rest = '/' + rest;
}
}
}
// now rest is set to the post-host stuff.
// chop off any delim chars.
if (!unsafeProtocol[lowerProto]) {
// First, make 100% sure that any "autoEscape" chars get
// escaped, even if encodeURIComponent doesn't think they
// need to be.
for (var i = 0, l = autoEscape.length; i < l; i++) {
var ae = autoEscape[i];
if (rest.indexOf(ae) === -1)
continue;
var esc = encodeURIComponent(ae);
if (esc === ae) {
esc = escape(ae);
}
rest = rest.split(ae).join(esc);
}
}
// chop off from the tail first.
var hash = rest.indexOf('#');
if (hash !== -1) {
// got a fragment string.
this.hash = rest.substr(hash);
rest = rest.slice(0, hash);
}
var qm = rest.indexOf('?');
if (qm !== -1) {
this.search = rest.substr(qm);
this.query = rest.substr(qm + 1);
if (parseQueryString) {
this.query = querystring.parse(this.query);
}
rest = rest.slice(0, qm);
} else if (parseQueryString) {
// no query string, but parseQueryString still requested
this.search = '';
this.query = {};
}
if (rest) this.pathname = rest;
if (slashedProtocol[lowerProto] &&
this.hostname && !this.pathname) {
this.pathname = '/';
}
//to support http.request
if (this.pathname || this.search) {
var p = this.pathname || '';
var s = this.search || '';
this.path = p + s;
}
// finally, reconstruct the href based on what has been validated.
this.href = this.format();
return this;
};
// format a parsed object into a url string
function urlFormat(obj) {
// ensure it's an object, and not a string url.
// If it's an obj, this is a no-op.
// this way, you can call url_format() on strings
// to clean up potentially wonky urls.
if (util.isString(obj)) obj = urlParse(obj);
if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
return obj.format();
}
Url.prototype.format = function() {
var auth = this.auth || '';
if (auth) {
auth = encodeURIComponent(auth);
auth = auth.replace(/%3A/i, ':');
auth += '@';
}
var protocol = this.protocol || '',
pathname = this.pathname || '',
hash = this.hash || '',
host = false,
query = '';
if (this.host) {
host = auth + this.host;
} else if (this.hostname) {
host = auth + (this.hostname.indexOf(':') === -1 ?
this.hostname :
'[' + this.hostname + ']');
if (this.port) {
host += ':' + this.port;
}
}
if (this.query &&
util.isObject(this.query) &&
Object.keys(this.query).length) {
query = querystring.stringify(this.query);
}
var search = this.search || (query && ('?' + query)) || '';
if (protocol && protocol.substr(-1) !== ':') protocol += ':';
// only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
// unless they had them to begin with.
if (this.slashes ||
(!protocol || slashedProtocol[protocol]) && host !== false) {
host = '//' + (host || '');
if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
} else if (!host) {
host = '';
}
if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
if (search && search.charAt(0) !== '?') search = '?' + search;
pathname = pathname.replace(/[?#]/g, function(match) {
return encodeURIComponent(match);
});
search = search.replace('#', '%23');
return protocol + host + pathname + search + hash;
};
function urlResolve(source, relative) {
return urlParse(source, false, true).resolve(relative);
}
Url.prototype.resolve = function(relative) {
return this.resolveObject(urlParse(relative, false, true)).format();
};
function urlResolveObject(source, relative) {
if (!source) return relative;
return urlParse(source, false, true).resolveObject(relative);
}
Url.prototype.resolveObject = function(relative) {
if (util.isString(relative)) {
var rel = new Url();
rel.parse(relative, false, true);
relative = rel;
}
var result = new Url();
var tkeys = Object.keys(this);
for (var tk = 0; tk < tkeys.length; tk++) {
var tkey = tkeys[tk];
result[tkey] = this[tkey];
}
// hash is always overridden, no matter what.
// even href="" will remove it.
result.hash = relative.hash;
// if the relative url is empty, then there's nothing left to do here.
if (relative.href === '') {
result.href = result.format();
return result;
}
// hrefs like //foo/bar always cut to the protocol.
if (relative.slashes && !relative.protocol) {
// take everything except the protocol from relative
var rkeys = Object.keys(relative);
for (var rk = 0; rk < rkeys.length; rk++) {
var rkey = rkeys[rk];
if (rkey !== 'protocol')
result[rkey] = relative[rkey];
}
//urlParse appends trailing / to urls like http://www.example.com
if (slashedProtocol[result.protocol] &&
result.hostname && !result.pathname) {
result.path = result.pathname = '/';
}
result.href = result.format();
return result;
}
if (relative.protocol && relative.protocol !== result.protocol) {
// if it's a known url protocol, then changing
// the protocol does weird things
// first, if it's not file:, then we MUST have a host,
// and if there was a path
// to begin with, then we MUST have a path.
// if it is file:, then the host is dropped,
// because that's known to be hostless.
// anything else is assumed to be absolute.
if (!slashedProtocol[relative.protocol]) {
var keys = Object.keys(relative);
for (var v = 0; v < keys.length; v++) {
var k = keys[v];
result[k] = relative[k];
}
result.href = result.format();
return result;
}
result.protocol = relative.protocol;
if (!relative.host && !hostlessProtocol[relative.protocol]) {
var relPath = (relative.pathname || '').split('/');
while (relPath.length && !(relative.host = relPath.shift()));
if (!relative.host) relative.host = '';
if (!relative.hostname) relative.hostname = '';
if (relPath[0] !== '') relPath.unshift('');
if (relPath.length < 2) relPath.unshift('');
result.pathname = relPath.join('/');
} else {
result.pathname = relative.pathname;
}
result.search = relative.search;
result.query = relative.query;
result.host = relative.host || '';
result.auth = relative.auth;
result.hostname = relative.hostname || relative.host;
result.port = relative.port;
// to support http.request
if (result.pathname || result.search) {
var p = result.pathname || '';
var s = result.search || '';
result.path = p + s;
}
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
}
var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
isRelAbs = (
relative.host ||
relative.pathname && relative.pathname.charAt(0) === '/'
),
mustEndAbs = (isRelAbs || isSourceAbs ||
(result.host && relative.pathname)),
removeAllDots = mustEndAbs,
srcPath = result.pathname && result.pathname.split('/') || [],
relPath = relative.pathname && relative.pathname.split('/') || [],
psychotic = result.protocol && !slashedProtocol[result.protocol];
// if the url is a non-slashed url, then relative
// links like ../.. should be able
// to crawl up to the hostname, as well. This is strange.
// result.protocol has already been set by now.
// Later on, put the first path part into the host field.
if (psychotic) {
result.hostname = '';
result.port = null;
if (result.host) {
if (srcPath[0] === '') srcPath[0] = result.host;
else srcPath.unshift(result.host);
}
result.host = '';
if (relative.protocol) {
relative.hostname = null;
relative.port = null;
if (relative.host) {
if (relPath[0] === '') relPath[0] = relative.host;
else relPath.unshift(relative.host);
}
relative.host = null;
}
mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
}
if (isRelAbs) {
// it's absolute.
result.host = (relative.host || relative.host === '') ?
relative.host : result.host;
result.hostname = (relative.hostname || relative.hostname === '') ?
relative.hostname : result.hostname;
result.search = relative.search;
result.query = relative.query;
srcPath = relPath;
// fall through to the dot-handling below.
} else if (relPath.length) {
// it's relative
// throw away the existing file, and take the new path instead.
if (!srcPath) srcPath = [];
srcPath.pop();
srcPath = srcPath.concat(relPath);
result.search = relative.search;
result.query = relative.query;
} else if (!util.isNullOrUndefined(relative.search)) {
// just pull out the search.
// like href='?foo'.
// Put this after the other two cases because it simplifies the booleans
if (psychotic) {
result.hostname = result.host = srcPath.shift();
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
result.search = relative.search;
result.query = relative.query;
//to support http.request
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.href = result.format();
return result;
}
if (!srcPath.length) {
// no path at all. easy.
// we've already handled the other stuff above.
result.pathname = null;
//to support http.request
if (result.search) {
result.path = '/' + result.search;
} else {
result.path = null;
}
result.href = result.format();
return result;
}
// if a url ENDs in . or .., then it must get a trailing slash.
// however, if it ends in anything else non-slashy,
// then it must NOT get a trailing slash.
var last = srcPath.slice(-1)[0];
var hasTrailingSlash = (
(result.host || relative.host || srcPath.length > 1) &&
(last === '.' || last === '..') || last === '');
// strip single dots, resolve double dots to parent dir
// if the path tries to go above the root, `up` ends up > 0
var up = 0;
for (var i = srcPath.length; i >= 0; i--) {
last = srcPath[i];
if (last === '.') {
srcPath.splice(i, 1);
} else if (last === '..') {
srcPath.splice(i, 1);
up++;
} else if (up) {
srcPath.splice(i, 1);
up--;
}
}
// if the path is allowed to go above the root, restore leading ..s
if (!mustEndAbs && !removeAllDots) {
for (; up--; up) {
srcPath.unshift('..');
}
}
if (mustEndAbs && srcPath[0] !== '' &&
(!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
srcPath.unshift('');
}
if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
srcPath.push('');
}
var isAbsolute = srcPath[0] === '' ||
(srcPath[0] && srcPath[0].charAt(0) === '/');
// put the host back
if (psychotic) {
result.hostname = result.host = isAbsolute ? '' :
srcPath.length ? srcPath.shift() : '';
//occationaly the auth can get stuck only in host
//this especially happens in cases like
//url.resolveObject('mailto:local1@domain1', 'local2@domain2')
var authInHost = result.host && result.host.indexOf('@') > 0 ?
result.host.split('@') : false;
if (authInHost) {
result.auth = authInHost.shift();
result.host = result.hostname = authInHost.shift();
}
}
mustEndAbs = mustEndAbs || (result.host && srcPath.length);
if (mustEndAbs && !isAbsolute) {
srcPath.unshift('');
}
if (!srcPath.length) {
result.pathname = null;
result.path = null;
} else {
result.pathname = srcPath.join('/');
}
//to support request.http
if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
result.path = (result.pathname ? result.pathname : '') +
(result.search ? result.search : '');
}
result.auth = relative.auth || result.auth;
result.slashes = result.slashes || relative.slashes;
result.href = result.format();
return result;
};
Url.prototype.parseHost = function() {
var host = this.host;
var port = portPattern.exec(host);
if (port) {
port = port[0];
if (port !== ':') {
this.port = port.substr(1);
}
host = host.substr(0, host.length - port.length);
}
if (host) this.hostname = host;
};
/***/ }),
/* 23 */
/***/ (function(module, exports, __webpack_require__) {
var hash = exports;
hash.utils = __webpack_require__(14);
hash.common = __webpack_require__(35);
hash.sha = __webpack_require__(112);
hash.ripemd = __webpack_require__(116);
hash.hmac = __webpack_require__(117);
// Proxy hash functions to the main object
hash.sha1 = hash.sha.sha1;
hash.sha256 = hash.sha.sha256;
hash.sha224 = hash.sha.sha224;
hash.sha384 = hash.sha.sha384;
hash.sha512 = hash.sha.sha512;
hash.ripemd160 = hash.ripemd.ripemd160;
/***/ }),
/* 24 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var enums = __webpack_require__(29);var
Field = enums.Field;var _require =
__webpack_require__(48);var AccountID = _require.AccountID;var _require2 =
__webpack_require__(287);var Amount = _require2.Amount;var _require3 =
__webpack_require__(289);var Blob = _require3.Blob;var _require4 =
__webpack_require__(52);var Currency = _require4.Currency;var _require5 =
__webpack_require__(290);var Hash128 = _require5.Hash128;var _require6 =
__webpack_require__(49);var Hash160 = _require6.Hash160;var _require7 =
__webpack_require__(83);var Hash256 = _require7.Hash256;var _require8 =
__webpack_require__(291);var PathSet = _require8.PathSet;var _require9 =
__webpack_require__(292);var STArray = _require9.STArray;var _require10 =
__webpack_require__(84);var STObject = _require10.STObject;var _require11 =
__webpack_require__(293);var UInt16 = _require11.UInt16;var _require12 =
__webpack_require__(294);var UInt32 = _require12.UInt32;var _require13 =
__webpack_require__(82);var UInt64 = _require13.UInt64;var _require14 =
__webpack_require__(295);var UInt8 = _require14.UInt8;var _require15 =
__webpack_require__(296);var Vector256 = _require15.Vector256;
var coreTypes = {
AccountID: AccountID,
Amount: Amount,
Blob: Blob,
Currency: Currency,
Hash128: Hash128,
Hash160: Hash160,
Hash256: Hash256,
PathSet: PathSet,
STArray: STArray,
STObject: STObject,
UInt8: UInt8,
UInt16: UInt16,
UInt32: UInt32,
UInt64: UInt64,
Vector256: Vector256 };
Field.values.forEach(function (field) {
field.associatedType = coreTypes[field.type];});
Field.TransactionType.associatedType = enums.TransactionType;
Field.TransactionResult.associatedType = enums.TransactionResult;
Field.LedgerEntryType.associatedType = enums.LedgerEntryType;
module.exports = coreTypes;
/***/ }),
/* 25 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
var Readable = __webpack_require__(87);
var Writable = __webpack_require__(55);
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
processNextTick(cb, err);
};
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
/***/ }),
/* 26 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var formatRegExp = /%[sdj%]/g;
exports.format = function(f) {
if (!isString(f)) {
var objects = [];
for (var i = 0; i < arguments.length; i++) {
objects.push(inspect(arguments[i]));
}
return objects.join(' ');
}
var i = 1;
var args = arguments;
var len = args.length;
var str = String(f).replace(formatRegExp, function(x) {
if (x === '%%') return '%';
if (i >= len) return x;
switch (x) {
case '%s': return String(args[i++]);
case '%d': return Number(args[i++]);
case '%j':
try {
return JSON.stringify(args[i++]);
} catch (_) {
return '[Circular]';
}
default:
return x;
}
});
for (var x = args[i]; i < len; x = args[++i]) {
if (isNull(x) || !isObject(x)) {
str += ' ' + x;
} else {
str += ' ' + inspect(x);
}
}
return str;
};
// Mark that a method should not be used.
// Returns a modified function which warns once by default.
// If --no-deprecation is set, then it is a no-op.
exports.deprecate = function(fn, msg) {
// Allow for deprecating things in the process of starting up.
if (isUndefined(global.process)) {
return function() {
return exports.deprecate(fn, msg).apply(this, arguments);
};
}
if (process.noDeprecation === true) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (process.throwDeprecation) {
throw new Error(msg);
} else if (process.traceDeprecation) {
console.trace(msg);
} else {
console.error(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
};
var debugs = {};
var debugEnviron;
exports.debuglog = function(set) {
if (isUndefined(debugEnviron))
debugEnviron = process.env.NODE_DEBUG || '';
set = set.toUpperCase();
if (!debugs[set]) {
if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
var pid = process.pid;
debugs[set] = function() {
var msg = exports.format.apply(exports, arguments);
console.error('%s %d: %s', set, pid, msg);
};
} else {
debugs[set] = function() {};
}
}
return debugs[set];
};
/**
* Echos the value of a value. Trys to print the value out
* in the best way possible given the different types.
*
* @param {Object} obj The object to print out.
* @param {Object} opts Optional options object that alters the output.
*/
/* legacy: obj, showHidden, depth, colors*/
function inspect(obj, opts) {
// default options
var ctx = {
seen: [],
stylize: stylizeNoColor
};
// legacy...
if (arguments.length >= 3) ctx.depth = arguments[2];
if (arguments.length >= 4) ctx.colors = arguments[3];
if (isBoolean(opts)) {
// legacy...
ctx.showHidden = opts;
} else if (opts) {
// got an "options" object
exports._extend(ctx, opts);
}
// set default options
if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
if (isUndefined(ctx.depth)) ctx.depth = 2;
if (isUndefined(ctx.colors)) ctx.colors = false;
if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
if (ctx.colors) ctx.stylize = stylizeWithColor;
return formatValue(ctx, obj, ctx.depth);
}
exports.inspect = inspect;
// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
inspect.colors = {
'bold' : [1, 22],
'italic' : [3, 23],
'underline' : [4, 24],
'inverse' : [7, 27],
'white' : [37, 39],
'grey' : [90, 39],
'black' : [30, 39],
'blue' : [34, 39],
'cyan' : [36, 39],
'green' : [32, 39],
'magenta' : [35, 39],
'red' : [31, 39],
'yellow' : [33, 39]
};
// Don't use 'blue' not visible on cmd.exe
inspect.styles = {
'special': 'cyan',
'number': 'yellow',
'boolean': 'yellow',
'undefined': 'grey',
'null': 'bold',
'string': 'green',
'date': 'magenta',
// "name": intentionally not styling
'regexp': 'red'
};
function stylizeWithColor(str, styleType) {
var style = inspect.styles[styleType];
if (style) {
return '\u001b[' + inspect.colors[style][0] + 'm' + str +
'\u001b[' + inspect.colors[style][1] + 'm';
} else {
return str;
}
}
function stylizeNoColor(str, styleType) {
return str;
}
function arrayToHash(array) {
var hash = {};
array.forEach(function(val, idx) {
hash[val] = true;
});
return hash;
}
function formatValue(ctx, value, recurseTimes) {
// Provide a hook for user-specified inspect functions.
// Check that value is an object with an inspect function on it
if (ctx.customInspect &&
value &&
isFunction(value.inspect) &&
// Filter out the util module, it's inspect function is special
value.inspect !== exports.inspect &&
// Also filter out any prototype objects using the circular check.
!(value.constructor && value.constructor.prototype === value)) {
var ret = value.inspect(recurseTimes, ctx);
if (!isString(ret)) {
ret = formatValue(ctx, ret, recurseTimes);
}
return ret;
}
// Primitive types cannot have properties
var primitive = formatPrimitive(ctx, value);
if (primitive) {
return primitive;
}
// Look up the keys of the object.
var keys = Object.keys(value);
var visibleKeys = arrayToHash(keys);
if (ctx.showHidden) {
keys = Object.getOwnPropertyNames(value);
}
// IE doesn't make error fields non-enumerable
// http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
if (isError(value)
&& (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
return formatError(value);
}
// Some type of object without properties can be shortcutted.
if (keys.length === 0) {
if (isFunction(value)) {
var name = value.name ? ': ' + value.name : '';
return ctx.stylize('[Function' + name + ']', 'special');
}
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
}
if (isDate(value)) {
return ctx.stylize(Date.prototype.toString.call(value), 'date');
}
if (isError(value)) {
return formatError(value);
}
}
var base = '', array = false, braces = ['{', '}'];
// Make Array say that they are Array
if (isArray(value)) {
array = true;
braces = ['[', ']'];
}
// Make functions say that they are functions
if (isFunction(value)) {
var n = value.name ? ': ' + value.name : '';
base = ' [Function' + n + ']';
}
// Make RegExps say that they are RegExps
if (isRegExp(value)) {
base = ' ' + RegExp.prototype.toString.call(value);
}
// Make dates with properties first say the date
if (isDate(value)) {
base = ' ' + Date.prototype.toUTCString.call(value);
}
// Make error with message first say the error
if (isError(value)) {
base = ' ' + formatError(value);
}
if (keys.length === 0 && (!array || value.length == 0)) {
return braces[0] + base + braces[1];
}
if (recurseTimes < 0) {
if (isRegExp(value)) {
return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
} else {
return ctx.stylize('[Object]', 'special');
}
}
ctx.seen.push(value);
var output;
if (array) {
output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
} else {
output = keys.map(function(key) {
return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
});
}
ctx.seen.pop();
return reduceToSingleString(output, base, braces);
}
function formatPrimitive(ctx, value) {
if (isUndefined(value))
return ctx.stylize('undefined', 'undefined');
if (isString(value)) {
var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
.replace(/'/g, "\\'")
.replace(/\\"/g, '"') + '\'';
return ctx.stylize(simple, 'string');
}
if (isNumber(value))
return ctx.stylize('' + value, 'number');
if (isBoolean(value))
return ctx.stylize('' + value, 'boolean');
// For some reason typeof null is "object", so special case here.
if (isNull(value))
return ctx.stylize('null', 'null');
}
function formatError(value) {
return '[' + Error.prototype.toString.call(value) + ']';
}
function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
var output = [];
for (var i = 0, l = value.length; i < l; ++i) {
if (hasOwnProperty(value, String(i))) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
String(i), true));
} else {
output.push('');
}
}
keys.forEach(function(key) {
if (!key.match(/^\d+$/)) {
output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
key, true));
}
});
return output;
}
function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
var name, str, desc;
desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
if (desc.get) {
if (desc.set) {
str = ctx.stylize('[Getter/Setter]', 'special');
} else {
str = ctx.stylize('[Getter]', 'special');
}
} else {
if (desc.set) {
str = ctx.stylize('[Setter]', 'special');
}
}
if (!hasOwnProperty(visibleKeys, key)) {
name = '[' + key + ']';
}
if (!str) {
if (ctx.seen.indexOf(desc.value) < 0) {
if (isNull(recurseTimes)) {
str = formatValue(ctx, desc.value, null);
} else {
str = formatValue(ctx, desc.value, recurseTimes - 1);
}
if (str.indexOf('\n') > -1) {
if (array) {
str = str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n').substr(2);
} else {
str = '\n' + str.split('\n').map(function(line) {
return ' ' + line;
}).join('\n');
}
}
} else {
str = ctx.stylize('[Circular]', 'special');
}
}
if (isUndefined(name)) {
if (array && key.match(/^\d+$/)) {
return str;
}
name = JSON.stringify('' + key);
if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
name = name.substr(1, name.length - 2);
name = ctx.stylize(name, 'name');
} else {
name = name.replace(/'/g, "\\'")
.replace(/\\"/g, '"')
.replace(/(^"|"$)/g, "'");
name = ctx.stylize(name, 'string');
}
}
return name + ': ' + str;
}
function reduceToSingleString(output, base, braces) {
var numLinesEst = 0;
var length = output.reduce(function(prev, cur) {
numLinesEst++;
if (cur.indexOf('\n') >= 0) numLinesEst++;
return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
}, 0);
if (length > 60) {
return braces[0] +
(base === '' ? '' : base + '\n ') +
' ' +
output.join(',\n ') +
' ' +
braces[1];
}
return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
}
// NOTE: These type checking functions intentionally don't use `instanceof`
// because it is fragile and can be easily faked with `Object.create()`.
function isArray(ar) {
return Array.isArray(ar);
}
exports.isArray = isArray;
function isBoolean(arg) {
return typeof arg === 'boolean';
}
exports.isBoolean = isBoolean;
function isNull(arg) {
return arg === null;
}
exports.isNull = isNull;
function isNullOrUndefined(arg) {
return arg == null;
}
exports.isNullOrUndefined = isNullOrUndefined;
function isNumber(arg) {
return typeof arg === 'number';
}
exports.isNumber = isNumber;
function isString(arg) {
return typeof arg === 'string';
}
exports.isString = isString;
function isSymbol(arg) {
return typeof arg === 'symbol';
}
exports.isSymbol = isSymbol;
function isUndefined(arg) {
return arg === void 0;
}
exports.isUndefined = isUndefined;
function isRegExp(re) {
return isObject(re) && objectToString(re) === '[object RegExp]';
}
exports.isRegExp = isRegExp;
function isObject(arg) {
return typeof arg === 'object' && arg !== null;
}
exports.isObject = isObject;
function isDate(d) {
return isObject(d) && objectToString(d) === '[object Date]';
}
exports.isDate = isDate;
function isError(e) {
return isObject(e) &&
(objectToString(e) === '[object Error]' || e instanceof Error);
}
exports.isError = isError;
function isFunction(arg) {
return typeof arg === 'function';
}
exports.isFunction = isFunction;
function isPrimitive(arg) {
return arg === null ||
typeof arg === 'boolean' ||
typeof arg === 'number' ||
typeof arg === 'string' ||
typeof arg === 'symbol' || // ES6 symbol
typeof arg === 'undefined';
}
exports.isPrimitive = isPrimitive;
exports.isBuffer = __webpack_require__(100);
function objectToString(o) {
return Object.prototype.toString.call(o);
}
function pad(n) {
return n < 10 ? '0' + n.toString(10) : n.toString(10);
}
var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
'Oct', 'Nov', 'Dec'];
// 26 Feb 16:19:34
function timestamp() {
var d = new Date();
var time = [pad(d.getHours()),
pad(d.getMinutes()),
pad(d.getSeconds())].join(':');
return [d.getDate(), months[d.getMonth()], time].join(' ');
}
// log is just a thin wrapper to console.log that prepends a timestamp
exports.log = function() {
console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
};
/**
* Inherit the prototype methods from one constructor into another.
*
* The Function.prototype.inherits from lang.js rewritten as a standalone
* function (not on Function.prototype). NOTE: If this file is to be loaded
* during bootstrapping this function needs to be rewritten using some native
* functions as prototype setup using normal JavaScript does not work as
* expected during bootstrapping (see mirror.js in r114903).
*
* @param {function} ctor Constructor function which needs to inherit the
* prototype.
* @param {function} superCtor Constructor function to inherit prototype from.
*/
exports.inherits = __webpack_require__(101);
exports._extend = function(origin, add) {
// Don't do anything if add isn't an object
if (!add || !isObject(add)) return origin;
var keys = Object.keys(add);
var i = keys.length;
while (i--) {
origin[keys[i]] = add[keys[i]];
}
return origin;
};
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(9)))
/***/ }),
/* 27 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a duplex stream is just a stream that is both readable and writable.
// Since JS doesn't have multiple prototypal inheritance, this class
// prototypally inherits from Readable, and then parasitically from
// Writable.
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
/*<replacement>*/
var objectKeys = Object.keys || function (obj) {
var keys = [];
for (var key in obj) {
keys.push(key);
}return keys;
};
/*</replacement>*/
module.exports = Duplex;
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
var Readable = __webpack_require__(71);
var Writable = __webpack_require__(74);
util.inherits(Duplex, Readable);
var keys = objectKeys(Writable.prototype);
for (var v = 0; v < keys.length; v++) {
var method = keys[v];
if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
}
function Duplex(options) {
if (!(this instanceof Duplex)) return new Duplex(options);
Readable.call(this, options);
Writable.call(this, options);
if (options && options.readable === false) this.readable = false;
if (options && options.writable === false) this.writable = false;
this.allowHalfOpen = true;
if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
this.once('end', onend);
}
// the no-half-open enforcer
function onend() {
// if we allow half-open state, or if the writable side ended,
// then we're ok.
if (this.allowHalfOpen || this._writableState.ended) return;
// no more data can be written.
// But allow more writes to happen in this tick.
processNextTick(onEndNT, this);
}
function onEndNT(self) {
self.end();
}
Object.defineProperty(Duplex.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined || this._writableState === undefined) {
return false;
}
return this._readableState.destroyed && this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (this._readableState === undefined || this._writableState === undefined) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
this._writableState.destroyed = value;
}
});
Duplex.prototype._destroy = function (err, cb) {
this.push(null);
this.end();
processNextTick(cb, err);
};
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
/***/ }),
/* 28 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {return typeof obj;} : function (obj) {return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;};var assert = __webpack_require__(2);
var coreTypes = __webpack_require__(285);var
quality =
coreTypes.quality;var _coreTypes$binary = coreTypes.binary;var bytesToHex = _coreTypes$binary.bytesToHex;var signingData = _coreTypes$binary.signingData;var signingClaimData = _coreTypes$binary.signingClaimData;var multiSigningData = _coreTypes$binary.multiSigningData;var binaryToJSON = _coreTypes$binary.binaryToJSON;var serializeObject = _coreTypes$binary.serializeObject;var BinaryParser = _coreTypes$binary.BinaryParser;
function decodeLedgerData(binary) {
assert(typeof binary === 'string', 'binary must be a hex string');
var parser = new BinaryParser(binary);
return {
ledger_index: parser.readUInt32(),
total_coins: parser.readType(coreTypes.UInt64).valueOf().toString(),
parent_hash: parser.readType(coreTypes.Hash256).toHex(),
transaction_hash: parser.readType(coreTypes.Hash256).toHex(),
account_hash: parser.readType(coreTypes.Hash256).toHex(),
parent_close_time: parser.readUInt32(),
close_time: parser.readUInt32(),
close_time_resolution: parser.readUInt8(),
close_flags: parser.readUInt8() };}
function decode(binary) {
assert(typeof binary === 'string', 'binary must be a hex string');
return binaryToJSON(binary);}
function encode(json) {
assert((typeof json === 'undefined' ? 'undefined' : _typeof(json)) === 'object');
return bytesToHex(serializeObject(json));}
function encodeForSigning(json) {
assert((typeof json === 'undefined' ? 'undefined' : _typeof(json)) === 'object');
return bytesToHex(signingData(json));}
function encodeForSigningClaim(json) {
assert((typeof json === 'undefined' ? 'undefined' : _typeof(json)) === 'object');
return bytesToHex(signingClaimData(json));}
function encodeForMultisigning(json, signer) {
assert((typeof json === 'undefined' ? 'undefined' : _typeof(json)) === 'object');
assert.equal(json.SigningPubKey, '');
return bytesToHex(multiSigningData(json, signer));}
function encodeQuality(value) {
assert(typeof value === 'string');
return bytesToHex(quality.encode(value));}
function decodeQuality(value) {
assert(typeof value === 'string');
return quality.decode(value).toString();}
module.exports = {
decode: decode,
encode: encode,
encodeForSigning: encodeForSigning,
encodeForSigningClaim: encodeForSigningClaim,
encodeForMultisigning: encodeForMultisigning,
encodeQuality: encodeQuality,
decodeQuality: decodeQuality,
decodeLedgerData: decodeLedgerData };
/***/ }),
/* 29 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _slicedToArray = function () {function sliceIterator(arr, i) {var _arr = [];var _n = true;var _d = false;var _e = undefined;try {for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {_arr.push(_s.value);if (i && _arr.length === i) break;}} catch (err) {_d = true;_e = err;} finally {try {if (!_n && _i["return"]) _i["return"]();} finally {if (_d) throw _e;}}return _arr;}return function (arr, i) {if (Array.isArray(arr)) {return arr;} else if (Symbol.iterator in Object(arr)) {return sliceIterator(arr, i);} else {throw new TypeError("Invalid attempt to destructure non-iterable instance");}};}();var assert = __webpack_require__(2);
var _ = __webpack_require__(1);var _require =
__webpack_require__(10);var parseBytes = _require.parseBytes;var serializeUIntN = _require.serializeUIntN;
var makeClass = __webpack_require__(4);
var enums = __webpack_require__(286);
function transformWith(func, obj) {
return _.transform(obj, func);}
function biMap(obj, valueKey) {
return _.transform(obj, function (result, value, key) {
result[key] = value;
result[value[valueKey]] = value;});}
var EnumType = makeClass({
EnumType: function EnumType(definition) {
_.assign(this, definition);
// At minimum
assert(this.bytes instanceof Uint8Array);
assert(typeof this.ordinal === 'number');
assert(typeof this.name === 'string');},
toString: function toString() {
return this.name;},
toJSON: function toJSON() {
return this.name;},
toBytesSink: function toBytesSink(sink) {
sink.put(this.bytes);},
statics: {
ordinalByteWidth: 1,
fromParser: function fromParser(parser) {
return this.from(parser.readUIntN(this.ordinalByteWidth));},
from: function from(val) {
var ret = val instanceof this ? val : this[val];
if (!ret) {
throw new Error(
val + ' is not a valid name or ordinal for ' + this.enumName);}
return ret;},
valuesByName: function valuesByName() {var _this = this;
return _.transform(this.initVals, function (result, ordinal, name) {
var bytes = serializeUIntN(ordinal, _this.ordinalByteWidth);
var type = new _this({ name: name, ordinal: ordinal, bytes: bytes });
result[name] = type;});},
init: function init() {
var mapped = this.valuesByName();
_.assign(this, biMap(mapped, 'ordinal'));
this.values = _.values(mapped);
return this;} } });
function makeEnum(name, definition) {
return makeClass({
inherits: EnumType,
statics: _.assign(definition, { enumName: name }) });}
function makeEnums(to, definition, name) {
to[name] = makeEnum(name, definition);}
var Enums = transformWith(makeEnums, {
Type: {
initVals: enums.TYPES },
LedgerEntryType: {
initVals: enums.LEDGER_ENTRY_TYPES, ordinalByteWidth: 2 },
TransactionType: {
initVals: enums.TRANSACTION_TYPES, ordinalByteWidth: 2 },
TransactionResult: {
initVals: enums.TRANSACTION_RESULTS, ordinalByteWidth: 1 } });
Enums.Field = makeClass({
inherits: EnumType,
statics: {
enumName: 'Field',
initVals: enums.FIELDS,
valuesByName: function valuesByName() {var _this2 = this;
var fields = _.map(this.initVals, function (_ref) {var _ref2 = _slicedToArray(_ref, 2);var name = _ref2[0];var definition = _ref2[1];
var type = Enums.Type[definition.type];
var bytes = _this2.header(type.ordinal, definition.nth);
var ordinal = type.ordinal << 16 | definition.nth;
var extra = { ordinal: ordinal, name: name, type: type, bytes: bytes };
return new _this2(_.assign(definition, extra));});
return _.keyBy(fields, 'name');},
header: function header(type, nth) {
var name = nth;
var header = [];
var push = header.push.bind(header);
if (type < 16) {
if (name < 16) {
push(type << 4 | name);} else
{
push(type << 4, name);}} else
if (name < 16) {
push(name, type);} else
{
push(0, type, name);}
return parseBytes(header, Uint8Array);} } });
module.exports = Enums;
/***/ }),
/* 30 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) {
'use strict';
// Utils
function assert (val, msg) {
if (!val) throw new Error(msg || 'Assertion failed');
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits (ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN (number, base, endian) {
if (BN.isBN(number)) {
return number;
}
this.negative = 0;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (number !== null) {
if (base === 'le' || base === 'be') {
endian = base;
base = 10;
}
this._init(number || 0, base || 10, endian || 'be');
}
}
if (typeof module === 'object') {
module.exports = BN;
} else {
exports.BN = BN;
}
BN.BN = BN;
BN.wordSize = 26;
var Buffer;
try {
Buffer = __webpack_require__(288).Buffer;
} catch (e) {
}
BN.isBN = function isBN (num) {
if (num instanceof BN) {
return true;
}
return num !== null && typeof num === 'object' &&
num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
};
BN.max = function max (left, right) {
if (left.cmp(right) > 0) return left;
return right;
};
BN.min = function min (left, right) {
if (left.cmp(right) < 0) return left;
return right;
};
BN.prototype._init = function init (number, base, endian) {
if (typeof number === 'number') {
return this._initNumber(number, base, endian);
}
if (typeof number === 'object') {
return this._initArray(number, base, endian);
}
if (base === 'hex') {
base = 16;
}
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, '');
var start = 0;
if (number[0] === '-') {
start++;
}
if (base === 16) {
this._parseHex(number, start);
} else {
this._parseBase(number, base, start);
}
if (number[0] === '-') {
this.negative = 1;
}
this.strip();
if (endian !== 'le') return;
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initNumber = function _initNumber (number, base, endian) {
if (number < 0) {
this.negative = 1;
number = -number;
}
if (number < 0x4000000) {
this.words = [ number & 0x3ffffff ];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== 'le') return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray (number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === 'number');
if (number.length <= 0) {
this.words = [ 0 ];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
var j, w;
var off = 0;
if (endian === 'be') {
for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
} else if (endian === 'le') {
for (i = 0, j = 0; i < number.length; i += 3) {
w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
}
return this.strip();
};
function parseHex (str, start, end) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r <<= 4;
// 'a' - 'f'
if (c >= 49 && c <= 54) {
r |= c - 49 + 0xa;
// 'A' - 'F'
} else if (c >= 17 && c <= 22) {
r |= c - 17 + 0xa;
// '0' - '9'
} else {
r |= c & 0xf;
}
}
return r;
}
BN.prototype._parseHex = function _parseHex (number, start) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
this.words[i] = 0;
}
var j, w;
// Scan 24-bit chunks and add them to the number
var off = 0;
for (i = number.length - 6, j = 0; i >= start; i -= 6) {
w = parseHex(number, i, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
// NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
if (i + 6 !== start) {
w = parseHex(number, start, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
}
this.strip();
};
function parseBase (str, start, end, mul) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49) {
r += c - 49 + 0xa;
// 'A'
} else if (c >= 17) {
r += c - 17 + 0xa;
// '0' - '9'
} else {
r += c;
}
}
return r;
}
BN.prototype._parseBase = function _parseBase (number, base, start) {
// Initialize as zero
this.words = [ 0 ];
this.length = 1;
// Find length of limb in base
for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
limbLen++;
}
limbLen--;
limbPow = (limbPow / base) | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for (var i = start; i < end; i += limbLen) {
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
if (mod !== 0) {
var pow = 1;
word = parseBase(number, i, number.length, base);
for (i = 0; i < mod; i++) {
pow *= base;
}
this.imuln(pow);
if (this.words[0] + word < 0x4000000) {
this.words[0] += word;
} else {
this._iaddn(word);
}
}
};
BN.prototype.copy = function copy (dest) {
dest.words = new Array(this.length);
for (var i = 0; i < this.length; i++) {
dest.words[i] = this.words[i];
}
dest.length = this.length;
dest.negative = this.negative;
dest.red = this.red;
};
BN.prototype.clone = function clone () {
var r = new BN(null);
this.copy(r);
return r;
};
BN.prototype._expand = function _expand (size) {
while (this.length < size) {
this.words[this.length++] = 0;
}
return this;
};
// Remove leading `0` from `this`
BN.prototype.strip = function strip () {
while (this.length > 1 && this.words[this.length - 1] === 0) {
this.length--;
}
return this._normSign();
};
BN.prototype._normSign = function _normSign () {
// -0 = 0
if (this.length === 1 && this.words[0] === 0) {
this.negative = 0;
}
return this;
};
BN.prototype.inspect = function inspect () {
return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
};
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/
var zeros = [
'',
'0',
'00',
'000',
'0000',
'00000',
'000000',
'0000000',
'00000000',
'000000000',
'0000000000',
'00000000000',
'000000000000',
'0000000000000',
'00000000000000',
'000000000000000',
'0000000000000000',
'00000000000000000',
'000000000000000000',
'0000000000000000000',
'00000000000000000000',
'000000000000000000000',
'0000000000000000000000',
'00000000000000000000000',
'000000000000000000000000',
'0000000000000000000000000'
];
var groupSizes = [
0, 0,
25, 16, 12, 11, 10, 9, 8,
8, 7, 7, 7, 7, 6, 6,
6, 6, 6, 6, 6, 5, 5,
5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5
];
var groupBases = [
0, 0,
33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
];
BN.prototype.toString = function toString (base, padding) {
base = base || 10;
padding = padding | 0 || 1;
var out;
if (base === 16 || base === 'hex') {
out = '';
var off = 0;
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i];
var word = (((w << off) | carry) & 0xffffff).toString(16);
carry = (w >>> (24 - off)) & 0xffffff;
if (carry !== 0 || i !== this.length - 1) {
out = zeros[6 - word.length] + word + out;
} else {
out = word + out;
}
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
}
if (carry !== 0) {
out = carry.toString(16) + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
out = '';
var c = this.clone();
c.negative = 0;
while (!c.isZero()) {
var r = c.modn(groupBase).toString(base);
c = c.idivn(groupBase);
if (!c.isZero()) {
out = zeros[groupSize - r.length] + r + out;
} else {
out = r + out;
}
}
if (this.isZero()) {
out = '0' + out;
}
while (out.length % padding !== 0) {
out = '0' + out;
}
if (this.negative !== 0) {
out = '-' + out;
}
return out;
}
assert(false, 'Base should be between 2 and 36');
};
BN.prototype.toNumber = function toNumber () {
var ret = this.words[0];
if (this.length === 2) {
ret += this.words[1] * 0x4000000;
} else if (this.length === 3 && this.words[2] === 0x01) {
// NOTE: at this stage it is known that the top bit is set
ret += 0x10000000000000 + (this.words[1] * 0x4000000);
} else if (this.length > 2) {
assert(false, 'Number can only safely store up to 53 bits');
}
return (this.negative !== 0) ? -ret : ret;
};
BN.prototype.toJSON = function toJSON () {
return this.toString(16);
};
BN.prototype.toBuffer = function toBuffer (endian, length) {
assert(typeof Buffer !== 'undefined');
return this.toArrayLike(Buffer, endian, length);
};
BN.prototype.toArray = function toArray (endian, length) {
return this.toArrayLike(Array, endian, length);
};
BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
var byteLength = this.byteLength();
var reqLength = length || Math.max(1, byteLength);
assert(byteLength <= reqLength, 'byte array longer than desired length');
assert(reqLength > 0, 'Requested array length <= 0');
this.strip();
var littleEndian = endian === 'le';
var res = new ArrayType(reqLength);
var b, i;
var q = this.clone();
if (!littleEndian) {
// Assume big-endian
for (i = 0; i < reqLength - byteLength; i++) {
res[i] = 0;
}
for (i = 0; !q.isZero(); i++) {
b = q.andln(0xff);
q.iushrn(8);
res[reqLength - i - 1] = b;
}
} else {
for (i = 0; !q.isZero(); i++) {
b = q.andln(0xff);
q.iushrn(8);
res[i] = b;
}
for (; i < reqLength; i++) {
res[i] = 0;
}
}
return res;
};
if (Math.clz32) {
BN.prototype._countBits = function _countBits (w) {
return 32 - Math.clz32(w);
};
} else {
BN.prototype._countBits = function _countBits (w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
}
BN.prototype._zeroBits = function _zeroBits (w) {
// Short-cut
if (w === 0) return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0) {
r++;
}
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength () {
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray (num) {
var w = new Array(num.bitLength());
for (var bit = 0; bit < w.length; bit++) {
var off = (bit / 26) | 0;
var wbit = bit % 26;
w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits () {
if (this.isZero()) return 0;
var r = 0;
for (var i = 0; i < this.length; i++) {
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26) break;
}
return r;
};
BN.prototype.byteLength = function byteLength () {
return Math.ceil(this.bitLength() / 8);
};
BN.prototype.toTwos = function toTwos (width) {
if (this.negative !== 0) {
return this.abs().inotn(width).iaddn(1);
}
return this.clone();
};
BN.prototype.fromTwos = function fromTwos (width) {
if (this.testn(width - 1)) {
return this.notn(width).iaddn(1).ineg();
}
return this.clone();
};
BN.prototype.isNeg = function isNeg () {
return this.negative !== 0;
};
// Return negative clone of `this`
BN.prototype.neg = function neg () {
return this.clone().ineg();
};
BN.prototype.ineg = function ineg () {
if (!this.isZero()) {
this.negative ^= 1;
}
return this;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor (num) {
while (this.length < num.length) {
this.words[this.length++] = 0;
}
for (var i = 0; i < num.length; i++) {
this.words[i] = this.words[i] | num.words[i];
}
return this.strip();
};
BN.prototype.ior = function ior (num) {
assert((this.negative | num.negative) === 0);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or (num) {
if (this.length > num.length) return this.clone().ior(num);
return num.clone().ior(this);
};
BN.prototype.uor = function uor (num) {
if (this.length > num.length) return this.clone().iuor(num);
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand (num) {
// b = min-length(num, this)
var b;
if (this.length > num.length) {
b = num;
} else {
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = this.words[i] & num.words[i];
}
this.length = b.length;
return this.strip();
};
BN.prototype.iand = function iand (num) {
assert((this.negative | num.negative) === 0);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and (num) {
if (this.length > num.length) return this.clone().iand(num);
return num.clone().iand(this);
};
BN.prototype.uand = function uand (num) {
if (this.length > num.length) return this.clone().iuand(num);
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor (num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for (var i = 0; i < b.length; i++) {
this.words[i] = a.words[i] ^ b.words[i];
}
if (this !== a) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = a.length;
return this.strip();
};
BN.prototype.ixor = function ixor (num) {
assert((this.negative | num.negative) === 0);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor (num) {
if (this.length > num.length) return this.clone().ixor(num);
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor (num) {
if (this.length > num.length) return this.clone().iuxor(num);
return num.clone().iuxor(this);
};
// Not ``this`` with ``width`` bitwidth
BN.prototype.inotn = function inotn (width) {
assert(typeof width === 'number' && width >= 0);
var bytesNeeded = Math.ceil(width / 26) | 0;
var bitsLeft = width % 26;
// Extend the buffer with leading zeroes
this._expand(bytesNeeded);
if (bitsLeft > 0) {
bytesNeeded--;
}
// Handle complete words
for (var i = 0; i < bytesNeeded; i++) {
this.words[i] = ~this.words[i] & 0x3ffffff;
}
// Handle the residue
if (bitsLeft > 0) {
this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
}
// And remove leading zeroes
return this.strip();
};
BN.prototype.notn = function notn (width) {
return this.clone().inotn(width);
};
// Set `bit` of `this`
BN.prototype.setn = function setn (bit, val) {
assert(typeof bit === 'number' && bit >= 0);
var off = (bit / 26) | 0;
var wbit = bit % 26;
this._expand(off + 1);
if (val) {
this.words[off] = this.words[off] | (1 << wbit);
} else {
this.words[off] = this.words[off] & ~(1 << wbit);
}
return this.strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd (num) {
var r;
// negative + positive
if (this.negative !== 0 && num.negative === 0) {
this.negative = 0;
r = this.isub(num);
this.negative ^= 1;
return this._normSign();
// positive + negative
} else if (this.negative === 0 && num.negative !== 0) {
num.negative = 0;
r = this.isub(num);
num.negative = 1;
return r._normSign();
}
// a.length > b.length
var a, b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
return this;
};
// Add `num` to `this`
BN.prototype.add = function add (num) {
var res;
if (num.negative !== 0 && this.negative === 0) {
num.negative = 0;
res = this.sub(num);
num.negative ^= 1;
return res;
} else if (num.negative === 0 && this.negative !== 0) {
this.negative = 0;
res = num.sub(this);
this.negative = 1;
return res;
}
if (this.length > num.length) return this.clone().iadd(num);
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub (num) {
// this - (-num) = this + num
if (num.negative !== 0) {
num.negative = 0;
var r = this.iadd(num);
num.negative = 1;
return r._normSign();
// -this - num = -(this + num)
} else if (this.negative !== 0) {
this.negative = 0;
this.iadd(num);
this.negative = 1;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.negative = 0;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a, b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for (; carry !== 0 && i < a.length; i++) {
r = (a.words[i] | 0) + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this) {
for (; i < a.length; i++) {
this.words[i] = a.words[i];
}
}
this.length = Math.max(this.length, i);
if (a !== this) {
this.negative = 1;
}
return this.strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub (num) {
return this.clone().isub(num);
};
function smallMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
var len = (self.length + num.length) | 0;
out.length = len;
len = (len - 1) | 0;
// Peel one iteration (compiler can't do it, because of code complexity)
var a = self.words[0] | 0;
var b = num.words[0] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
var carry = (r / 0x4000000) | 0;
out.words[0] = lo;
for (var k = 1; k < len; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = (k - j) | 0;
a = self.words[i] | 0;
b = num.words[j] | 0;
r = a * b + rword;
ncarry += (r / 0x4000000) | 0;
rword = r & 0x3ffffff;
}
out.words[k] = rword | 0;
carry = ncarry | 0;
}
if (carry !== 0) {
out.words[k] = carry | 0;
} else {
out.length--;
}
return out.strip();
}
// TODO(indutny): it may be reasonable to omit it for users who don't need
// to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
// multiplication (like elliptic secp256k1).
var comb10MulTo = function comb10MulTo (self, num, out) {
var a = self.words;
var b = num.words;
var o = out.words;
var c = 0;
var lo;
var mid;
var hi;
var a0 = a[0] | 0;
var al0 = a0 & 0x1fff;
var ah0 = a0 >>> 13;
var a1 = a[1] | 0;
var al1 = a1 & 0x1fff;
var ah1 = a1 >>> 13;
var a2 = a[2] | 0;
var al2 = a2 & 0x1fff;
var ah2 = a2 >>> 13;
var a3 = a[3] | 0;
var al3 = a3 & 0x1fff;
var ah3 = a3 >>> 13;
var a4 = a[4] | 0;
var al4 = a4 & 0x1fff;
var ah4 = a4 >>> 13;
var a5 = a[5] | 0;
var al5 = a5 & 0x1fff;
var ah5 = a5 >>> 13;
var a6 = a[6] | 0;
var al6 = a6 & 0x1fff;
var ah6 = a6 >>> 13;
var a7 = a[7] | 0;
var al7 = a7 & 0x1fff;
var ah7 = a7 >>> 13;
var a8 = a[8] | 0;
var al8 = a8 & 0x1fff;
var ah8 = a8 >>> 13;
var a9 = a[9] | 0;
var al9 = a9 & 0x1fff;
var ah9 = a9 >>> 13;
var b0 = b[0] | 0;
var bl0 = b0 & 0x1fff;
var bh0 = b0 >>> 13;
var b1 = b[1] | 0;
var bl1 = b1 & 0x1fff;
var bh1 = b1 >>> 13;
var b2 = b[2] | 0;
var bl2 = b2 & 0x1fff;
var bh2 = b2 >>> 13;
var b3 = b[3] | 0;
var bl3 = b3 & 0x1fff;
var bh3 = b3 >>> 13;
var b4 = b[4] | 0;
var bl4 = b4 & 0x1fff;
var bh4 = b4 >>> 13;
var b5 = b[5] | 0;
var bl5 = b5 & 0x1fff;
var bh5 = b5 >>> 13;
var b6 = b[6] | 0;
var bl6 = b6 & 0x1fff;
var bh6 = b6 >>> 13;
var b7 = b[7] | 0;
var bl7 = b7 & 0x1fff;
var bh7 = b7 >>> 13;
var b8 = b[8] | 0;
var bl8 = b8 & 0x1fff;
var bh8 = b8 >>> 13;
var b9 = b[9] | 0;
var bl9 = b9 & 0x1fff;
var bh9 = b9 >>> 13;
out.negative = self.negative ^ num.negative;
out.length = 19;
/* k = 0 */
lo = Math.imul(al0, bl0);
mid = Math.imul(al0, bh0);
mid = (mid + Math.imul(ah0, bl0)) | 0;
hi = Math.imul(ah0, bh0);
var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
w0 &= 0x3ffffff;
/* k = 1 */
lo = Math.imul(al1, bl0);
mid = Math.imul(al1, bh0);
mid = (mid + Math.imul(ah1, bl0)) | 0;
hi = Math.imul(ah1, bh0);
lo = (lo + Math.imul(al0, bl1)) | 0;
mid = (mid + Math.imul(al0, bh1)) | 0;
mid = (mid + Math.imul(ah0, bl1)) | 0;
hi = (hi + Math.imul(ah0, bh1)) | 0;
var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
w1 &= 0x3ffffff;
/* k = 2 */
lo = Math.imul(al2, bl0);
mid = Math.imul(al2, bh0);
mid = (mid + Math.imul(ah2, bl0)) | 0;
hi = Math.imul(ah2, bh0);
lo = (lo + Math.imul(al1, bl1)) | 0;
mid = (mid + Math.imul(al1, bh1)) | 0;
mid = (mid + Math.imul(ah1, bl1)) | 0;
hi = (hi + Math.imul(ah1, bh1)) | 0;
lo = (lo + Math.imul(al0, bl2)) | 0;
mid = (mid + Math.imul(al0, bh2)) | 0;
mid = (mid + Math.imul(ah0, bl2)) | 0;
hi = (hi + Math.imul(ah0, bh2)) | 0;
var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
w2 &= 0x3ffffff;
/* k = 3 */
lo = Math.imul(al3, bl0);
mid = Math.imul(al3, bh0);
mid = (mid + Math.imul(ah3, bl0)) | 0;
hi = Math.imul(ah3, bh0);
lo = (lo + Math.imul(al2, bl1)) | 0;
mid = (mid + Math.imul(al2, bh1)) | 0;
mid = (mid + Math.imul(ah2, bl1)) | 0;
hi = (hi + Math.imul(ah2, bh1)) | 0;
lo = (lo + Math.imul(al1, bl2)) | 0;
mid = (mid + Math.imul(al1, bh2)) | 0;
mid = (mid + Math.imul(ah1, bl2)) | 0;
hi = (hi + Math.imul(ah1, bh2)) | 0;
lo = (lo + Math.imul(al0, bl3)) | 0;
mid = (mid + Math.imul(al0, bh3)) | 0;
mid = (mid + Math.imul(ah0, bl3)) | 0;
hi = (hi + Math.imul(ah0, bh3)) | 0;
var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
w3 &= 0x3ffffff;
/* k = 4 */
lo = Math.imul(al4, bl0);
mid = Math.imul(al4, bh0);
mid = (mid + Math.imul(ah4, bl0)) | 0;
hi = Math.imul(ah4, bh0);
lo = (lo + Math.imul(al3, bl1)) | 0;
mid = (mid + Math.imul(al3, bh1)) | 0;
mid = (mid + Math.imul(ah3, bl1)) | 0;
hi = (hi + Math.imul(ah3, bh1)) | 0;
lo = (lo + Math.imul(al2, bl2)) | 0;
mid = (mid + Math.imul(al2, bh2)) | 0;
mid = (mid + Math.imul(ah2, bl2)) | 0;
hi = (hi + Math.imul(ah2, bh2)) | 0;
lo = (lo + Math.imul(al1, bl3)) | 0;
mid = (mid + Math.imul(al1, bh3)) | 0;
mid = (mid + Math.imul(ah1, bl3)) | 0;
hi = (hi + Math.imul(ah1, bh3)) | 0;
lo = (lo + Math.imul(al0, bl4)) | 0;
mid = (mid + Math.imul(al0, bh4)) | 0;
mid = (mid + Math.imul(ah0, bl4)) | 0;
hi = (hi + Math.imul(ah0, bh4)) | 0;
var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
w4 &= 0x3ffffff;
/* k = 5 */
lo = Math.imul(al5, bl0);
mid = Math.imul(al5, bh0);
mid = (mid + Math.imul(ah5, bl0)) | 0;
hi = Math.imul(ah5, bh0);
lo = (lo + Math.imul(al4, bl1)) | 0;
mid = (mid + Math.imul(al4, bh1)) | 0;
mid = (mid + Math.imul(ah4, bl1)) | 0;
hi = (hi + Math.imul(ah4, bh1)) | 0;
lo = (lo + Math.imul(al3, bl2)) | 0;
mid = (mid + Math.imul(al3, bh2)) | 0;
mid = (mid + Math.imul(ah3, bl2)) | 0;
hi = (hi + Math.imul(ah3, bh2)) | 0;
lo = (lo + Math.imul(al2, bl3)) | 0;
mid = (mid + Math.imul(al2, bh3)) | 0;
mid = (mid + Math.imul(ah2, bl3)) | 0;
hi = (hi + Math.imul(ah2, bh3)) | 0;
lo = (lo + Math.imul(al1, bl4)) | 0;
mid = (mid + Math.imul(al1, bh4)) | 0;
mid = (mid + Math.imul(ah1, bl4)) | 0;
hi = (hi + Math.imul(ah1, bh4)) | 0;
lo = (lo + Math.imul(al0, bl5)) | 0;
mid = (mid + Math.imul(al0, bh5)) | 0;
mid = (mid + Math.imul(ah0, bl5)) | 0;
hi = (hi + Math.imul(ah0, bh5)) | 0;
var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
w5 &= 0x3ffffff;
/* k = 6 */
lo = Math.imul(al6, bl0);
mid = Math.imul(al6, bh0);
mid = (mid + Math.imul(ah6, bl0)) | 0;
hi = Math.imul(ah6, bh0);
lo = (lo + Math.imul(al5, bl1)) | 0;
mid = (mid + Math.imul(al5, bh1)) | 0;
mid = (mid + Math.imul(ah5, bl1)) | 0;
hi = (hi + Math.imul(ah5, bh1)) | 0;
lo = (lo + Math.imul(al4, bl2)) | 0;
mid = (mid + Math.imul(al4, bh2)) | 0;
mid = (mid + Math.imul(ah4, bl2)) | 0;
hi = (hi + Math.imul(ah4, bh2)) | 0;
lo = (lo + Math.imul(al3, bl3)) | 0;
mid = (mid + Math.imul(al3, bh3)) | 0;
mid = (mid + Math.imul(ah3, bl3)) | 0;
hi = (hi + Math.imul(ah3, bh3)) | 0;
lo = (lo + Math.imul(al2, bl4)) | 0;
mid = (mid + Math.imul(al2, bh4)) | 0;
mid = (mid + Math.imul(ah2, bl4)) | 0;
hi = (hi + Math.imul(ah2, bh4)) | 0;
lo = (lo + Math.imul(al1, bl5)) | 0;
mid = (mid + Math.imul(al1, bh5)) | 0;
mid = (mid + Math.imul(ah1, bl5)) | 0;
hi = (hi + Math.imul(ah1, bh5)) | 0;
lo = (lo + Math.imul(al0, bl6)) | 0;
mid = (mid + Math.imul(al0, bh6)) | 0;
mid = (mid + Math.imul(ah0, bl6)) | 0;
hi = (hi + Math.imul(ah0, bh6)) | 0;
var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
w6 &= 0x3ffffff;
/* k = 7 */
lo = Math.imul(al7, bl0);
mid = Math.imul(al7, bh0);
mid = (mid + Math.imul(ah7, bl0)) | 0;
hi = Math.imul(ah7, bh0);
lo = (lo + Math.imul(al6, bl1)) | 0;
mid = (mid + Math.imul(al6, bh1)) | 0;
mid = (mid + Math.imul(ah6, bl1)) | 0;
hi = (hi + Math.imul(ah6, bh1)) | 0;
lo = (lo + Math.imul(al5, bl2)) | 0;
mid = (mid + Math.imul(al5, bh2)) | 0;
mid = (mid + Math.imul(ah5, bl2)) | 0;
hi = (hi + Math.imul(ah5, bh2)) | 0;
lo = (lo + Math.imul(al4, bl3)) | 0;
mid = (mid + Math.imul(al4, bh3)) | 0;
mid = (mid + Math.imul(ah4, bl3)) | 0;
hi = (hi + Math.imul(ah4, bh3)) | 0;
lo = (lo + Math.imul(al3, bl4)) | 0;
mid = (mid + Math.imul(al3, bh4)) | 0;
mid = (mid + Math.imul(ah3, bl4)) | 0;
hi = (hi + Math.imul(ah3, bh4)) | 0;
lo = (lo + Math.imul(al2, bl5)) | 0;
mid = (mid + Math.imul(al2, bh5)) | 0;
mid = (mid + Math.imul(ah2, bl5)) | 0;
hi = (hi + Math.imul(ah2, bh5)) | 0;
lo = (lo + Math.imul(al1, bl6)) | 0;
mid = (mid + Math.imul(al1, bh6)) | 0;
mid = (mid + Math.imul(ah1, bl6)) | 0;
hi = (hi + Math.imul(ah1, bh6)) | 0;
lo = (lo + Math.imul(al0, bl7)) | 0;
mid = (mid + Math.imul(al0, bh7)) | 0;
mid = (mid + Math.imul(ah0, bl7)) | 0;
hi = (hi + Math.imul(ah0, bh7)) | 0;
var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
w7 &= 0x3ffffff;
/* k = 8 */
lo = Math.imul(al8, bl0);
mid = Math.imul(al8, bh0);
mid = (mid + Math.imul(ah8, bl0)) | 0;
hi = Math.imul(ah8, bh0);
lo = (lo + Math.imul(al7, bl1)) | 0;
mid = (mid + Math.imul(al7, bh1)) | 0;
mid = (mid + Math.imul(ah7, bl1)) | 0;
hi = (hi + Math.imul(ah7, bh1)) | 0;
lo = (lo + Math.imul(al6, bl2)) | 0;
mid = (mid + Math.imul(al6, bh2)) | 0;
mid = (mid + Math.imul(ah6, bl2)) | 0;
hi = (hi + Math.imul(ah6, bh2)) | 0;
lo = (lo + Math.imul(al5, bl3)) | 0;
mid = (mid + Math.imul(al5, bh3)) | 0;
mid = (mid + Math.imul(ah5, bl3)) | 0;
hi = (hi + Math.imul(ah5, bh3)) | 0;
lo = (lo + Math.imul(al4, bl4)) | 0;
mid = (mid + Math.imul(al4, bh4)) | 0;
mid = (mid + Math.imul(ah4, bl4)) | 0;
hi = (hi + Math.imul(ah4, bh4)) | 0;
lo = (lo + Math.imul(al3, bl5)) | 0;
mid = (mid + Math.imul(al3, bh5)) | 0;
mid = (mid + Math.imul(ah3, bl5)) | 0;
hi = (hi + Math.imul(ah3, bh5)) | 0;
lo = (lo + Math.imul(al2, bl6)) | 0;
mid = (mid + Math.imul(al2, bh6)) | 0;
mid = (mid + Math.imul(ah2, bl6)) | 0;
hi = (hi + Math.imul(ah2, bh6)) | 0;
lo = (lo + Math.imul(al1, bl7)) | 0;
mid = (mid + Math.imul(al1, bh7)) | 0;
mid = (mid + Math.imul(ah1, bl7)) | 0;
hi = (hi + Math.imul(ah1, bh7)) | 0;
lo = (lo + Math.imul(al0, bl8)) | 0;
mid = (mid + Math.imul(al0, bh8)) | 0;
mid = (mid + Math.imul(ah0, bl8)) | 0;
hi = (hi + Math.imul(ah0, bh8)) | 0;
var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
w8 &= 0x3ffffff;
/* k = 9 */
lo = Math.imul(al9, bl0);
mid = Math.imul(al9, bh0);
mid = (mid + Math.imul(ah9, bl0)) | 0;
hi = Math.imul(ah9, bh0);
lo = (lo + Math.imul(al8, bl1)) | 0;
mid = (mid + Math.imul(al8, bh1)) | 0;
mid = (mid + Math.imul(ah8, bl1)) | 0;
hi = (hi + Math.imul(ah8, bh1)) | 0;
lo = (lo + Math.imul(al7, bl2)) | 0;
mid = (mid + Math.imul(al7, bh2)) | 0;
mid = (mid + Math.imul(ah7, bl2)) | 0;
hi = (hi + Math.imul(ah7, bh2)) | 0;
lo = (lo + Math.imul(al6, bl3)) | 0;
mid = (mid + Math.imul(al6, bh3)) | 0;
mid = (mid + Math.imul(ah6, bl3)) | 0;
hi = (hi + Math.imul(ah6, bh3)) | 0;
lo = (lo + Math.imul(al5, bl4)) | 0;
mid = (mid + Math.imul(al5, bh4)) | 0;
mid = (mid + Math.imul(ah5, bl4)) | 0;
hi = (hi + Math.imul(ah5, bh4)) | 0;
lo = (lo + Math.imul(al4, bl5)) | 0;
mid = (mid + Math.imul(al4, bh5)) | 0;
mid = (mid + Math.imul(ah4, bl5)) | 0;
hi = (hi + Math.imul(ah4, bh5)) | 0;
lo = (lo + Math.imul(al3, bl6)) | 0;
mid = (mid + Math.imul(al3, bh6)) | 0;
mid = (mid + Math.imul(ah3, bl6)) | 0;
hi = (hi + Math.imul(ah3, bh6)) | 0;
lo = (lo + Math.imul(al2, bl7)) | 0;
mid = (mid + Math.imul(al2, bh7)) | 0;
mid = (mid + Math.imul(ah2, bl7)) | 0;
hi = (hi + Math.imul(ah2, bh7)) | 0;
lo = (lo + Math.imul(al1, bl8)) | 0;
mid = (mid + Math.imul(al1, bh8)) | 0;
mid = (mid + Math.imul(ah1, bl8)) | 0;
hi = (hi + Math.imul(ah1, bh8)) | 0;
lo = (lo + Math.imul(al0, bl9)) | 0;
mid = (mid + Math.imul(al0, bh9)) | 0;
mid = (mid + Math.imul(ah0, bl9)) | 0;
hi = (hi + Math.imul(ah0, bh9)) | 0;
var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
w9 &= 0x3ffffff;
/* k = 10 */
lo = Math.imul(al9, bl1);
mid = Math.imul(al9, bh1);
mid = (mid + Math.imul(ah9, bl1)) | 0;
hi = Math.imul(ah9, bh1);
lo = (lo + Math.imul(al8, bl2)) | 0;
mid = (mid + Math.imul(al8, bh2)) | 0;
mid = (mid + Math.imul(ah8, bl2)) | 0;
hi = (hi + Math.imul(ah8, bh2)) | 0;
lo = (lo + Math.imul(al7, bl3)) | 0;
mid = (mid + Math.imul(al7, bh3)) | 0;
mid = (mid + Math.imul(ah7, bl3)) | 0;
hi = (hi + Math.imul(ah7, bh3)) | 0;
lo = (lo + Math.imul(al6, bl4)) | 0;
mid = (mid + Math.imul(al6, bh4)) | 0;
mid = (mid + Math.imul(ah6, bl4)) | 0;
hi = (hi + Math.imul(ah6, bh4)) | 0;
lo = (lo + Math.imul(al5, bl5)) | 0;
mid = (mid + Math.imul(al5, bh5)) | 0;
mid = (mid + Math.imul(ah5, bl5)) | 0;
hi = (hi + Math.imul(ah5, bh5)) | 0;
lo = (lo + Math.imul(al4, bl6)) | 0;
mid = (mid + Math.imul(al4, bh6)) | 0;
mid = (mid + Math.imul(ah4, bl6)) | 0;
hi = (hi + Math.imul(ah4, bh6)) | 0;
lo = (lo + Math.imul(al3, bl7)) | 0;
mid = (mid + Math.imul(al3, bh7)) | 0;
mid = (mid + Math.imul(ah3, bl7)) | 0;
hi = (hi + Math.imul(ah3, bh7)) | 0;
lo = (lo + Math.imul(al2, bl8)) | 0;
mid = (mid + Math.imul(al2, bh8)) | 0;
mid = (mid + Math.imul(ah2, bl8)) | 0;
hi = (hi + Math.imul(ah2, bh8)) | 0;
lo = (lo + Math.imul(al1, bl9)) | 0;
mid = (mid + Math.imul(al1, bh9)) | 0;
mid = (mid + Math.imul(ah1, bl9)) | 0;
hi = (hi + Math.imul(ah1, bh9)) | 0;
var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
w10 &= 0x3ffffff;
/* k = 11 */
lo = Math.imul(al9, bl2);
mid = Math.imul(al9, bh2);
mid = (mid + Math.imul(ah9, bl2)) | 0;
hi = Math.imul(ah9, bh2);
lo = (lo + Math.imul(al8, bl3)) | 0;
mid = (mid + Math.imul(al8, bh3)) | 0;
mid = (mid + Math.imul(ah8, bl3)) | 0;
hi = (hi + Math.imul(ah8, bh3)) | 0;
lo = (lo + Math.imul(al7, bl4)) | 0;
mid = (mid + Math.imul(al7, bh4)) | 0;
mid = (mid + Math.imul(ah7, bl4)) | 0;
hi = (hi + Math.imul(ah7, bh4)) | 0;
lo = (lo + Math.imul(al6, bl5)) | 0;
mid = (mid + Math.imul(al6, bh5)) | 0;
mid = (mid + Math.imul(ah6, bl5)) | 0;
hi = (hi + Math.imul(ah6, bh5)) | 0;
lo = (lo + Math.imul(al5, bl6)) | 0;
mid = (mid + Math.imul(al5, bh6)) | 0;
mid = (mid + Math.imul(ah5, bl6)) | 0;
hi = (hi + Math.imul(ah5, bh6)) | 0;
lo = (lo + Math.imul(al4, bl7)) | 0;
mid = (mid + Math.imul(al4, bh7)) | 0;
mid = (mid + Math.imul(ah4, bl7)) | 0;
hi = (hi + Math.imul(ah4, bh7)) | 0;
lo = (lo + Math.imul(al3, bl8)) | 0;
mid = (mid + Math.imul(al3, bh8)) | 0;
mid = (mid + Math.imul(ah3, bl8)) | 0;
hi = (hi + Math.imul(ah3, bh8)) | 0;
lo = (lo + Math.imul(al2, bl9)) | 0;
mid = (mid + Math.imul(al2, bh9)) | 0;
mid = (mid + Math.imul(ah2, bl9)) | 0;
hi = (hi + Math.imul(ah2, bh9)) | 0;
var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
w11 &= 0x3ffffff;
/* k = 12 */
lo = Math.imul(al9, bl3);
mid = Math.imul(al9, bh3);
mid = (mid + Math.imul(ah9, bl3)) | 0;
hi = Math.imul(ah9, bh3);
lo = (lo + Math.imul(al8, bl4)) | 0;
mid = (mid + Math.imul(al8, bh4)) | 0;
mid = (mid + Math.imul(ah8, bl4)) | 0;
hi = (hi + Math.imul(ah8, bh4)) | 0;
lo = (lo + Math.imul(al7, bl5)) | 0;
mid = (mid + Math.imul(al7, bh5)) | 0;
mid = (mid + Math.imul(ah7, bl5)) | 0;
hi = (hi + Math.imul(ah7, bh5)) | 0;
lo = (lo + Math.imul(al6, bl6)) | 0;
mid = (mid + Math.imul(al6, bh6)) | 0;
mid = (mid + Math.imul(ah6, bl6)) | 0;
hi = (hi + Math.imul(ah6, bh6)) | 0;
lo = (lo + Math.imul(al5, bl7)) | 0;
mid = (mid + Math.imul(al5, bh7)) | 0;
mid = (mid + Math.imul(ah5, bl7)) | 0;
hi = (hi + Math.imul(ah5, bh7)) | 0;
lo = (lo + Math.imul(al4, bl8)) | 0;
mid = (mid + Math.imul(al4, bh8)) | 0;
mid = (mid + Math.imul(ah4, bl8)) | 0;
hi = (hi + Math.imul(ah4, bh8)) | 0;
lo = (lo + Math.imul(al3, bl9)) | 0;
mid = (mid + Math.imul(al3, bh9)) | 0;
mid = (mid + Math.imul(ah3, bl9)) | 0;
hi = (hi + Math.imul(ah3, bh9)) | 0;
var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
w12 &= 0x3ffffff;
/* k = 13 */
lo = Math.imul(al9, bl4);
mid = Math.imul(al9, bh4);
mid = (mid + Math.imul(ah9, bl4)) | 0;
hi = Math.imul(ah9, bh4);
lo = (lo + Math.imul(al8, bl5)) | 0;
mid = (mid + Math.imul(al8, bh5)) | 0;
mid = (mid + Math.imul(ah8, bl5)) | 0;
hi = (hi + Math.imul(ah8, bh5)) | 0;
lo = (lo + Math.imul(al7, bl6)) | 0;
mid = (mid + Math.imul(al7, bh6)) | 0;
mid = (mid + Math.imul(ah7, bl6)) | 0;
hi = (hi + Math.imul(ah7, bh6)) | 0;
lo = (lo + Math.imul(al6, bl7)) | 0;
mid = (mid + Math.imul(al6, bh7)) | 0;
mid = (mid + Math.imul(ah6, bl7)) | 0;
hi = (hi + Math.imul(ah6, bh7)) | 0;
lo = (lo + Math.imul(al5, bl8)) | 0;
mid = (mid + Math.imul(al5, bh8)) | 0;
mid = (mid + Math.imul(ah5, bl8)) | 0;
hi = (hi + Math.imul(ah5, bh8)) | 0;
lo = (lo + Math.imul(al4, bl9)) | 0;
mid = (mid + Math.imul(al4, bh9)) | 0;
mid = (mid + Math.imul(ah4, bl9)) | 0;
hi = (hi + Math.imul(ah4, bh9)) | 0;
var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
w13 &= 0x3ffffff;
/* k = 14 */
lo = Math.imul(al9, bl5);
mid = Math.imul(al9, bh5);
mid = (mid + Math.imul(ah9, bl5)) | 0;
hi = Math.imul(ah9, bh5);
lo = (lo + Math.imul(al8, bl6)) | 0;
mid = (mid + Math.imul(al8, bh6)) | 0;
mid = (mid + Math.imul(ah8, bl6)) | 0;
hi = (hi + Math.imul(ah8, bh6)) | 0;
lo = (lo + Math.imul(al7, bl7)) | 0;
mid = (mid + Math.imul(al7, bh7)) | 0;
mid = (mid + Math.imul(ah7, bl7)) | 0;
hi = (hi + Math.imul(ah7, bh7)) | 0;
lo = (lo + Math.imul(al6, bl8)) | 0;
mid = (mid + Math.imul(al6, bh8)) | 0;
mid = (mid + Math.imul(ah6, bl8)) | 0;
hi = (hi + Math.imul(ah6, bh8)) | 0;
lo = (lo + Math.imul(al5, bl9)) | 0;
mid = (mid + Math.imul(al5, bh9)) | 0;
mid = (mid + Math.imul(ah5, bl9)) | 0;
hi = (hi + Math.imul(ah5, bh9)) | 0;
var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
w14 &= 0x3ffffff;
/* k = 15 */
lo = Math.imul(al9, bl6);
mid = Math.imul(al9, bh6);
mid = (mid + Math.imul(ah9, bl6)) | 0;
hi = Math.imul(ah9, bh6);
lo = (lo + Math.imul(al8, bl7)) | 0;
mid = (mid + Math.imul(al8, bh7)) | 0;
mid = (mid + Math.imul(ah8, bl7)) | 0;
hi = (hi + Math.imul(ah8, bh7)) | 0;
lo = (lo + Math.imul(al7, bl8)) | 0;
mid = (mid + Math.imul(al7, bh8)) | 0;
mid = (mid + Math.imul(ah7, bl8)) | 0;
hi = (hi + Math.imul(ah7, bh8)) | 0;
lo = (lo + Math.imul(al6, bl9)) | 0;
mid = (mid + Math.imul(al6, bh9)) | 0;
mid = (mid + Math.imul(ah6, bl9)) | 0;
hi = (hi + Math.imul(ah6, bh9)) | 0;
var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
w15 &= 0x3ffffff;
/* k = 16 */
lo = Math.imul(al9, bl7);
mid = Math.imul(al9, bh7);
mid = (mid + Math.imul(ah9, bl7)) | 0;
hi = Math.imul(ah9, bh7);
lo = (lo + Math.imul(al8, bl8)) | 0;
mid = (mid + Math.imul(al8, bh8)) | 0;
mid = (mid + Math.imul(ah8, bl8)) | 0;
hi = (hi + Math.imul(ah8, bh8)) | 0;
lo = (lo + Math.imul(al7, bl9)) | 0;
mid = (mid + Math.imul(al7, bh9)) | 0;
mid = (mid + Math.imul(ah7, bl9)) | 0;
hi = (hi + Math.imul(ah7, bh9)) | 0;
var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
w16 &= 0x3ffffff;
/* k = 17 */
lo = Math.imul(al9, bl8);
mid = Math.imul(al9, bh8);
mid = (mid + Math.imul(ah9, bl8)) | 0;
hi = Math.imul(ah9, bh8);
lo = (lo + Math.imul(al8, bl9)) | 0;
mid = (mid + Math.imul(al8, bh9)) | 0;
mid = (mid + Math.imul(ah8, bl9)) | 0;
hi = (hi + Math.imul(ah8, bh9)) | 0;
var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
w17 &= 0x3ffffff;
/* k = 18 */
lo = Math.imul(al9, bl9);
mid = Math.imul(al9, bh9);
mid = (mid + Math.imul(ah9, bl9)) | 0;
hi = Math.imul(ah9, bh9);
var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
w18 &= 0x3ffffff;
o[0] = w0;
o[1] = w1;
o[2] = w2;
o[3] = w3;
o[4] = w4;
o[5] = w5;
o[6] = w6;
o[7] = w7;
o[8] = w8;
o[9] = w9;
o[10] = w10;
o[11] = w11;
o[12] = w12;
o[13] = w13;
o[14] = w14;
o[15] = w15;
o[16] = w16;
o[17] = w17;
o[18] = w18;
if (c !== 0) {
o[19] = c;
out.length++;
}
return out;
};
// Polyfill comb
if (!Math.imul) {
comb10MulTo = smallMulTo;
}
function bigMulTo (self, num, out) {
out.negative = num.negative ^ self.negative;
out.length = self.length + num.length;
var carry = 0;
var hncarry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = self.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out.strip();
}
function jumboMulTo (self, num, out) {
var fftm = new FFTM();
return fftm.mulp(self, num, out);
}
BN.prototype.mulTo = function mulTo (num, out) {
var res;
var len = this.length + num.length;
if (this.length === 10 && num.length === 10) {
res = comb10MulTo(this, num, out);
} else if (len < 63) {
res = smallMulTo(this, num, out);
} else if (len < 1024) {
res = bigMulTo(this, num, out);
} else {
res = jumboMulTo(this, num, out);
}
return res;
};
// Cooley-Tukey algorithm for FFT
// slightly revisited to rely on looping instead of recursion
function FFTM (x, y) {
this.x = x;
this.y = y;
}
FFTM.prototype.makeRBT = function makeRBT (N) {
var t = new Array(N);
var l = BN.prototype._countBits(N) - 1;
for (var i = 0; i < N; i++) {
t[i] = this.revBin(i, l, N);
}
return t;
};
// Returns binary-reversed representation of `x`
FFTM.prototype.revBin = function revBin (x, l, N) {
if (x === 0 || x === N - 1) return x;
var rb = 0;
for (var i = 0; i < l; i++) {
rb |= (x & 1) << (l - i - 1);
x >>= 1;
}
return rb;
};
// Performs "tweedling" phase, therefore 'emulating'
// behaviour of the recursive algorithm
FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
for (var i = 0; i < N; i++) {
rtws[i] = rws[rbt[i]];
itws[i] = iws[rbt[i]];
}
};
FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
this.permute(rbt, rws, iws, rtws, itws, N);
for (var s = 1; s < N; s <<= 1) {
var l = s << 1;
var rtwdf = Math.cos(2 * Math.PI / l);
var itwdf = Math.sin(2 * Math.PI / l);
for (var p = 0; p < N; p += l) {
var rtwdf_ = rtwdf;
var itwdf_ = itwdf;
for (var j = 0; j < s; j++) {
var re = rtws[p + j];
var ie = itws[p + j];
var ro = rtws[p + j + s];
var io = itws[p + j + s];
var rx = rtwdf_ * ro - itwdf_ * io;
io = rtwdf_ * io + itwdf_ * ro;
ro = rx;
rtws[p + j] = re + ro;
itws[p + j] = ie + io;
rtws[p + j + s] = re - ro;
itws[p + j + s] = ie - io;
/* jshint maxdepth : false */
if (j !== l) {
rx = rtwdf * rtwdf_ - itwdf * itwdf_;
itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
rtwdf_ = rx;
}
}
}
}
};
FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
var N = Math.max(m, n) | 1;
var odd = N & 1;
var i = 0;
for (N = N / 2 | 0; N; N = N >>> 1) {
i++;
}
return 1 << i + 1 + odd;
};
FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
if (N <= 1) return;
for (var i = 0; i < N / 2; i++) {
var t = rws[i];
rws[i] = rws[N - i - 1];
rws[N - i - 1] = t;
t = iws[i];
iws[i] = -iws[N - i - 1];
iws[N - i - 1] = -t;
}
};
FFTM.prototype.normalize13b = function normalize13b (ws, N) {
var carry = 0;
for (var i = 0; i < N / 2; i++) {
var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
Math.round(ws[2 * i] / N) +
carry;
ws[i] = w & 0x3ffffff;
if (w < 0x4000000) {
carry = 0;
} else {
carry = w / 0x4000000 | 0;
}
}
return ws;
};
FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
var carry = 0;
for (var i = 0; i < len; i++) {
carry = carry + (ws[i] | 0);
rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
}
// Pad with zeroes
for (i = 2 * len; i < N; ++i) {
rws[i] = 0;
}
assert(carry === 0);
assert((carry & ~0x1fff) === 0);
};
FFTM.prototype.stub = function stub (N) {
var ph = new Array(N);
for (var i = 0; i < N; i++) {
ph[i] = 0;
}
return ph;
};
FFTM.prototype.mulp = function mulp (x, y, out) {
var N = 2 * this.guessLen13b(x.length, y.length);
var rbt = this.makeRBT(N);
var _ = this.stub(N);
var rws = new Array(N);
var rwst = new Array(N);
var iwst = new Array(N);
var nrws = new Array(N);
var nrwst = new Array(N);
var niwst = new Array(N);
var rmws = out.words;
rmws.length = N;
this.convert13b(x.words, x.length, rws, N);
this.convert13b(y.words, y.length, nrws, N);
this.transform(rws, _, rwst, iwst, N, rbt);
this.transform(nrws, _, nrwst, niwst, N, rbt);
for (var i = 0; i < N; i++) {
var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
rwst[i] = rx;
}
this.conjugate(rwst, iwst, N);
this.transform(rwst, iwst, rmws, _, N, rbt);
this.conjugate(rmws, _, N);
this.normalize13b(rmws, N);
out.negative = x.negative ^ y.negative;
out.length = x.length + y.length;
return out.strip();
};
// Multiply `this` by `num`
BN.prototype.mul = function mul (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// Multiply employing FFT
BN.prototype.mulf = function mulf (num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return jumboMulTo(this, num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul (num) {
return this.clone().mulTo(num, this);
};
BN.prototype.imuln = function imuln (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
// Carry
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = (this.words[i] | 0) * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += (w / 0x4000000) | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.muln = function muln (num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr () {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr () {
return this.imul(this.clone());
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow (num) {
var w = toBitArray(num);
if (w.length === 0) return new BN(1);
// Skip leading zeroes
var res = this;
for (var i = 0; i < w.length; i++, res = res.sqr()) {
if (w[i] !== 0) break;
}
if (++i < w.length) {
for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
if (w[i] === 0) continue;
res = res.mul(q);
}
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
var i;
if (r !== 0) {
var carry = 0;
for (i = 0; i < this.length; i++) {
var newCarry = this.words[i] & carryMask;
var c = ((this.words[i] | 0) - newCarry) << r;
this.words[i] = c | carry;
carry = newCarry >>> (26 - r);
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for (i = this.length - 1; i >= 0; i--) {
this.words[i + s] = this.words[i];
}
for (i = 0; i < s; i++) {
this.words[i] = 0;
}
this.length += s;
}
return this.strip();
};
BN.prototype.ishln = function ishln (bits) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn (bits, hint, extended) {
assert(typeof bits === 'number' && bits >= 0);
var h;
if (hint) {
h = (hint - (hint % 26)) / 26;
} else {
h = 0;
}
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for (var i = 0; i < s; i++) {
maskedWords.words[i] = this.words[i];
}
maskedWords.length = s;
}
if (s === 0) {
// No-op, we should not move anything at all
} else if (this.length > s) {
this.length -= s;
for (i = 0; i < this.length; i++) {
this.words[i] = this.words[i + s];
}
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
var word = this.words[i] | 0;
this.words[i] = (carry << (26 - r)) | (word >>> r);
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0) {
maskedWords.words[maskedWords.length++] = carry;
}
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
return this.strip();
};
BN.prototype.ishrn = function ishrn (bits, hint, extended) {
// TODO(indutny): implement me
assert(this.negative === 0);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln (bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln (bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn (bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn (bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn (bit) {
assert(typeof bit === 'number' && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) return false;
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn (bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(this.negative === 0, 'imaskn works only with positive numbers');
if (this.length <= s) {
return this;
}
if (r !== 0) {
s++;
}
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
this.words[this.length - 1] &= mask;
}
return this.strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn (bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.isubn(-num);
// Possible sign change
if (this.negative !== 0) {
if (this.length === 1 && (this.words[0] | 0) < num) {
this.words[0] = num - (this.words[0] | 0);
this.negative = 0;
return this;
}
this.negative = 0;
this.isubn(num);
this.negative = 1;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn (num) {
this.words[0] += num;
// Carry
for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
this.words[i] -= 0x4000000;
if (i === this.length - 1) {
this.words[i + 1] = 1;
} else {
this.words[i + 1]++;
}
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn (num) {
assert(typeof num === 'number');
assert(num < 0x4000000);
if (num < 0) return this.iaddn(-num);
if (this.negative !== 0) {
this.negative = 0;
this.iaddn(num);
this.negative = 1;
return this;
}
this.words[0] -= num;
if (this.length === 1 && this.words[0] < 0) {
this.words[0] = -this.words[0];
this.negative = 1;
} else {
// Carry
for (var i = 0; i < this.length && this.words[i] < 0; i++) {
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
}
return this.strip();
};
BN.prototype.addn = function addn (num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn (num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs () {
this.negative = 0;
return this;
};
BN.prototype.abs = function abs () {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
var len = num.length + shift;
var i;
this._expand(len);
var w;
var carry = 0;
for (i = 0; i < num.length; i++) {
w = (this.words[i + shift] | 0) + carry;
var right = (num.words[i] | 0) * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - ((right / 0x4000000) | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for (; i < this.length - shift; i++) {
w = (this.words[i + shift] | 0) + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0) return this.strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for (i = 0; i < this.length; i++) {
w = -(this.words[i] | 0) + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.negative = 1;
return this.strip();
};
BN.prototype._wordDiv = function _wordDiv (num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1] | 0;
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1] | 0;
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== 'mod') {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for (var i = 0; i < q.length; i++) {
q.words[i] = 0;
}
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (diff.negative === 0) {
a = diff;
if (q) {
q.words[m] = 1;
}
}
for (var j = m - 1; j >= 0; j--) {
var qj = (a.words[b.length + j] | 0) * 0x4000000 +
(a.words[b.length + j - 1] | 0);
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min((qj / bhi) | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while (a.negative !== 0) {
qj--;
a.negative = 0;
a._ishlnsubmul(b, 1, j);
if (!a.isZero()) {
a.negative ^= 1;
}
}
if (q) {
q.words[j] = qj;
}
}
if (q) {
q.strip();
}
a.strip();
// Denormalize
if (mode !== 'div' && shift !== 0) {
a.iushrn(shift);
}
return {
div: q || null,
mod: a
};
};
// NOTE: 1) `mode` can be set to `mod` to request mod only,
// to `div` to request div only, or be absent to
// request both div & mod
// 2) `positive` is true if unsigned mod is requested
BN.prototype.divmod = function divmod (num, mode, positive) {
assert(!num.isZero());
if (this.isZero()) {
return {
div: new BN(0),
mod: new BN(0)
};
}
var div, mod, res;
if (this.negative !== 0 && num.negative === 0) {
res = this.neg().divmod(num, mode);
if (mode !== 'mod') {
div = res.div.neg();
}
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.iadd(num);
}
}
return {
div: div,
mod: mod
};
}
if (this.negative === 0 && num.negative !== 0) {
res = this.divmod(num.neg(), mode);
if (mode !== 'mod') {
div = res.div.neg();
}
return {
div: div,
mod: res.mod
};
}
if ((this.negative & num.negative) !== 0) {
res = this.neg().divmod(num.neg(), mode);
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.negative !== 0) {
mod.isub(num);
}
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0) {
return {
div: new BN(0),
mod: this
};
}
// Very short reduction
if (num.length === 1) {
if (mode === 'div') {
return {
div: this.divn(num.words[0]),
mod: null
};
}
if (mode === 'mod') {
return {
div: null,
mod: new BN(this.modn(num.words[0]))
};
}
return {
div: this.divn(num.words[0]),
mod: new BN(this.modn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div (num) {
return this.divmod(num, 'div', false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod (num) {
return this.divmod(num, 'mod', false).mod;
};
BN.prototype.umod = function umod (num) {
return this.divmod(num, 'mod', true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound (num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.isZero()) return dm.div;
var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
// Round up
return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modn = function modn (num) {
assert(num <= 0x3ffffff);
var p = (1 << 26) % num;
var acc = 0;
for (var i = this.length - 1; i >= 0; i--) {
acc = (p * acc + (this.words[i] | 0)) % num;
}
return acc;
};
// In-place division by number
BN.prototype.idivn = function idivn (num) {
assert(num <= 0x3ffffff);
var carry = 0;
for (var i = this.length - 1; i >= 0; i--) {
var w = (this.words[i] | 0) + carry * 0x4000000;
this.words[i] = (w / num) | 0;
carry = w % num;
}
return this.strip();
};
BN.prototype.divn = function divn (num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd (p) {
assert(p.negative === 0);
assert(!p.isZero());
var x = this;
var y = p.clone();
if (x.negative !== 0) {
x = x.umod(p);
} else {
x = x.clone();
}
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while (x.isEven() && y.isEven()) {
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while (!x.isZero()) {
for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
x.iushrn(i);
while (i-- > 0) {
if (A.isOdd() || B.isOdd()) {
A.iadd(yp);
B.isub(xp);
}
A.iushrn(1);
B.iushrn(1);
}
}
for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
y.iushrn(j);
while (j-- > 0) {
if (C.isOdd() || D.isOdd()) {
C.iadd(yp);
D.isub(xp);
}
C.iushrn(1);
D.iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp (p) {
assert(p.negative === 0);
assert(!p.isZero());
var a = this;
var b = p.clone();
if (a.negative !== 0) {
a = a.umod(p);
} else {
a = a.clone();
}
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
if (i > 0) {
a.iushrn(i);
while (i-- > 0) {
if (x1.isOdd()) {
x1.iadd(delta);
}
x1.iushrn(1);
}
}
for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
if (j > 0) {
b.iushrn(j);
while (j-- > 0) {
if (x2.isOdd()) {
x2.iadd(delta);
}
x2.iushrn(1);
}
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0) {
res = x1;
} else {
res = x2;
}
if (res.cmpn(0) < 0) {
res.iadd(p);
}
return res;
};
BN.prototype.gcd = function gcd (num) {
if (this.isZero()) return num.abs();
if (num.isZero()) return this.abs();
var a = this.clone();
var b = num.clone();
a.negative = 0;
b.negative = 0;
// Remove common factor of two
for (var shift = 0; a.isEven() && b.isEven(); shift++) {
a.iushrn(1);
b.iushrn(1);
}
do {
while (a.isEven()) {
a.iushrn(1);
}
while (b.isEven()) {
b.iushrn(1);
}
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) {
break;
}
a.isub(b);
} while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm (num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven () {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd () {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln (num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn (bit) {
assert(typeof bit === 'number');
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
this._expand(s + 1);
this.words[s] |= q;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for (var i = s; carry !== 0 && i < this.length; i++) {
var w = this.words[i] | 0;
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.isZero = function isZero () {
return this.length === 1 && this.words[0] === 0;
};
BN.prototype.cmpn = function cmpn (num) {
var negative = num < 0;
if (this.negative !== 0 && !negative) return -1;
if (this.negative === 0 && negative) return 1;
this.strip();
var res;
if (this.length > 1) {
res = 1;
} else {
if (negative) {
num = -num;
}
assert(num <= 0x3ffffff, 'Number is too big');
var w = this.words[0] | 0;
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.negative !== 0) return -res | 0;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp (num) {
if (this.negative !== 0 && num.negative === 0) return -1;
if (this.negative === 0 && num.negative !== 0) return 1;
var res = this.ucmp(num);
if (this.negative !== 0) return -res | 0;
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp (num) {
// At this point both numbers have the same sign
if (this.length > num.length) return 1;
if (this.length < num.length) return -1;
var res = 0;
for (var i = this.length - 1; i >= 0; i--) {
var a = this.words[i] | 0;
var b = num.words[i] | 0;
if (a === b) continue;
if (a < b) {
res = -1;
} else if (a > b) {
res = 1;
}
break;
}
return res;
};
BN.prototype.gtn = function gtn (num) {
return this.cmpn(num) === 1;
};
BN.prototype.gt = function gt (num) {
return this.cmp(num) === 1;
};
BN.prototype.gten = function gten (num) {
return this.cmpn(num) >= 0;
};
BN.prototype.gte = function gte (num) {
return this.cmp(num) >= 0;
};
BN.prototype.ltn = function ltn (num) {
return this.cmpn(num) === -1;
};
BN.prototype.lt = function lt (num) {
return this.cmp(num) === -1;
};
BN.prototype.lten = function lten (num) {
return this.cmpn(num) <= 0;
};
BN.prototype.lte = function lte (num) {
return this.cmp(num) <= 0;
};
BN.prototype.eqn = function eqn (num) {
return this.cmpn(num) === 0;
};
BN.prototype.eq = function eq (num) {
return this.cmp(num) === 0;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red (num) {
return new Red(num);
};
BN.prototype.toRed = function toRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
assert(this.negative === 0, 'red works only with positives');
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed () {
assert(this.red, 'fromRed works only with numbers in reduction context');
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed (ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed (ctx) {
assert(!this.red, 'Already a number in reduction context');
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd (num) {
assert(this.red, 'redAdd works only with red numbers');
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd (num) {
assert(this.red, 'redIAdd works only with red numbers');
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub (num) {
assert(this.red, 'redSub works only with red numbers');
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub (num) {
assert(this.red, 'redISub works only with red numbers');
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl (num) {
assert(this.red, 'redShl works only with red numbers');
return this.red.shl(this, num);
};
BN.prototype.redMul = function redMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul (num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr () {
assert(this.red, 'redSqr works only with red numbers');
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr () {
assert(this.red, 'redISqr works only with red numbers');
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt () {
assert(this.red, 'redSqrt works only with red numbers');
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm () {
assert(this.red, 'redInvm works only with red numbers');
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg () {
assert(this.red, 'redNeg works only with red numbers');
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow (num) {
assert(this.red && !num.red, 'redPow(normalNum)');
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime (name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp () {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce (num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
} while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) {
r.isub(this.p);
} else {
r.strip();
}
return r;
};
MPrime.prototype.split = function split (input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK (num) {
return num.imul(this.k);
};
function K256 () {
MPrime.call(
this,
'k256',
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
}
inherits(K256, MPrime);
K256.prototype.split = function split (input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for (var i = 0; i < outLen; i++) {
output.words[i] = input.words[i];
}
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for (i = 10; i < input.length; i++) {
var next = input.words[i] | 0;
input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
prev = next;
}
prev >>>= 22;
input.words[i - 10] = prev;
if (prev === 0 && input.length > 10) {
input.length -= 10;
} else {
input.length -= 9;
}
};
K256.prototype.imulK = function imulK (num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var lo = 0;
for (var i = 0; i < num.length; i++) {
var w = num.words[i] | 0;
lo += w * 0x3d1;
num.words[i] = lo & 0x3ffffff;
lo = w * 0x40 + ((lo / 0x4000000) | 0);
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0) {
num.length--;
}
}
return num;
};
function P224 () {
MPrime.call(
this,
'p224',
'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
}
inherits(P224, MPrime);
function P192 () {
MPrime.call(
this,
'p192',
'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
}
inherits(P192, MPrime);
function P25519 () {
// 2 ^ 255 - 19
MPrime.call(
this,
'25519',
'7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK (num) {
// K = 0x13
var carry = 0;
for (var i = 0; i < num.length; i++) {
var hi = (num.words[i] | 0) * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0) {
num.words[num.length++] = carry;
}
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime (name) {
// Cached version of prime
if (primes[name]) return primes[name];
var prime;
if (name === 'k256') {
prime = new K256();
} else if (name === 'p224') {
prime = new P224();
} else if (name === 'p192') {
prime = new P192();
} else if (name === 'p25519') {
prime = new P25519();
} else {
throw new Error('Unknown prime ' + name);
}
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red (m) {
if (typeof m === 'string') {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
assert(m.gtn(1), 'modulus must be greater than 1');
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1 (a) {
assert(a.negative === 0, 'red works only with positives');
assert(a.red, 'red works only with red numbers');
};
Red.prototype._verify2 = function _verify2 (a, b) {
assert((a.negative | b.negative) === 0, 'red works only with positives');
assert(a.red && a.red === b.red,
'red works only with red numbers');
};
Red.prototype.imod = function imod (a) {
if (this.prime) return this.prime.ireduce(a)._forceRed(this);
return a.umod(this.m)._forceRed(this);
};
Red.prototype.neg = function neg (a) {
if (a.isZero()) {
return a.clone();
}
return this.m.sub(a)._forceRed(this);
};
Red.prototype.add = function add (a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res._forceRed(this);
};
Red.prototype.iadd = function iadd (a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0) {
res.isub(this.m);
}
return res;
};
Red.prototype.sub = function sub (a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res._forceRed(this);
};
Red.prototype.isub = function isub (a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0) {
res.iadd(this.m);
}
return res;
};
Red.prototype.shl = function shl (a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul (a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul (a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr (a) {
return this.imul(a, a.clone());
};
Red.prototype.sqr = function sqr (a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt (a) {
if (a.isZero()) return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
return this.pow(a, pow);
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while (!q.isZero() && q.andln(1) === 0) {
s++;
q.iushrn(1);
}
assert(!q.isZero());
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while (this.pow(z, lpow).cmp(nOne) !== 0) {
z.redIAdd(nOne);
}
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while (t.cmp(one) !== 0) {
var tmp = t;
for (var i = 0; tmp.cmp(one) !== 0; i++) {
tmp = tmp.redSqr();
}
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm (a) {
var inv = a._invmp(this.m);
if (inv.negative !== 0) {
inv.negative = 0;
return this.imod(inv).redNeg();
} else {
return this.imod(inv);
}
};
Red.prototype.pow = function pow (a, num) {
if (num.isZero()) return new BN(1).toRed(this);
if (num.cmpn(1) === 0) return a.clone();
var windowSize = 4;
var wnd = new Array(1 << windowSize);
wnd[0] = new BN(1).toRed(this);
wnd[1] = a;
for (var i = 2; i < wnd.length; i++) {
wnd[i] = this.mul(wnd[i - 1], a);
}
var res = wnd[0];
var current = 0;
var currentLen = 0;
var start = num.bitLength() % 26;
if (start === 0) {
start = 26;
}
for (i = num.length - 1; i >= 0; i--) {
var word = num.words[i];
for (var j = start - 1; j >= 0; j--) {
var bit = (word >> j) & 1;
if (res !== wnd[0]) {
res = this.sqr(res);
}
if (bit === 0 && current === 0) {
currentLen = 0;
continue;
}
current <<= 1;
current |= bit;
currentLen++;
if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
res = this.mul(res, wnd[current]);
currentLen = 0;
current = 0;
}
start = 26;
}
return res;
};
Red.prototype.convertTo = function convertTo (num) {
var r = num.umod(this.m);
return r === num ? r.clone() : r;
};
Red.prototype.convertFrom = function convertFrom (num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont (num) {
return new Mont(num);
};
function Mont (m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0) {
this.shift += 26 - (this.shift % 26);
}
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo (num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom (num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul (a, b) {
if (a.isZero() || b.isZero()) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.mul = function mul (a, b) {
if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0) {
res = u.isub(this.m);
} else if (u.cmpn(0) < 0) {
res = u.iadd(this.m);
}
return res._forceRed(this);
};
Mont.prototype.invm = function invm (a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})(typeof module === 'undefined' || module, this);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(40)(module)))
/***/ }),
/* 31 */
/***/ (function(module, exports, __webpack_require__) {
var Buffer = __webpack_require__(8).Buffer
// prototype class for hash functions
function Hash (blockSize, finalSize) {
this._block = Buffer.alloc(blockSize)
this._finalSize = finalSize
this._blockSize = blockSize
this._len = 0
}
Hash.prototype.update = function (data, enc) {
if (typeof data === 'string') {
enc = enc || 'utf8'
data = Buffer.from(data, enc)
}
var block = this._block
var blockSize = this._blockSize
var length = data.length
var accum = this._len
for (var offset = 0; offset < length;) {
var assigned = accum % blockSize
var remainder = Math.min(length - offset, blockSize - assigned)
for (var i = 0; i < remainder; i++) {
block[assigned + i] = data[offset + i]
}
accum += remainder
offset += remainder
if ((accum % blockSize) === 0) {
this._update(block)
}
}
this._len += length
return this
}
Hash.prototype.digest = function (enc) {
var rem = this._len % this._blockSize
this._block[rem] = 0x80
// zero (rem + 1) trailing bits, where (rem + 1) is the smallest
// non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
this._block.fill(0, rem + 1)
if (rem >= this._finalSize) {
this._update(this._block)
this._block.fill(0)
}
var bits = this._len * 8
// uint32
if (bits <= 0xffffffff) {
this._block.writeUInt32BE(bits, this._blockSize - 4)
// uint64
} else {
var lowBits = (bits & 0xffffffff) >>> 0
var highBits = (bits - lowBits) / 0x100000000
this._block.writeUInt32BE(highBits, this._blockSize - 8)
this._block.writeUInt32BE(lowBits, this._blockSize - 4)
}
this._update(this._block)
var hash = this._hash()
return enc ? hash.toString(enc) : hash
}
Hash.prototype._update = function () {
throw new Error('_update must be implemented by subclass')
}
module.exports = Hash
/***/ }),
/* 32 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var uri = __webpack_require__(22);
var ValidationError = exports.ValidationError = function ValidationError (message, instance, schema, propertyPath, name, argument) {
if (propertyPath) {
this.property = propertyPath;
}
if (message) {
this.message = message;
}
if (schema) {
if (schema.id) {
this.schema = schema.id;
} else {
this.schema = schema;
}
}
if (instance) {
this.instance = instance;
}
this.name = name;
this.argument = argument;
this.stack = this.toString();
};
ValidationError.prototype.toString = function toString() {
return this.property + ' ' + this.message;
};
var ValidatorResult = exports.ValidatorResult = function ValidatorResult(instance, schema, options, ctx) {
this.instance = instance;
this.schema = schema;
this.propertyPath = ctx.propertyPath;
this.errors = [];
this.throwError = options && options.throwError;
this.disableFormat = options && options.disableFormat === true;
};
ValidatorResult.prototype.addError = function addError(detail) {
var err;
if (typeof detail == 'string') {
err = new ValidationError(detail, this.instance, this.schema, this.propertyPath);
} else {
if (!detail) throw new Error('Missing error detail');
if (!detail.message) throw new Error('Missing error message');
if (!detail.name) throw new Error('Missing validator type');
err = new ValidationError(detail.message, this.instance, this.schema, this.propertyPath, detail.name, detail.argument);
}
if (this.throwError) {
throw err;
}
this.errors.push(err);
return err;
};
ValidatorResult.prototype.importErrors = function importErrors(res) {
if (typeof res == 'string' || (res && res.validatorType)) {
this.addError(res);
} else if (res && res.errors) {
Array.prototype.push.apply(this.errors, res.errors);
}
};
function stringizer (v,i){
return i+': '+v.toString()+'\n';
}
ValidatorResult.prototype.toString = function toString(res) {
return this.errors.map(stringizer).join('');
};
Object.defineProperty(ValidatorResult.prototype, "valid", { get: function() {
return !this.errors.length;
} });
/**
* Describes a problem with a Schema which prevents validation of an instance
* @name SchemaError
* @constructor
*/
var SchemaError = exports.SchemaError = function SchemaError (msg, schema) {
this.message = msg;
this.schema = schema;
Error.call(this, msg);
Error.captureStackTrace(this, SchemaError);
};
SchemaError.prototype = Object.create(Error.prototype,
{ constructor: {value: SchemaError, enumerable: false}
, name: {value: 'SchemaError', enumerable: false}
});
var SchemaContext = exports.SchemaContext = function SchemaContext (schema, options, propertyPath, base, schemas) {
this.schema = schema;
this.options = options;
this.propertyPath = propertyPath;
this.base = base;
this.schemas = schemas;
};
SchemaContext.prototype.resolve = function resolve (target) {
return uri.resolve(this.base, target);
};
SchemaContext.prototype.makeChild = function makeChild(schema, propertyName){
var propertyPath = (propertyName===undefined) ? this.propertyPath : this.propertyPath+makeSuffix(propertyName);
var base = uri.resolve(this.base, schema.id||'');
var ctx = new SchemaContext(schema, this.options, propertyPath, base, Object.create(this.schemas));
if(schema.id && !ctx.schemas[base]){
ctx.schemas[base] = schema;
}
return ctx;
}
var FORMAT_REGEXPS = exports.FORMAT_REGEXPS = {
'date-time': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])[tT ](2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])(\.\d+)?([zZ]|[+-]([0-5][0-9]):(60|[0-5][0-9]))$/,
'date': /^\d{4}-(?:0[0-9]{1}|1[0-2]{1})-(3[01]|0[1-9]|[12][0-9])$/,
'time': /^(2[0-4]|[01][0-9]):([0-5][0-9]):(60|[0-5][0-9])$/,
'email': /^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!\.)){0,61}[a-zA-Z0-9]?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9\-](?!$)){0,61}[a-zA-Z0-9]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/,
'ip-address': /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/,
'ipv6': /^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/,
'uri': /^[a-zA-Z][a-zA-Z0-9+-.]*:[^\s]*$/,
'color': /^(#?([0-9A-Fa-f]{3}){1,2}\b|aqua|black|blue|fuchsia|gray|green|lime|maroon|navy|olive|orange|purple|red|silver|teal|white|yellow|(rgb\(\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*,\s*\b([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])\b\s*\))|(rgb\(\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*,\s*(\d?\d%|100%)+\s*\)))$/,
// hostname regex from: http://stackoverflow.com/a/1420225/5628
'hostname': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
'host-name': /^(?=.{1,255}$)[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|-){0,61}[0-9A-Za-z])?)*\.?$/,
'alpha': /^[a-zA-Z]+$/,
'alphanumeric': /^[a-zA-Z0-9]+$/,
'utc-millisec': function (input) {
return (typeof input === 'string') && parseFloat(input) === parseInt(input, 10) && !isNaN(input);
},
'regex': function (input) {
var result = true;
try {
new RegExp(input);
} catch (e) {
result = false;
}
return result;
},
'style': /\s*(.+?):\s*([^;]+);?/g,
'phone': /^\+(?:[0-9] ?){6,14}[0-9]$/
};
FORMAT_REGEXPS.regexp = FORMAT_REGEXPS.regex;
FORMAT_REGEXPS.pattern = FORMAT_REGEXPS.regex;
FORMAT_REGEXPS.ipv4 = FORMAT_REGEXPS['ip-address'];
exports.isFormat = function isFormat (input, format, validator) {
if (typeof input === 'string' && FORMAT_REGEXPS[format] !== undefined) {
if (FORMAT_REGEXPS[format] instanceof RegExp) {
return FORMAT_REGEXPS[format].test(input);
}
if (typeof FORMAT_REGEXPS[format] === 'function') {
return FORMAT_REGEXPS[format](input);
}
} else if (validator && validator.customFormats &&
typeof validator.customFormats[format] === 'function') {
return validator.customFormats[format](input);
}
return true;
};
var makeSuffix = exports.makeSuffix = function makeSuffix (key) {
key = key.toString();
// This function could be capable of outputting valid a ECMAScript string, but the
// resulting code for testing which form to use would be tens of thousands of characters long
// That means this will use the name form for some illegal forms
if (!key.match(/[.\s\[\]]/) && !key.match(/^[\d]/)) {
return '.' + key;
}
if (key.match(/^\d+$/)) {
return '[' + key + ']';
}
return '[' + JSON.stringify(key) + ']';
};
exports.deepCompareStrict = function deepCompareStrict (a, b) {
if (typeof a !== typeof b) {
return false;
}
if (a instanceof Array) {
if (!(b instanceof Array)) {
return false;
}
if (a.length !== b.length) {
return false;
}
return a.every(function (v, i) {
return deepCompareStrict(a[i], b[i]);
});
}
if (typeof a === 'object') {
if (!a || !b) {
return a === b;
}
var aKeys = Object.keys(a);
var bKeys = Object.keys(b);
if (aKeys.length !== bKeys.length) {
return false;
}
return aKeys.every(function (v) {
return deepCompareStrict(a[v], b[v]);
});
}
return a === b;
};
function deepMerger (target, dst, e, i) {
if (typeof e === 'object') {
dst[i] = deepMerge(target[i], e)
} else {
if (target.indexOf(e) === -1) {
dst.push(e)
}
}
}
function copyist (src, dst, key) {
dst[key] = src[key];
}
function copyistWithDeepMerge (target, src, dst, key) {
if (typeof src[key] !== 'object' || !src[key]) {
dst[key] = src[key];
}
else {
if (!target[key]) {
dst[key] = src[key];
} else {
dst[key] = deepMerge(target[key], src[key])
}
}
}
function deepMerge (target, src) {
var array = Array.isArray(src);
var dst = array && [] || {};
if (array) {
target = target || [];
dst = dst.concat(target);
src.forEach(deepMerger.bind(null, target, dst));
} else {
if (target && typeof target === 'object') {
Object.keys(target).forEach(copyist.bind(null, target, dst));
}
Object.keys(src).forEach(copyistWithDeepMerge.bind(null, target, src, dst));
}
return dst;
};
module.exports.deepMerge = deepMerge;
/**
* Validates instance against the provided schema
* Implements URI+JSON Pointer encoding, e.g. "%7e"="~0"=>"~", "~1"="%2f"=>"/"
* @param o
* @param s The path to walk o along
* @return any
*/
exports.objectGetPath = function objectGetPath(o, s) {
var parts = s.split('/').slice(1);
var k;
while (typeof (k=parts.shift()) == 'string') {
var n = decodeURIComponent(k.replace(/~0/,'~').replace(/~1/g,'/'));
if (!(n in o)) return;
o = o[n];
}
return o;
};
function pathEncoder (v) {
return '/'+encodeURIComponent(v).replace(/~/g,'%7E');
}
/**
* Accept an Array of property names and return a JSON Pointer URI fragment
* @param Array a
* @return {String}
*/
exports.encodePath = function encodePointer(a){
// ~ must be encoded explicitly because hacks
// the slash is encoded by encodeURIComponent
return a.map(pathEncoder).join('');
};
/**
* Calculate the number of decimal places a number uses
* We need this to get correct results out of multipleOf and divisibleBy
* when either figure is has decimal places, due to IEEE-754 float issues.
* @param number
* @returns {number}
*/
exports.getDecimalPlaces = function getDecimalPlaces(number) {
var decimalPlaces = 0;
if (isNaN(number)) return decimalPlaces;
if (typeof number !== 'number') {
number = Number(number);
}
var parts = number.toString().split('e');
if (parts.length === 2) {
if (parts[1][0] !== '-') {
return decimalPlaces;
} else {
decimalPlaces = Number(parts[1].slice(1));
}
}
var decimalParts = parts[0].split('.');
if (decimalParts.length === 2) {
decimalPlaces += decimalParts[1].length;
}
return decimalPlaces;
};
/***/ }),
/* 33 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var hashjs = __webpack_require__(23);
var apiFactory = __webpack_require__(118);
var NODE_PUBLIC = 28;
var NODE_PRIVATE = 32;
var ACCOUNT_ID = 0;
var FAMILY_SEED = 33;
var ED25519_SEED = [0x01, 0xE1, 0x4B];
module.exports = apiFactory({
sha256: function(bytes) {
return hashjs.sha256().update(bytes).digest();
},
defaultAlphabet: 'ripple',
codecMethods: {
EdSeed: {
expectedLength: 16,
version: ED25519_SEED
},
Seed: {
// TODO: Use a map, not a parallel array
versionTypes: ['ed25519', 'secp256k1'],
versions: [ED25519_SEED, FAMILY_SEED],
expectedLength: 16
},
AccountID: {version: ACCOUNT_ID, expectedLength: 20},
Address: {version: ACCOUNT_ID, expectedLength: 20},
NodePublic: {version: NODE_PUBLIC, expectedLength: 33},
NodePrivate: {version: NODE_PRIVATE, expectedLength: 32},
K256Seed: {version: FAMILY_SEED, expectedLength: 16}}
});
/***/ }),
/* 34 */
/***/ (function(module, exports) {
module.exports = assert;
function assert(val, msg) {
if (!val)
throw new Error(msg || 'Assertion failed');
}
assert.equal = function assertEqual(l, r, msg) {
if (l != r)
throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
};
/***/ }),
/* 35 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(14);
var assert = __webpack_require__(34);
function BlockHash() {
this.pending = null;
this.pendingTotal = 0;
this.blockSize = this.constructor.blockSize;
this.outSize = this.constructor.outSize;
this.hmacStrength = this.constructor.hmacStrength;
this.padLength = this.constructor.padLength / 8;
this.endian = 'big';
this._delta8 = this.blockSize / 8;
this._delta32 = this.blockSize / 32;
}
exports.BlockHash = BlockHash;
BlockHash.prototype.update = function update(msg, enc) {
// Convert message to array, pad it, and join into 32bit blocks
msg = utils.toArray(msg, enc);
if (!this.pending)
this.pending = msg;
else
this.pending = this.pending.concat(msg);
this.pendingTotal += msg.length;
// Enough data, try updating
if (this.pending.length >= this._delta8) {
msg = this.pending;
// Process pending data in blocks
var r = msg.length % this._delta8;
this.pending = msg.slice(msg.length - r, msg.length);
if (this.pending.length === 0)
this.pending = null;
msg = utils.join32(msg, 0, msg.length - r, this.endian);
for (var i = 0; i < msg.length; i += this._delta32)
this._update(msg, i, i + this._delta32);
}
return this;
};
BlockHash.prototype.digest = function digest(enc) {
this.update(this._pad());
assert(this.pending === null);
return this._digest(enc);
};
BlockHash.prototype._pad = function pad() {
var len = this.pendingTotal;
var bytes = this._delta8;
var k = bytes - ((len + this.padLength) % bytes);
var res = new Array(k + this.padLength);
res[0] = 0x80;
for (var i = 1; i < k; i++)
res[i] = 0;
// Append length
len <<= 3;
if (this.endian === 'big') {
for (var t = 8; t < this.padLength; t++)
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = (len >>> 24) & 0xff;
res[i++] = (len >>> 16) & 0xff;
res[i++] = (len >>> 8) & 0xff;
res[i++] = len & 0xff;
} else {
res[i++] = len & 0xff;
res[i++] = (len >>> 8) & 0xff;
res[i++] = (len >>> 16) & 0xff;
res[i++] = (len >>> 24) & 0xff;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
res[i++] = 0;
for (t = 8; t < this.padLength; t++)
res[i++] = 0;
}
return res;
};
/***/ }),
/* 36 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// eslint-disable-line strict
var assert = __webpack_require__(2);
var brorand = __webpack_require__(62);
var hashjs = __webpack_require__(23);
var elliptic = __webpack_require__(12);
var Ed25519 = elliptic.eddsa('ed25519');
var Secp256k1 = elliptic.ec('secp256k1');
var addressCodec = __webpack_require__(33);
var derivePrivateKey = __webpack_require__(63).derivePrivateKey;
var accountPublicFromPublicGenerator = __webpack_require__(63).accountPublicFromPublicGenerator;
var utils = __webpack_require__(144);
var hexToBytes = utils.hexToBytes;
var bytesToHex = utils.bytesToHex;
function generateSeed() {
var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
assert(!options.entropy || options.entropy.length >= 16, 'entropy too short');
var entropy = options.entropy ? options.entropy.slice(0, 16) : brorand(16);
var type = options.algorithm === 'ed25519' ? 'ed25519' : 'secp256k1';
return addressCodec.encodeSeed(entropy, type);
}
function hash(message) {
return hashjs.sha512().update(message).digest().slice(0, 32);
}
var secp256k1 = {
deriveKeypair: function deriveKeypair(entropy, options) {
var prefix = '00';
var privateKey = prefix + derivePrivateKey(entropy, options).toString(16, 64).toUpperCase();
var publicKey = bytesToHex(Secp256k1.keyFromPrivate(privateKey.slice(2)).getPublic().encodeCompressed());
return { privateKey: privateKey, publicKey: publicKey };
},
sign: function sign(message, privateKey) {
return bytesToHex(Secp256k1.sign(hash(message), hexToBytes(privateKey), { canonical: true }).toDER());
},
verify: function verify(message, signature, publicKey) {
return Secp256k1.verify(hash(message), signature, hexToBytes(publicKey));
}
};
var ed25519 = {
deriveKeypair: function deriveKeypair(entropy) {
var prefix = 'ED';
var rawPrivateKey = hash(entropy);
var privateKey = prefix + bytesToHex(rawPrivateKey);
var publicKey = prefix + bytesToHex(Ed25519.keyFromSecret(rawPrivateKey).pubBytes());
return { privateKey: privateKey, publicKey: publicKey };
},
sign: function sign(message, privateKey) {
// caution: Ed25519.sign interprets all strings as hex, stripping
// any non-hex characters without warning
assert(Array.isArray(message), 'message must be array of octets');
return bytesToHex(Ed25519.sign(message, hexToBytes(privateKey).slice(1)).toBytes());
},
verify: function verify(message, signature, publicKey) {
return Ed25519.verify(message, hexToBytes(signature), hexToBytes(publicKey).slice(1));
}
};
function select(algorithm) {
var methods = { 'ecdsa-secp256k1': secp256k1, ed25519: ed25519 };
return methods[algorithm];
}
function deriveKeypair(seed, options) {
var decoded = addressCodec.decodeSeed(seed);
var algorithm = decoded.type === 'ed25519' ? 'ed25519' : 'ecdsa-secp256k1';
var method = select(algorithm);
var keypair = method.deriveKeypair(decoded.bytes, options);
var messageToVerify = hash('This test message should verify.');
var signature = method.sign(messageToVerify, keypair.privateKey);
if (method.verify(messageToVerify, signature, keypair.publicKey) !== true) {
throw new Error('derived keypair did not generate verifiable signature');
}
return keypair;
}
function getAlgorithmFromKey(key) {
var bytes = hexToBytes(key);
return bytes.length === 33 && bytes[0] === 0xED ? 'ed25519' : 'ecdsa-secp256k1';
}
function sign(messageHex, privateKey) {
var algorithm = getAlgorithmFromKey(privateKey);
return select(algorithm).sign(hexToBytes(messageHex), privateKey);
}
function verify(messageHex, signature, publicKey) {
var algorithm = getAlgorithmFromKey(publicKey);
return select(algorithm).verify(hexToBytes(messageHex), signature, publicKey);
}
function deriveAddressFromBytes(publicKeyBytes) {
return addressCodec.encodeAccountID(utils.computePublicKeyHash(publicKeyBytes));
}
function deriveAddress(publicKey) {
return deriveAddressFromBytes(hexToBytes(publicKey));
}
function deriveNodeAddress(publicKey) {
var generatorBytes = addressCodec.decodeNodePublic(publicKey);
var accountPublicBytes = accountPublicFromPublicGenerator(generatorBytes);
return deriveAddressFromBytes(accountPublicBytes);
}
module.exports = {
generateSeed: generateSeed,
deriveKeypair: deriveKeypair,
sign: sign,
verify: verify,
deriveAddress: deriveAddress,
deriveNodeAddress: deriveNodeAddress
};
/***/ }),
/* 37 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Buffer = __webpack_require__(8).Buffer;
var isEncoding = Buffer.isEncoding || function (encoding) {
encoding = '' + encoding;
switch (encoding && encoding.toLowerCase()) {
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':
return true;
default:
return false;
}
};
function _normalizeEncoding(enc) {
if (!enc) return 'utf8';
var retried;
while (true) {
switch (enc) {
case 'utf8':
case 'utf-8':
return 'utf8';
case 'ucs2':
case 'ucs-2':
case 'utf16le':
case 'utf-16le':
return 'utf16le';
case 'latin1':
case 'binary':
return 'latin1';
case 'base64':
case 'ascii':
case 'hex':
return enc;
default:
if (retried) return; // undefined
enc = ('' + enc).toLowerCase();
retried = true;
}
}
};
// Do not cache `Buffer.isEncoding` when checking encoding names as some
// modules monkey-patch it to support additional encodings
function normalizeEncoding(enc) {
var nenc = _normalizeEncoding(enc);
if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
return nenc || enc;
}
// StringDecoder provides an interface for efficiently splitting a series of
// buffers into a series of JS strings without breaking apart multi-byte
// characters.
exports.StringDecoder = StringDecoder;
function StringDecoder(encoding) {
this.encoding = normalizeEncoding(encoding);
var nb;
switch (this.encoding) {
case 'utf16le':
this.text = utf16Text;
this.end = utf16End;
nb = 4;
break;
case 'utf8':
this.fillLast = utf8FillLast;
nb = 4;
break;
case 'base64':
this.text = base64Text;
this.end = base64End;
nb = 3;
break;
default:
this.write = simpleWrite;
this.end = simpleEnd;
return;
}
this.lastNeed = 0;
this.lastTotal = 0;
this.lastChar = Buffer.allocUnsafe(nb);
}
StringDecoder.prototype.write = function (buf) {
if (buf.length === 0) return '';
var r;
var i;
if (this.lastNeed) {
r = this.fillLast(buf);
if (r === undefined) return '';
i = this.lastNeed;
this.lastNeed = 0;
} else {
i = 0;
}
if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
return r || '';
};
StringDecoder.prototype.end = utf8End;
// Returns only complete characters in a Buffer
StringDecoder.prototype.text = utf8Text;
// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
StringDecoder.prototype.fillLast = function (buf) {
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
this.lastNeed -= buf.length;
};
// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
// continuation byte.
function utf8CheckByte(byte) {
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;
return -1;
}
// Checks at most 3 bytes at the end of a Buffer in order to detect an
// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
// needed to complete the UTF-8 character (if applicable) are returned.
function utf8CheckIncomplete(self, buf, i) {
var j = buf.length - 1;
if (j < i) return 0;
var nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 1;
return nb;
}
if (--j < i) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) self.lastNeed = nb - 2;
return nb;
}
if (--j < i) return 0;
nb = utf8CheckByte(buf[j]);
if (nb >= 0) {
if (nb > 0) {
if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
}
return nb;
}
return 0;
}
// Validates as many continuation bytes for a multi-byte UTF-8 character as
// needed or are available. If we see a non-continuation byte where we expect
// one, we "replace" the validated continuation bytes we've seen so far with
// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
// behavior. The continuation byte check is included three times in the case
// where all of the continuation bytes for a character exist in the same buffer.
// It is also done this way as a slight performance increase instead of using a
// loop.
function utf8CheckExtraBytes(self, buf, p) {
if ((buf[0] & 0xC0) !== 0x80) {
self.lastNeed = 0;
return '\ufffd'.repeat(p);
}
if (self.lastNeed > 1 && buf.length > 1) {
if ((buf[1] & 0xC0) !== 0x80) {
self.lastNeed = 1;
return '\ufffd'.repeat(p + 1);
}
if (self.lastNeed > 2 && buf.length > 2) {
if ((buf[2] & 0xC0) !== 0x80) {
self.lastNeed = 2;
return '\ufffd'.repeat(p + 2);
}
}
}
}
// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
function utf8FillLast(buf) {
var p = this.lastTotal - this.lastNeed;
var r = utf8CheckExtraBytes(this, buf, p);
if (r !== undefined) return r;
if (this.lastNeed <= buf.length) {
buf.copy(this.lastChar, p, 0, this.lastNeed);
return this.lastChar.toString(this.encoding, 0, this.lastTotal);
}
buf.copy(this.lastChar, p, 0, buf.length);
this.lastNeed -= buf.length;
}
// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
// partial character, the character's bytes are buffered until the required
// number of bytes are available.
function utf8Text(buf, i) {
var total = utf8CheckIncomplete(this, buf, i);
if (!this.lastNeed) return buf.toString('utf8', i);
this.lastTotal = total;
var end = buf.length - (total - this.lastNeed);
buf.copy(this.lastChar, 0, end);
return buf.toString('utf8', i, end);
}
// For UTF-8, a replacement character for each buffered byte of a (partial)
// character needs to be added to the output.
function utf8End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
return r;
}
// UTF-16LE typically needs two bytes per character, but even if we have an even
// number of bytes available, we need to check if we end on a leading/high
// surrogate. In that case, we need to wait for the next two bytes in order to
// decode the last character properly.
function utf16Text(buf, i) {
if ((buf.length - i) % 2 === 0) {
var r = buf.toString('utf16le', i);
if (r) {
var c = r.charCodeAt(r.length - 1);
if (c >= 0xD800 && c <= 0xDBFF) {
this.lastNeed = 2;
this.lastTotal = 4;
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
return r.slice(0, -1);
}
}
return r;
}
this.lastNeed = 1;
this.lastTotal = 2;
this.lastChar[0] = buf[buf.length - 1];
return buf.toString('utf16le', i, buf.length - 1);
}
// For UTF-16LE we do not explicitly append special replacement characters if we
// end on a partial character, we simply let v8 handle that.
function utf16End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) {
var end = this.lastTotal - this.lastNeed;
return r + this.lastChar.toString('utf16le', 0, end);
}
return r;
}
function base64Text(buf, i) {
var n = (buf.length - i) % 3;
if (n === 0) return buf.toString('base64', i);
this.lastNeed = 3 - n;
this.lastTotal = 3;
if (n === 1) {
this.lastChar[0] = buf[buf.length - 1];
} else {
this.lastChar[0] = buf[buf.length - 2];
this.lastChar[1] = buf[buf.length - 1];
}
return buf.toString('base64', i, buf.length - n);
}
function base64End(buf) {
var r = buf && buf.length ? this.write(buf) : '';
if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
return r;
}
// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
function simpleWrite(buf) {
return buf.toString(this.encoding);
}
function simpleEnd(buf) {
return buf && buf.length ? this.write(buf) : '';
}
/***/ }),
/* 38 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _require = __webpack_require__(10);var serializeUIntN = _require.serializeUIntN;
function bytes(uint32) {
return serializeUIntN(uint32, 4);}
var HashPrefix = {
transactionID: bytes(0x54584E00),
// transaction plus metadata
transaction: bytes(0x534E4400),
// account state
accountStateEntry: bytes(0x4D4C4E00),
// inner node in tree
innerNode: bytes(0x4D494E00),
// ledger master data for signing
ledgerHeader: bytes(0x4C575200),
// inner transaction to sign
transactionSig: bytes(0x53545800),
// inner transaction to sign
transactionMultiSig: bytes(0x534D5400),
// validation for signing
validation: bytes(0x56414C00),
// proposal for signing
proposal: bytes(0x50525000),
// payment channel claim
paymentChannelClaim: bytes(0x434C4D00) };
module.exports = {
HashPrefix: HashPrefix };
/***/ }),
/* 39 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const util_1 = __webpack_require__(26);
const browserHacks = __webpack_require__(102);
class RippleError extends Error {
constructor(message = '', data) {
super(message);
this.name = browserHacks.getConstructorName(this);
this.message = message;
this.data = data;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
toString() {
let result = '[' + this.name + '(' + this.message;
if (this.data) {
result += ', ' + util_1.inspect(this.data);
}
result += ')]';
return result;
}
/* console.log in node uses util.inspect on object, and util.inspect allows
us to cutomize its output:
https://nodejs.org/api/util.html#util_custom_inspect_function_on_objects */
inspect() {
return this.toString();
}
}
exports.RippleError = RippleError;
class RippledError extends RippleError {
}
exports.RippledError = RippledError;
class UnexpectedError extends RippleError {
}
exports.UnexpectedError = UnexpectedError;
class LedgerVersionError extends RippleError {
}
exports.LedgerVersionError = LedgerVersionError;
class ConnectionError extends RippleError {
}
exports.ConnectionError = ConnectionError;
class NotConnectedError extends ConnectionError {
}
exports.NotConnectedError = NotConnectedError;
class DisconnectedError extends ConnectionError {
}
exports.DisconnectedError = DisconnectedError;
class RippledNotInitializedError extends ConnectionError {
}
exports.RippledNotInitializedError = RippledNotInitializedError;
class TimeoutError extends ConnectionError {
}
exports.TimeoutError = TimeoutError;
class ResponseFormatError extends ConnectionError {
}
exports.ResponseFormatError = ResponseFormatError;
class ValidationError extends RippleError {
}
exports.ValidationError = ValidationError;
class NotFoundError extends RippleError {
constructor(message = 'Not found') {
super(message);
}
}
exports.NotFoundError = NotFoundError;
class MissingLedgerHistoryError extends RippleError {
constructor(message) {
super(message || 'Server is missing ledger history in the specified range');
}
}
exports.MissingLedgerHistoryError = MissingLedgerHistoryError;
class PendingLedgerVersionError extends RippleError {
constructor(message) {
super(message || 'maxLedgerVersion is greater than server\'s most recent ' +
' validated ledger');
}
}
exports.PendingLedgerVersionError = PendingLedgerVersionError;
/***/ }),
/* 40 */
/***/ (function(module, exports) {
module.exports = function(module) {
if(!module.webpackPolyfill) {
module.deprecate = function() {};
module.paths = [];
// module.parent = undefined by default
if(!module.children) module.children = [];
Object.defineProperty(module, "loaded", {
enumerable: true,
get: function() {
return module.l;
}
});
Object.defineProperty(module, "id", {
enumerable: true,
get: function() {
return module.i;
}
});
module.webpackPolyfill = 1;
}
return module;
};
/***/ }),
/* 41 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var curve = exports;
curve.base = __webpack_require__(126);
curve.short = __webpack_require__(127);
curve.mont = __webpack_require__(128);
curve.edwards = __webpack_require__(129);
/***/ }),
/* 42 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _ = __webpack_require__(1)
var BigNumber = __webpack_require__(6)
// drops is a bignumber.js BigNumber
function dropsToXRP(drops) {
return drops.dividedBy(1000000)
}
function normalizeNode(affectedNode) {
var diffType = Object.keys(affectedNode)[0]
var node = affectedNode[diffType]
return {
diffType: diffType,
entryType: node.LedgerEntryType,
ledgerIndex: node.LedgerIndex,
newFields: node.NewFields || {},
finalFields: node.FinalFields || {},
previousFields: node.PreviousFields || {}
}
}
function normalizeNodes(metadata) {
if (!metadata.AffectedNodes) {
return []
}
return metadata.AffectedNodes.map(normalizeNode)
}
function parseCurrencyAmount(currencyAmount) {
if (currencyAmount === undefined) {
return undefined
}
if (typeof currencyAmount === 'string') {
return {
currency: 'XRP',
value: dropsToXRP(new BigNumber(currencyAmount)).toString()
}
}
return {
currency: currencyAmount.currency,
counterparty: currencyAmount.issuer,
value: currencyAmount.value
}
}
function isAccountField(fieldName) {
var fieldNames = ['Account', 'Owner', 'Destination', 'Issuer', 'Target']
return _.includes(fieldNames, fieldName)
}
function isAmountFieldAffectingIssuer(fieldName) {
var fieldNames = ['LowLimit', 'HighLimit', 'TakerPays', 'TakerGets']
return _.includes(fieldNames, fieldName)
}
function getAffectedAccounts(metadata) {
var accounts = []
_.forEach(normalizeNodes(metadata), function(node) {
var fields = node.diffType === 'CreatedNode' ?
node.newFields : node.finalFields
_.forEach(fields, function(fieldValue, fieldName) {
if (isAccountField(fieldName)) {
accounts.push(fieldValue)
} else if (isAmountFieldAffectingIssuer(fieldName) && fieldValue.issuer) {
accounts.push(fieldValue.issuer)
}
})
})
return _.uniq(accounts)
}
module.exports = {
dropsToXRP: dropsToXRP,
normalizeNodes: normalizeNodes,
parseCurrencyAmount: parseCurrencyAmount,
getAffectedAccounts: getAffectedAccounts
}
/***/ }),
/* 43 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assert = __webpack_require__(2);
var BN = __webpack_require__(30);
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(21);var Comparable = _require.Comparable;var SerializedType = _require.SerializedType;var _require2 =
__webpack_require__(10);var serializeUIntN = _require2.serializeUIntN;
var MAX_VALUES = [0, 255, 65535, 16777215, 4294967295];
function signum(a, b) {
return a < b ? -1 : a === b ? 0 : 1;}
var UInt = makeClass({
mixins: [Comparable, SerializedType],
UInt: function UInt() {var val = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
var max = MAX_VALUES[this.constructor.width];
if (val < 0 || !(val <= max)) {
throw new Error(val + ' not in range 0 <= $val <= ' + max);}
this.val = val;},
statics: {
width: 0,
fromParser: function fromParser(parser) {
var val = this.width > 4 ? parser.read(this.width) :
parser.readUIntN(this.width);
return new this(val);},
from: function from(val) {
return val instanceof this ? val : new this(val);} },
toJSON: function toJSON() {
return this.val;},
valueOf: function valueOf() {
return this.val;},
compareTo: function compareTo(other) {
var thisValue = this.valueOf();
var otherValue = other.valueOf();
if (thisValue instanceof BN) {
return otherValue instanceof BN ?
thisValue.cmp(otherValue) :
thisValue.cmpn(otherValue);} else
if (otherValue instanceof BN) {
return -other.compareTo(this);}
assert(typeof otherValue === 'number');
return signum(thisValue, otherValue);},
toBytesSink: function toBytesSink(sink) {
sink.put(this.toBytes());},
toBytes: function toBytes() {
return serializeUIntN(this.val, this.constructor.width);} });
module.exports = {
UInt: UInt };
/***/ }),
/* 44 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {var makeClass = __webpack_require__(4);var _require =
__webpack_require__(38);var HashPrefix = _require.HashPrefix;var _require2 =
__webpack_require__(24);var Hash256 = _require2.Hash256;var _require3 =
__webpack_require__(10);var parseBytes = _require3.parseBytes;
var createHash = __webpack_require__(85);
var Sha512Half = makeClass({
Sha512Half: function Sha512Half() {
this.hash = createHash('sha512');},
statics: {
put: function put(bytes) {
return new this().put(bytes);} },
put: function put(bytes) {
this.hash.update(parseBytes(bytes, Buffer));
return this;},
finish256: function finish256() {
var bytes = this.hash.digest();
return bytes.slice(0, 32);},
finish: function finish() {
return new Hash256(this.finish256());} });
function sha512Half() {
var hash = new Sha512Half();for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {args[_key] = arguments[_key];}
args.forEach(function (a) {return hash.put(a);});
return parseBytes(hash.finish256(), Uint8Array);}
function transactionID(serialized) {
return new Hash256(sha512Half(HashPrefix.transactionID, serialized));}
module.exports = {
Sha512Half: Sha512Half,
sha512Half: sha512Half,
transactionID: transactionID };
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 45 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var BigNumber = __webpack_require__(6);
var decodeAddress = __webpack_require__(33).decodeAddress;
var binary = __webpack_require__(28);
var hashprefixes = __webpack_require__(94);
var SHAMap = __webpack_require__(95).SHAMap;
var SHAMapTreeNode = __webpack_require__(95).SHAMapTreeNode;
var ledgerspaces = __webpack_require__(319);
var sha512half = __webpack_require__(96);
function hash(hex) {
return sha512half(new Buffer(hex, 'hex'));
}
function padLeftZero(string, length) {
return Array(length - string.length + 1).join('0') + string;
}
function intToHex(integer, byteLength) {
return padLeftZero(Number(integer).toString(16), byteLength * 2);
}
function bytesToHex(bytes) {
return (new Buffer(bytes)).toString('hex');
}
function bigintToHex(integerString, byteLength) {
var hex = (new BigNumber(integerString)).toString(16);
return padLeftZero(hex, byteLength * 2);
}
function ledgerSpaceHex(name) {
return intToHex(ledgerspaces[name].charCodeAt(0), 2);
}
function addressToHex(address) {
return (new Buffer(decodeAddress(address))).toString('hex');
}
function currencyToHex(currency) {
if (currency.length === 3) {
var bytes = new Array(20 + 1).join('0').split('').map(parseFloat);
bytes[12] = currency.charCodeAt(0) & 0xff;
bytes[13] = currency.charCodeAt(1) & 0xff;
bytes[14] = currency.charCodeAt(2) & 0xff;
return bytesToHex(bytes);
}
return currency;
}
function addLengthPrefix(hex) {
var length = hex.length / 2;
if (length <= 192) {
return bytesToHex([length]) + hex;
} else if (length <= 12480) {
var x = length - 193;
return bytesToHex([193 + (x >>> 8), x & 0xff]) + hex;
} else if (length <= 918744) {
var x = length - 12481;
return bytesToHex([241 + (x >>> 16), x >>> 8 & 0xff, x & 0xff]) + hex;
}
throw new Error('Variable integer overflow.');
}
function computeBinaryTransactionHash(txBlobHex) {
var prefix = hashprefixes.HASH_TX_ID.toString(16).toUpperCase();
return hash(prefix + txBlobHex);
}
function computeTransactionHash(txJSON) {
return computeBinaryTransactionHash(binary.encode(txJSON));
}
function computeBinaryTransactionSigningHash(txBlobHex) {
var prefix = hashprefixes.HASH_TX_SIGN.toString(16).toUpperCase();
return hash(prefix + txBlobHex);
}
function computeTransactionSigningHash(txJSON) {
return computeBinaryTransactionSigningHash(binary.encode(txJSON));
}
function computeAccountHash(address) {
return hash(ledgerSpaceHex('account') + addressToHex(address));
}
function computeSignerListHash(address) {
return hash(ledgerSpaceHex('signerList') +
addressToHex(address) +
'00000000' /* uint32(0) signer list index */);
}
function computeOrderHash(address, sequence) {
var prefix = '00' + intToHex(ledgerspaces.offer.charCodeAt(0), 1);
return hash(prefix + addressToHex(address) + intToHex(sequence, 4));
}
function computeTrustlineHash(address1, address2, currency) {
var address1Hex = addressToHex(address1);
var address2Hex = addressToHex(address2);
var swap = (new BigNumber(address1Hex, 16)).greaterThan(
new BigNumber(address2Hex, 16));
var lowAddressHex = swap ? address2Hex : address1Hex;
var highAddressHex = swap ? address1Hex : address2Hex;
var prefix = ledgerSpaceHex('rippleState');
return hash(prefix + lowAddressHex + highAddressHex +
currencyToHex(currency));
}
function computeTransactionTreeHash(transactions) {
var shamap = new SHAMap();
transactions.forEach(function(txJSON) {
var txBlobHex = binary.encode(txJSON);
var metaHex = binary.encode(txJSON.metaData);
var txHash = computeBinaryTransactionHash(txBlobHex);
var data = addLengthPrefix(txBlobHex) + addLengthPrefix(metaHex);
shamap.add_item(txHash, data, SHAMapTreeNode.TYPE_TRANSACTION_MD);
});
return shamap.hash();
}
function computeStateTreeHash(entries) {
var shamap = new SHAMap();
entries.forEach(function(ledgerEntry) {
var data = binary.encode(ledgerEntry);
shamap.add_item(ledgerEntry.index, data, SHAMapTreeNode.TYPE_ACCOUNT_STATE);
});
return shamap.hash();
}
// see rippled Ledger::updateHash()
function computeLedgerHash(ledgerHeader) {
var prefix = hashprefixes.HASH_LEDGER.toString(16).toUpperCase();
return hash(prefix +
intToHex(ledgerHeader.ledger_index, 4) +
bigintToHex(ledgerHeader.total_coins, 8) +
ledgerHeader.parent_hash +
ledgerHeader.transaction_hash +
ledgerHeader.account_hash +
intToHex(ledgerHeader.parent_close_time, 4) +
intToHex(ledgerHeader.close_time, 4) +
intToHex(ledgerHeader.close_time_resolution, 1) +
intToHex(ledgerHeader.close_flags, 1)
);
}
function computeEscrowHash(address, sequence) {
return hash(ledgerSpaceHex('escrow') + addressToHex(address) +
intToHex(sequence, 4));
}
function computePaymentChannelHash(address, dstAddress, sequence) {
return hash(ledgerSpaceHex('paychan') + addressToHex(address) +
addressToHex(dstAddress) + intToHex(sequence, 4));
}
module.exports = {
computeTransactionHash: computeTransactionHash,
computeBinaryTransactionHash: computeBinaryTransactionHash,
computeTransactionSigningHash: computeTransactionSigningHash,
computeBinaryTransactionSigningHash: computeBinaryTransactionSigningHash,
computeAccountHash: computeAccountHash,
computeOrderHash: computeOrderHash,
computeTrustlineHash: computeTrustlineHash,
computeSignerListHash: computeSignerListHash,
computeStateTreeHash: computeStateTreeHash,
computeTransactionTreeHash: computeTransactionTreeHash,
computeLedgerHash: computeLedgerHash,
computeEscrowHash: computeEscrowHash,
computePaymentChannelHash: computePaymentChannelHash
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 46 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const bignumber_js_1 = __webpack_require__(6);
const { deriveKeypair } = __webpack_require__(36);
function isValidSecret(secret) {
try {
deriveKeypair(secret);
return true;
}
catch (err) {
return false;
}
}
exports.isValidSecret = isValidSecret;
function dropsToXrp(drops) {
return (new bignumber_js_1.default(drops)).dividedBy(1000000.0).toString();
}
exports.dropsToXrp = dropsToXrp;
function xrpToDrops(xrp) {
return (new bignumber_js_1.default(xrp)).times(1000000.0).floor().toString();
}
exports.xrpToDrops = xrpToDrops;
function toRippledAmount(amount) {
if (amount.currency === 'XRP') {
return xrpToDrops(amount.value);
}
return {
currency: amount.currency,
issuer: amount.counterparty ? amount.counterparty :
(amount.issuer ? amount.issuer : undefined),
value: amount.value
};
}
exports.toRippledAmount = toRippledAmount;
function convertKeysFromSnakeCaseToCamelCase(obj) {
if (typeof obj === 'object') {
let newKey;
return _.reduce(obj, (result, value, key) => {
newKey = key;
// taking this out of function leads to error in PhantomJS
const FINDSNAKE = /([a-zA-Z]_[a-zA-Z])/g;
if (FINDSNAKE.test(key)) {
newKey = key.replace(FINDSNAKE, r => r[0] + r[2].toUpperCase());
}
result[newKey] = convertKeysFromSnakeCaseToCamelCase(value);
return result;
}, {});
}
return obj;
}
exports.convertKeysFromSnakeCaseToCamelCase = convertKeysFromSnakeCaseToCamelCase;
function removeUndefined(obj) {
return _.omitBy(obj, _.isUndefined);
}
exports.removeUndefined = removeUndefined;
/**
* @param {Number} rpepoch (seconds since 1/1/2000 GMT)
* @return {Number} ms since unix epoch
*
*/
function rippleToUnixTimestamp(rpepoch) {
return (rpepoch + 0x386D4380) * 1000;
}
/**
* @param {Number|Date} timestamp (ms since unix epoch)
* @return {Number} seconds since ripple epoch ( 1/1/2000 GMT)
*/
function unixToRippleTimestamp(timestamp) {
return Math.round(timestamp / 1000) - 0x386D4380;
}
function rippleTimeToISO8601(rippleTime) {
return new Date(rippleToUnixTimestamp(rippleTime)).toISOString();
}
exports.rippleTimeToISO8601 = rippleTimeToISO8601;
function iso8601ToRippleTime(iso8601) {
return unixToRippleTimestamp(Date.parse(iso8601));
}
exports.iso8601ToRippleTime = iso8601ToRippleTime;
/***/ }),
/* 47 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const assert = __webpack_require__(2);
const utils_1 = __webpack_require__(13);
const common_1 = __webpack_require__(0);
const payment_1 = __webpack_require__(271);
const trustline_1 = __webpack_require__(272);
const order_1 = __webpack_require__(273);
const cancellation_1 = __webpack_require__(274);
const settings_1 = __webpack_require__(275);
const escrow_creation_1 = __webpack_require__(276);
const escrow_execution_1 = __webpack_require__(277);
const escrow_cancellation_1 = __webpack_require__(278);
const payment_channel_create_1 = __webpack_require__(279);
const payment_channel_fund_1 = __webpack_require__(280);
const payment_channel_claim_1 = __webpack_require__(281);
const fee_update_1 = __webpack_require__(282);
const amendment_1 = __webpack_require__(283);
function parseTransactionType(type) {
const mapping = {
Payment: 'payment',
TrustSet: 'trustline',
OfferCreate: 'order',
OfferCancel: 'orderCancellation',
AccountSet: 'settings',
SetRegularKey: 'settings',
EscrowCreate: 'escrowCreation',
EscrowFinish: 'escrowExecution',
EscrowCancel: 'escrowCancellation',
PaymentChannelCreate: 'paymentChannelCreate',
PaymentChannelFund: 'paymentChannelFund',
PaymentChannelClaim: 'paymentChannelClaim',
SignerListSet: 'settings',
SetFee: 'feeUpdate',
EnableAmendment: 'amendment' // pseudo-transaction
};
return mapping[type] || null;
}
function parseTransaction(tx) {
const type = parseTransactionType(tx.TransactionType);
const mapping = {
'payment': payment_1.default,
'trustline': trustline_1.default,
'order': order_1.default,
'orderCancellation': cancellation_1.default,
'settings': settings_1.default,
'escrowCreation': escrow_creation_1.default,
'escrowExecution': escrow_execution_1.default,
'escrowCancellation': escrow_cancellation_1.default,
'paymentChannelCreate': payment_channel_create_1.default,
'paymentChannelFund': payment_channel_fund_1.default,
'paymentChannelClaim': payment_channel_claim_1.default,
'feeUpdate': fee_update_1.default,
'amendment': amendment_1.default
};
const parser = mapping[type];
assert(parser !== undefined, 'Unrecognized transaction type');
const specification = parser(tx);
const outcome = utils_1.parseOutcome(tx);
return common_1.removeUndefined({
type: type,
address: tx.Account,
sequence: tx.Sequence,
id: tx.hash,
specification: common_1.removeUndefined(specification),
outcome: outcome ? common_1.removeUndefined(outcome) : undefined
});
}
exports.default = parseTransaction;
/***/ }),
/* 48 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(33);var decodeAccountID = _require.decodeAccountID;var encodeAccountID = _require.encodeAccountID;var _require2 =
__webpack_require__(49);var Hash160 = _require2.Hash160;
var AccountID = makeClass({
AccountID: function AccountID(bytes) {
Hash160.call(this, bytes);},
inherits: Hash160,
statics: {
from: function from(value) {
return value instanceof this ? value :
/^r/.test(value) ? this.fromBase58(value) :
new this(value);},
cache: {},
fromCache: function fromCache(base58) {
var cached = this.cache[base58];
if (!cached) {
cached = this.cache[base58] = this.fromBase58(base58);}
return cached;},
fromBase58: function fromBase58(value) {
var acc = new this(decodeAccountID(value));
acc._toBase58 = value;
return acc;} },
toJSON: function toJSON() {
return this.toBase58();},
cached: {
toBase58: function toBase58() {
return encodeAccountID(this._bytes);} } });
module.exports = {
AccountID: AccountID };
/***/ }),
/* 49 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(50);var Hash = _require.Hash;
var Hash160 = makeClass({
inherits: Hash,
statics: { width: 20 } });
module.exports = {
Hash160: Hash160 };
/***/ }),
/* 50 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assert = __webpack_require__(2);
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(21);var Comparable = _require.Comparable;var SerializedType = _require.SerializedType;var _require2 =
__webpack_require__(10);var compareBytes = _require2.compareBytes;var parseBytes = _require2.parseBytes;
var Hash = makeClass({
Hash: function Hash(bytes) {
var width = this.constructor.width;
this._bytes = bytes ? parseBytes(bytes, Uint8Array) :
new Uint8Array(width);
assert.equal(this._bytes.length, width);},
mixins: [Comparable, SerializedType],
statics: {
width: NaN,
from: function from(value) {
if (value instanceof this) {
return value;}
return new this(parseBytes(value));},
fromParser: function fromParser(parser, hint) {
return new this(parser.read(hint || this.width));} },
compareTo: function compareTo(other) {
return compareBytes(this._bytes, this.constructor.from(other)._bytes);},
toString: function toString() {
return this.toHex();},
nibblet: function nibblet(depth) {
var byte_ix = depth > 0 ? depth / 2 | 0 : 0;
var b = this._bytes[byte_ix];
if (depth % 2 === 0) {
b = (b & 0xF0) >>> 4;} else
{
b = b & 0x0F;}
return b;} });
module.exports = {
Hash: Hash };
/***/ }),
/* 51 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assert = __webpack_require__(2);var _require =
__webpack_require__(10);var parseBytes = _require.parseBytes;var bytesToHex = _require.bytesToHex;
var makeClass = __webpack_require__(4);var _require2 =
__webpack_require__(29);var Type = _require2.Type;var Field = _require2.Field;
var BytesSink = {
put: function put() /* bytesSequence */{
// any hex string or any object with a `length` and where 0 <= [ix] <= 255
} };
var BytesList = makeClass({
implementing: BytesSink,
BytesList: function BytesList() {
this.arrays = [];
this.length = 0;},
put: function put(bytesArg) {
var bytes = parseBytes(bytesArg, Uint8Array);
this.length += bytes.length;
this.arrays.push(bytes);
return this;},
toBytesSink: function toBytesSink(sink) {
this.arrays.forEach(function (arr) {
sink.put(arr);});},
toBytes: function toBytes() {
var concatenated = new Uint8Array(this.length);
var pointer = 0;
this.arrays.forEach(function (arr) {
concatenated.set(arr, pointer);
pointer += arr.length;});
return concatenated;},
toHex: function toHex() {
return bytesToHex(this.toBytes());} });
var BinarySerializer = makeClass({
BinarySerializer: function BinarySerializer(sink) {
this.sink = sink;},
write: function write(value) {
value.toBytesSink(this.sink);},
put: function put(bytes) {
this.sink.put(bytes);},
writeType: function writeType(type, value) {
this.write(type.from(value));},
writeBytesList: function writeBytesList(bl) {
bl.toBytesSink(this.sink);},
encodeVL: function encodeVL(len) {
var length = len;
var lenBytes = new Uint8Array(4);
if (length <= 192) {
lenBytes[0] = length;
return lenBytes.subarray(0, 1);} else
if (length <= 12480) {
length -= 193;
lenBytes[0] = 193 + (length >>> 8);
lenBytes[1] = length & 0xff;
return lenBytes.subarray(0, 2);} else
if (length <= 918744) {
length -= 12481;
lenBytes[0] = 241 + (length >>> 16);
lenBytes[1] = length >> 8 & 0xff;
lenBytes[2] = length & 0xff;
return lenBytes.subarray(0, 3);}
throw new Error('Overflow error');},
writeFieldAndValue: function writeFieldAndValue(field, _value) {
var sink = this.sink;
var value = field.associatedType.from(_value);
assert(value.toBytesSink, field);
sink.put(field.bytes);
if (field.isVLEncoded) {
this.writeLengthEncoded(value);} else
{
value.toBytesSink(sink);
if (field.type === Type.STObject) {
sink.put(Field.ObjectEndMarker.bytes);} else
if (field.type === Type.STArray) {
sink.put(Field.ArrayEndMarker.bytes);}}},
writeLengthEncoded: function writeLengthEncoded(value) {
var bytes = new BytesList();
value.toBytesSink(bytes);
this.put(this.encodeVL(bytes.length));
this.writeBytesList(bytes);} });
module.exports = {
BytesList: BytesList,
BinarySerializer: BinarySerializer };
/***/ }),
/* 52 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _ = __webpack_require__(1);
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(10);var slice = _require.slice;var _require2 =
__webpack_require__(49);var Hash160 = _require2.Hash160;
var ISO_REGEX = /^[A-Z0-9]{3}$/;
var HEX_REGEX = /^[A-F0-9]{40}$/;
function isoToBytes(iso) {
var bytes = new Uint8Array(20);
if (iso !== 'XRP') {
var isoBytes = iso.split('').map(function (c) {return c.charCodeAt(0);});
bytes.set(isoBytes, 12);}
return bytes;}
function isISOCode(val) {
return val.length === 3; // ISO_REGEX.test(val);
}
function isHex(val) {
return HEX_REGEX.test(val);}
function isStringRepr(val) {
return _.isString(val) && (isISOCode(val) || isHex(val));}
function isBytesArray(val) {
return val.length === 20;}
function isValidRepr(val) {
return isStringRepr(val) || isBytesArray(val);}
function bytesFromRepr(val) {
if (isValidRepr(val)) {
// We assume at this point that we have an object with a length, either 3,
// 20 or 40.
return val.length === 3 ? isoToBytes(val) : val;}
throw new Error('Unsupported Currency repr: ' + val);}
var $uper = Hash160.prototype;
var Currency = makeClass({
inherits: Hash160,
getters: ['isNative', 'iso'],
statics: {
init: function init() {
this.XRP = new this(new Uint8Array(20));},
from: function from(val) {
return val instanceof this ? val : new this(bytesFromRepr(val));} },
Currency: function Currency(bytes) {
Hash160.call(this, bytes);
this.classify();},
classify: function classify() {
// We only have a non null iso() property available if the currency can be
// losslessly represented by the 3 letter iso code. If none is available a
// hex encoding of the full 20 bytes is the canonical representation.
var onlyISO = true;
var bytes = this._bytes;
var code = slice(this._bytes, 12, 15, Array);
var iso = code.map(function (c) {return String.fromCharCode(c);}).join('');
for (var i = bytes.length - 1; i >= 0; i--) {
if (bytes[i] !== 0 && !(i === 12 || i === 13 || i === 14)) {
onlyISO = false;
break;}}
var lossLessISO = onlyISO && iso !== 'XRP' && ISO_REGEX.test(iso);
this._isNative = onlyISO && _.isEqual(code, [0, 0, 0]);
this._iso = this._isNative ? 'XRP' : lossLessISO ? iso : null;},
toJSON: function toJSON() {
if (this.iso()) {
return this.iso();}
return $uper.toJSON.call(this);} });
module.exports = {
Currency: Currency };
/***/ }),
/* 53 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* eslint-disable func-style */
var BN = __webpack_require__(30);
var types = __webpack_require__(24);var _require =
__webpack_require__(38);var HashPrefix = _require.HashPrefix;var _require2 =
__webpack_require__(297);var BinaryParser = _require2.BinaryParser;var _require3 =
__webpack_require__(51);var BinarySerializer = _require3.BinarySerializer;var BytesList = _require3.BytesList;var _require4 =
__webpack_require__(10);var bytesToHex = _require4.bytesToHex;var slice = _require4.slice;var parseBytes = _require4.parseBytes;var _require5 =
__webpack_require__(44);var sha512Half = _require5.sha512Half;var transactionID = _require5.transactionID;
var makeParser = function makeParser(bytes) {return new BinaryParser(bytes);};
var readJSON = function readJSON(parser) {return parser.readType(types.STObject).toJSON();};
var binaryToJSON = function binaryToJSON(bytes) {return readJSON(makeParser(bytes));};
function serializeObject(object) {var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];var
prefix = opts.prefix;var suffix = opts.suffix;var _opts$signingFieldsOn = opts.signingFieldsOnly;var signingFieldsOnly = _opts$signingFieldsOn === undefined ? false : _opts$signingFieldsOn;
var bytesList = new BytesList();
if (prefix) {
bytesList.put(prefix);}
var filter = signingFieldsOnly ? function (f) {return f.isSigningField;} : undefined;
types.STObject.from(object).toBytesSink(bytesList, filter);
if (suffix) {
bytesList.put(suffix);}
return bytesList.toBytes();}
function signingData(tx) {var prefix = arguments.length <= 1 || arguments[1] === undefined ? HashPrefix.transactionSig : arguments[1];
return serializeObject(tx, { prefix: prefix, signingFieldsOnly: true });}
function signingClaimData(claim) {
var prefix = HashPrefix.paymentChannelClaim;
var channel = types.Hash256.from(claim.channel).toBytes();
var amount = new types.UInt64(new BN(claim.amount)).toBytes();
var bytesList = new BytesList();
bytesList.put(prefix);
bytesList.put(channel);
bytesList.put(amount);
return bytesList.toBytes();}
function multiSigningData(tx, signingAccount) {
var prefix = HashPrefix.transactionMultiSig;
var suffix = types.AccountID.from(signingAccount).toBytes();
return serializeObject(tx, { prefix: prefix, suffix: suffix, signingFieldsOnly: true });}
module.exports = {
BinaryParser: BinaryParser,
BinarySerializer: BinarySerializer,
BytesList: BytesList,
makeParser: makeParser,
serializeObject: serializeObject,
readJSON: readJSON,
bytesToHex: bytesToHex,
parseBytes: parseBytes,
multiSigningData: multiSigningData,
signingData: signingData,
signingClaimData: signingClaimData,
binaryToJSON: binaryToJSON,
sha512Half: sha512Half,
transactionID: transactionID,
slice: slice };
/***/ }),
/* 54 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(87);
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __webpack_require__(55);
exports.Duplex = __webpack_require__(25);
exports.Transform = __webpack_require__(90);
exports.PassThrough = __webpack_require__(305);
/***/ }),
/* 55 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: __webpack_require__(76)
};
/*</replacement>*/
/*<replacement>*/
var Stream = __webpack_require__(88);
/*</replacement>*/
/*<replacement>*/
var Buffer = __webpack_require__(8).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = __webpack_require__(89);
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || __webpack_require__(25);
options = options || {};
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || __webpack_require__(25);
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
processNextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
processNextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = _isUint8Array(chunk) && !state.objectMode;
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
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);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
processNextTick(cb, er);
// this can emit finish, and it will always happen
// after error
processNextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequestCount = 0;
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
processNextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) processNextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9), __webpack_require__(75).setImmediate, __webpack_require__(7)))
/***/ }),
/* 56 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const events_1 = __webpack_require__(17);
const common_1 = __webpack_require__(0);
const server = __webpack_require__(267);
const connect = server.connect;
const disconnect = server.disconnect;
const getServerInfo = server.getServerInfo;
const getFee = server.getFee;
const isConnected = server.isConnected;
const getLedgerVersion = server.getLedgerVersion;
const transaction_1 = __webpack_require__(78);
const transactions_1 = __webpack_require__(284);
const trustlines_1 = __webpack_require__(320);
const balances_1 = __webpack_require__(322);
const balance_sheet_1 = __webpack_require__(323);
const pathfind_1 = __webpack_require__(324);
const orders_1 = __webpack_require__(326);
const orderbook_1 = __webpack_require__(328);
const settings_1 = __webpack_require__(330);
const accountinfo_1 = __webpack_require__(331);
const payment_channel_1 = __webpack_require__(332);
const payment_1 = __webpack_require__(334);
const trustline_1 = __webpack_require__(335);
const order_1 = __webpack_require__(336);
const ordercancellation_1 = __webpack_require__(337);
const escrow_creation_1 = __webpack_require__(338);
const escrow_execution_1 = __webpack_require__(339);
const escrow_cancellation_1 = __webpack_require__(340);
const payment_channel_create_1 = __webpack_require__(341);
const payment_channel_fund_1 = __webpack_require__(342);
const payment_channel_claim_1 = __webpack_require__(343);
const settings_2 = __webpack_require__(344);
const sign_1 = __webpack_require__(345);
const combine_1 = __webpack_require__(346);
const submit_1 = __webpack_require__(347);
const generate_address_1 = __webpack_require__(348);
const ledgerhash_1 = __webpack_require__(349);
const sign_payment_channel_claim_1 = __webpack_require__(350);
const verify_payment_channel_claim_1 = __webpack_require__(351);
const ledger_1 = __webpack_require__(352);
const rangeset_1 = __webpack_require__(65);
const ledgerUtils = __webpack_require__(19);
const schemaValidator = __webpack_require__(58);
// prevent access to non-validated ledger versions
class RestrictedConnection extends common_1.Connection {
request(request, timeout) {
const ledger_index = request.ledger_index;
if (ledger_index !== undefined && ledger_index !== 'validated') {
if (!_.isNumber(ledger_index) || ledger_index > this._ledgerVersion) {
return Promise.reject(new common_1.errors.LedgerVersionError(`ledgerVersion ${ledger_index} is greater than server\'s ` +
`most recent validated ledger: ${this._ledgerVersion}`));
}
}
return super.request(request, timeout);
}
}
class RippleAPI extends events_1.EventEmitter {
constructor(options = {}) {
super();
this.connect = connect;
this.disconnect = disconnect;
this.isConnected = isConnected;
this.getServerInfo = getServerInfo;
this.getFee = getFee;
this.getLedgerVersion = getLedgerVersion;
this.getTransaction = transaction_1.default;
this.getTransactions = transactions_1.default;
this.getTrustlines = trustlines_1.default;
this.getBalances = balances_1.default;
this.getBalanceSheet = balance_sheet_1.default;
this.getPaths = pathfind_1.default;
this.getOrders = orders_1.default;
this.getOrderbook = orderbook_1.default;
this.getSettings = settings_1.default;
this.getAccountInfo = accountinfo_1.default;
this.getPaymentChannel = payment_channel_1.default;
this.getLedger = ledger_1.default;
this.preparePayment = payment_1.default;
this.prepareTrustline = trustline_1.default;
this.prepareOrder = order_1.default;
this.prepareOrderCancellation = ordercancellation_1.default;
this.prepareEscrowCreation = escrow_creation_1.default;
this.prepareEscrowExecution = escrow_execution_1.default;
this.prepareEscrowCancellation = escrow_cancellation_1.default;
this.preparePaymentChannelCreate = payment_channel_create_1.default;
this.preparePaymentChannelFund = payment_channel_fund_1.default;
this.preparePaymentChannelClaim = payment_channel_claim_1.default;
this.prepareSettings = settings_2.default;
this.sign = sign_1.default;
this.combine = combine_1.default;
this.submit = submit_1.default;
this.generateAddress = generate_address_1.generateAddressAPI;
this.computeLedgerHash = ledgerhash_1.default;
this.signPaymentChannelClaim = sign_payment_channel_claim_1.default;
this.verifyPaymentChannelClaim = verify_payment_channel_claim_1.default;
this.errors = common_1.errors;
common_1.validate.apiOptions(options);
this._feeCushion = options.feeCushion || 1.2;
const serverURL = options.server;
if (serverURL !== undefined) {
this.connection = new RestrictedConnection(serverURL, options);
this.connection.on('ledgerClosed', message => {
this.emit('ledger', server.formatLedgerClose(message));
});
this.connection.on('error', (errorCode, errorMessage, data) => {
this.emit('error', errorCode, errorMessage, data);
});
this.connection.on('connected', () => {
this.emit('connected');
});
this.connection.on('disconnected', code => {
this.emit('disconnected', code);
});
}
else {
// use null object pattern to provide better error message if user
// tries to call a method that requires a connection
this.connection = new RestrictedConnection(null, options);
}
}
}
// these are exposed only for use by unit tests; they are not part of the API.
RippleAPI._PRIVATE = {
validate: common_1.validate,
RangeSet: rangeset_1.default,
ledgerUtils,
schemaValidator
};
exports.RippleAPI = RippleAPI;
/***/ }),
/* 57 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const txFlags = {
// Universal flags can apply to any transaction type
Universal: {
FullyCanonicalSig: 0x80000000
},
AccountSet: {
RequireDestTag: 0x00010000,
OptionalDestTag: 0x00020000,
RequireAuth: 0x00040000,
OptionalAuth: 0x00080000,
DisallowXRP: 0x00100000,
AllowXRP: 0x00200000
},
TrustSet: {
SetAuth: 0x00010000,
NoRipple: 0x00020000,
SetNoRipple: 0x00020000,
ClearNoRipple: 0x00040000,
SetFreeze: 0x00100000,
ClearFreeze: 0x00200000
},
OfferCreate: {
Passive: 0x00010000,
ImmediateOrCancel: 0x00020000,
FillOrKill: 0x00040000,
Sell: 0x00080000
},
Payment: {
NoRippleDirect: 0x00010000,
PartialPayment: 0x00020000,
LimitQuality: 0x00040000
},
PaymentChannelClaim: {
Renew: 0x00010000,
Close: 0x00020000
}
};
exports.txFlags = txFlags;
// The following are integer (as opposed to bit) flags
// that can be set for particular transactions in the
// SetFlag or ClearFlag field
const txFlagIndices = {
AccountSet: {
asfRequireDest: 1,
asfRequireAuth: 2,
asfDisallowXRP: 3,
asfDisableMaster: 4,
asfAccountTxnID: 5,
asfNoFreeze: 6,
asfGlobalFreeze: 7,
asfDefaultRipple: 8
}
};
exports.txFlagIndices = txFlagIndices;
/***/ }),
/* 58 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const assert = __webpack_require__(2);
const { Validator } = __webpack_require__(104);
const errors_1 = __webpack_require__(39);
const ripple_address_codec_1 = __webpack_require__(33);
const utils_1 = __webpack_require__(46);
exports.isValidSecret = utils_1.isValidSecret;
function loadSchemas() {
// listed explicitly for webpack (instead of scanning schemas directory)
const schemas = [
__webpack_require__(145),
__webpack_require__(146),
__webpack_require__(147),
__webpack_require__(148),
__webpack_require__(149),
__webpack_require__(150),
__webpack_require__(151),
__webpack_require__(152),
__webpack_require__(153),
__webpack_require__(154),
__webpack_require__(155),
__webpack_require__(156),
__webpack_require__(157),
__webpack_require__(158),
__webpack_require__(159),
__webpack_require__(160),
__webpack_require__(161),
__webpack_require__(162),
__webpack_require__(163),
__webpack_require__(164),
__webpack_require__(165),
__webpack_require__(166),
__webpack_require__(167),
__webpack_require__(168),
__webpack_require__(169),
__webpack_require__(170),
__webpack_require__(171),
__webpack_require__(172),
__webpack_require__(173),
__webpack_require__(174),
__webpack_require__(175),
__webpack_require__(176),
__webpack_require__(177),
__webpack_require__(178),
__webpack_require__(179),
__webpack_require__(180),
__webpack_require__(181),
__webpack_require__(182),
__webpack_require__(183),
__webpack_require__(184),
__webpack_require__(185),
__webpack_require__(186),
__webpack_require__(187),
__webpack_require__(188),
__webpack_require__(189),
__webpack_require__(190),
__webpack_require__(191),
__webpack_require__(192),
__webpack_require__(193),
__webpack_require__(194),
__webpack_require__(195),
__webpack_require__(196),
__webpack_require__(197),
__webpack_require__(198),
__webpack_require__(199),
__webpack_require__(200),
__webpack_require__(201),
__webpack_require__(202),
__webpack_require__(203),
__webpack_require__(204),
__webpack_require__(205),
__webpack_require__(206),
__webpack_require__(207),
__webpack_require__(208),
__webpack_require__(209),
__webpack_require__(210),
__webpack_require__(211),
__webpack_require__(212),
__webpack_require__(213),
__webpack_require__(214),
__webpack_require__(215),
__webpack_require__(216),
__webpack_require__(217),
__webpack_require__(218),
__webpack_require__(219),
__webpack_require__(220),
__webpack_require__(221),
__webpack_require__(222),
__webpack_require__(223),
__webpack_require__(224),
__webpack_require__(225),
__webpack_require__(226),
__webpack_require__(227),
__webpack_require__(228),
__webpack_require__(229),
__webpack_require__(230),
__webpack_require__(231),
__webpack_require__(232),
__webpack_require__(233),
__webpack_require__(234),
__webpack_require__(235),
__webpack_require__(236),
__webpack_require__(237),
__webpack_require__(238),
__webpack_require__(239),
__webpack_require__(240),
__webpack_require__(241),
__webpack_require__(242),
__webpack_require__(243)
];
const titles = schemas.map(schema => schema.title);
const duplicates = _.keys(_.pickBy(_.countBy(titles), count => count > 1));
assert(duplicates.length === 0, 'Duplicate schemas for: ' + duplicates);
const validator = new Validator();
// Register custom format validators that ignore undefined instances
// since jsonschema will still call the format validator on a missing
// (optional) property
validator.customFormats.address = function (instance) {
if (instance === undefined) {
return true;
}
return ripple_address_codec_1.isValidAddress(instance);
};
validator.customFormats.secret = function (instance) {
if (instance === undefined) {
return true;
}
return utils_1.isValidSecret(instance);
};
// Register under the root URI '/'
_.forEach(schemas, schema => validator.addSchema(schema, '/' + schema.title));
return validator;
}
const schemaValidator = loadSchemas();
function schemaValidate(schemaName, object) {
// Lookup under the root URI '/'
const schema = schemaValidator.getSchema('/' + schemaName);
if (schema === undefined) {
throw new errors_1.ValidationError('no schema for ' + schemaName);
}
const result = schemaValidator.validate(object, schema);
if (!result.valid) {
throw new errors_1.ValidationError(result.errors.join());
}
}
exports.schemaValidate = schemaValidate;
/***/ }),
/* 59 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(14);
var rotr32 = utils.rotr32;
function ft_1(s, x, y, z) {
if (s === 0)
return ch32(x, y, z);
if (s === 1 || s === 3)
return p32(x, y, z);
if (s === 2)
return maj32(x, y, z);
}
exports.ft_1 = ft_1;
function ch32(x, y, z) {
return (x & y) ^ ((~x) & z);
}
exports.ch32 = ch32;
function maj32(x, y, z) {
return (x & y) ^ (x & z) ^ (y & z);
}
exports.maj32 = maj32;
function p32(x, y, z) {
return x ^ y ^ z;
}
exports.p32 = p32;
function s0_256(x) {
return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
}
exports.s0_256 = s0_256;
function s1_256(x) {
return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
}
exports.s1_256 = s1_256;
function g0_256(x) {
return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
}
exports.g0_256 = g0_256;
function g1_256(x) {
return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
}
exports.g1_256 = g1_256;
/***/ }),
/* 60 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(14);
var common = __webpack_require__(35);
var shaCommon = __webpack_require__(59);
var assert = __webpack_require__(34);
var sum32 = utils.sum32;
var sum32_4 = utils.sum32_4;
var sum32_5 = utils.sum32_5;
var ch32 = shaCommon.ch32;
var maj32 = shaCommon.maj32;
var s0_256 = shaCommon.s0_256;
var s1_256 = shaCommon.s1_256;
var g0_256 = shaCommon.g0_256;
var g1_256 = shaCommon.g1_256;
var BlockHash = common.BlockHash;
var sha256_K = [
0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
];
function SHA256() {
if (!(this instanceof SHA256))
return new SHA256();
BlockHash.call(this);
this.h = [
0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
];
this.k = sha256_K;
this.W = new Array(64);
}
utils.inherits(SHA256, BlockHash);
module.exports = SHA256;
SHA256.blockSize = 512;
SHA256.outSize = 256;
SHA256.hmacStrength = 192;
SHA256.padLength = 64;
SHA256.prototype._update = function _update(msg, start) {
var W = this.W;
for (var i = 0; i < 16; i++)
W[i] = msg[start + i];
for (; i < W.length; i++)
W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
var a = this.h[0];
var b = this.h[1];
var c = this.h[2];
var d = this.h[3];
var e = this.h[4];
var f = this.h[5];
var g = this.h[6];
var h = this.h[7];
assert(this.k.length === W.length);
for (i = 0; i < W.length; i++) {
var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
var T2 = sum32(s0_256(a), maj32(a, b, c));
h = g;
g = f;
f = e;
e = sum32(d, T1);
d = c;
c = b;
b = a;
a = sum32(T1, T2);
}
this.h[0] = sum32(this.h[0], a);
this.h[1] = sum32(this.h[1], b);
this.h[2] = sum32(this.h[2], c);
this.h[3] = sum32(this.h[3], d);
this.h[4] = sum32(this.h[4], e);
this.h[5] = sum32(this.h[5], f);
this.h[6] = sum32(this.h[6], g);
this.h[7] = sum32(this.h[7], h);
};
SHA256.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h, 'big');
else
return utils.split32(this.h, 'big');
};
/***/ }),
/* 61 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var utils = __webpack_require__(14);
var common = __webpack_require__(35);
var assert = __webpack_require__(34);
var rotr64_hi = utils.rotr64_hi;
var rotr64_lo = utils.rotr64_lo;
var shr64_hi = utils.shr64_hi;
var shr64_lo = utils.shr64_lo;
var sum64 = utils.sum64;
var sum64_hi = utils.sum64_hi;
var sum64_lo = utils.sum64_lo;
var sum64_4_hi = utils.sum64_4_hi;
var sum64_4_lo = utils.sum64_4_lo;
var sum64_5_hi = utils.sum64_5_hi;
var sum64_5_lo = utils.sum64_5_lo;
var BlockHash = common.BlockHash;
var sha512_K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
];
function SHA512() {
if (!(this instanceof SHA512))
return new SHA512();
BlockHash.call(this);
this.h = [
0x6a09e667, 0xf3bcc908,
0xbb67ae85, 0x84caa73b,
0x3c6ef372, 0xfe94f82b,
0xa54ff53a, 0x5f1d36f1,
0x510e527f, 0xade682d1,
0x9b05688c, 0x2b3e6c1f,
0x1f83d9ab, 0xfb41bd6b,
0x5be0cd19, 0x137e2179 ];
this.k = sha512_K;
this.W = new Array(160);
}
utils.inherits(SHA512, BlockHash);
module.exports = SHA512;
SHA512.blockSize = 1024;
SHA512.outSize = 512;
SHA512.hmacStrength = 192;
SHA512.padLength = 128;
SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
var W = this.W;
// 32 x 32bit words
for (var i = 0; i < 32; i++)
W[i] = msg[start + i];
for (; i < W.length; i += 2) {
var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
var c1_hi = W[i - 14]; // i - 7
var c1_lo = W[i - 13];
var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
var c3_hi = W[i - 32]; // i - 16
var c3_lo = W[i - 31];
W[i] = sum64_4_hi(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo);
W[i + 1] = sum64_4_lo(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo);
}
};
SHA512.prototype._update = function _update(msg, start) {
this._prepareBlock(msg, start);
var W = this.W;
var ah = this.h[0];
var al = this.h[1];
var bh = this.h[2];
var bl = this.h[3];
var ch = this.h[4];
var cl = this.h[5];
var dh = this.h[6];
var dl = this.h[7];
var eh = this.h[8];
var el = this.h[9];
var fh = this.h[10];
var fl = this.h[11];
var gh = this.h[12];
var gl = this.h[13];
var hh = this.h[14];
var hl = this.h[15];
assert(this.k.length === W.length);
for (var i = 0; i < W.length; i += 2) {
var c0_hi = hh;
var c0_lo = hl;
var c1_hi = s1_512_hi(eh, el);
var c1_lo = s1_512_lo(eh, el);
var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
var c3_hi = this.k[i];
var c3_lo = this.k[i + 1];
var c4_hi = W[i];
var c4_lo = W[i + 1];
var T1_hi = sum64_5_hi(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo,
c4_hi, c4_lo);
var T1_lo = sum64_5_lo(
c0_hi, c0_lo,
c1_hi, c1_lo,
c2_hi, c2_lo,
c3_hi, c3_lo,
c4_hi, c4_lo);
c0_hi = s0_512_hi(ah, al);
c0_lo = s0_512_lo(ah, al);
c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
eh = sum64_hi(dh, dl, T1_hi, T1_lo);
el = sum64_lo(dl, dl, T1_hi, T1_lo);
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
}
sum64(this.h, 0, ah, al);
sum64(this.h, 2, bh, bl);
sum64(this.h, 4, ch, cl);
sum64(this.h, 6, dh, dl);
sum64(this.h, 8, eh, el);
sum64(this.h, 10, fh, fl);
sum64(this.h, 12, gh, gl);
sum64(this.h, 14, hh, hl);
};
SHA512.prototype._digest = function digest(enc) {
if (enc === 'hex')
return utils.toHex32(this.h, 'big');
else
return utils.split32(this.h, 'big');
};
function ch64_hi(xh, xl, yh, yl, zh) {
var r = (xh & yh) ^ ((~xh) & zh);
if (r < 0)
r += 0x100000000;
return r;
}
function ch64_lo(xh, xl, yh, yl, zh, zl) {
var r = (xl & yl) ^ ((~xl) & zl);
if (r < 0)
r += 0x100000000;
return r;
}
function maj64_hi(xh, xl, yh, yl, zh) {
var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
if (r < 0)
r += 0x100000000;
return r;
}
function maj64_lo(xh, xl, yh, yl, zh, zl) {
var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
if (r < 0)
r += 0x100000000;
return r;
}
function s0_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 28);
var c1_hi = rotr64_hi(xl, xh, 2); // 34
var c2_hi = rotr64_hi(xl, xh, 7); // 39
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function s0_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 28);
var c1_lo = rotr64_lo(xl, xh, 2); // 34
var c2_lo = rotr64_lo(xl, xh, 7); // 39
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function s1_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 14);
var c1_hi = rotr64_hi(xh, xl, 18);
var c2_hi = rotr64_hi(xl, xh, 9); // 41
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function s1_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 14);
var c1_lo = rotr64_lo(xh, xl, 18);
var c2_lo = rotr64_lo(xl, xh, 9); // 41
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function g0_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 1);
var c1_hi = rotr64_hi(xh, xl, 8);
var c2_hi = shr64_hi(xh, xl, 7);
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function g0_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 1);
var c1_lo = rotr64_lo(xh, xl, 8);
var c2_lo = shr64_lo(xh, xl, 7);
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
function g1_512_hi(xh, xl) {
var c0_hi = rotr64_hi(xh, xl, 19);
var c1_hi = rotr64_hi(xl, xh, 29); // 61
var c2_hi = shr64_hi(xh, xl, 6);
var r = c0_hi ^ c1_hi ^ c2_hi;
if (r < 0)
r += 0x100000000;
return r;
}
function g1_512_lo(xh, xl) {
var c0_lo = rotr64_lo(xh, xl, 19);
var c1_lo = rotr64_lo(xl, xh, 29); // 61
var c2_lo = shr64_lo(xh, xl, 6);
var r = c0_lo ^ c1_lo ^ c2_lo;
if (r < 0)
r += 0x100000000;
return r;
}
/***/ }),
/* 62 */
/***/ (function(module, exports, __webpack_require__) {
var r;
module.exports = function rand(len) {
if (!r)
r = new Rand(null);
return r.generate(len);
};
function Rand(rand) {
this.rand = rand;
}
module.exports.Rand = Rand;
Rand.prototype.generate = function generate(len) {
return this._rand(len);
};
// Emulate crypto API using randy
Rand.prototype._rand = function _rand(n) {
if (this.rand.getBytes)
return this.rand.getBytes(n);
var res = new Uint8Array(n);
for (var i = 0; i < res.length; i++)
res[i] = this.rand.getByte();
return res;
};
if (typeof self === 'object') {
if (self.crypto && self.crypto.getRandomValues) {
// Modern browsers
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
self.crypto.getRandomValues(arr);
return arr;
};
} else if (self.msCrypto && self.msCrypto.getRandomValues) {
// IE
Rand.prototype._rand = function _rand(n) {
var arr = new Uint8Array(n);
self.msCrypto.getRandomValues(arr);
return arr;
};
// Safari's WebWorkers do not have `crypto`
} else if (typeof window === 'object') {
// Old junk
Rand.prototype._rand = function() {
throw new Error('Not implemented yet');
};
}
} else {
// Node.js or Web worker with no crypto support
try {
var crypto = __webpack_require__(122);
if (typeof crypto.randomBytes !== 'function')
throw new Error('Not supported');
Rand.prototype._rand = function _rand(n) {
return crypto.randomBytes(n);
};
} catch (e) {
}
}
/***/ }),
/* 63 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// eslint-disable-line strict
var elliptic = __webpack_require__(12);
var secp256k1 = elliptic.ec('secp256k1');
var Sha512 = __webpack_require__(138);
function deriveScalar(bytes, discrim) {
var order = secp256k1.curve.n;
for (var i = 0; i <= 0xFFFFFFFF; i++) {
// We hash the bytes to find a 256 bit number, looping until we are sure it
// is less than the order of the curve.
var hasher = new Sha512().add(bytes);
// If the optional discriminator index was passed in, update the hash.
if (discrim !== undefined) {
hasher.addU32(discrim);
}
hasher.addU32(i);
var key = hasher.first256BN();
if (key.cmpn(0) > 0 && key.cmp(order) < 0) {
return key;
}
}
throw new Error('impossible unicorn ;)');
}
/**
* @param {Array} seed - bytes
* @param {Object} [opts] - object
* @param {Number} [opts.accountIndex=0] - the account number to generate
* @param {Boolean} [opts.validator=false] - generate root key-pair,
* as used by validators.
* @return {bn.js} - 256 bit scalar value
*
*/
function derivePrivateKey(seed) {
var opts = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
var root = opts.validator;
var order = secp256k1.curve.n;
// This private generator represents the `root` private key, and is what's
// used by validators for signing when a keypair is generated from a seed.
var privateGen = deriveScalar(seed);
if (root) {
// As returned by validation_create for a given seed
return privateGen;
}
var publicGen = secp256k1.g.mul(privateGen);
// A seed can generate many keypairs as a function of the seed and a uint32.
// Almost everyone just uses the first account, `0`.
var accountIndex = opts.accountIndex || 0;
return deriveScalar(publicGen.encodeCompressed(), accountIndex).add(privateGen).mod(order);
}
function accountPublicFromPublicGenerator(publicGenBytes) {
var rootPubPoint = secp256k1.curve.decodePoint(publicGenBytes);
var scalar = deriveScalar(publicGenBytes, 0);
var point = secp256k1.g.mul(scalar);
var offset = rootPubPoint.add(point);
return offset.encodeCompressed();
}
module.exports = {
derivePrivateKey: derivePrivateKey,
accountPublicFromPublicGenerator: accountPublicFromPublicGenerator
};
/***/ }),
/* 64 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) {
'use strict';
// Utils
function assert(val, msg) {
if (!val)
throw new Error(msg || 'Assertion failed');
}
// Could use `inherits` module, but don't want to move from single file
// architecture yet.
function inherits(ctor, superCtor) {
ctor.super_ = superCtor;
var TempCtor = function () {};
TempCtor.prototype = superCtor.prototype;
ctor.prototype = new TempCtor();
ctor.prototype.constructor = ctor;
}
// BN
function BN(number, base, endian) {
// May be `new BN(bn)` ?
if (number !== null &&
typeof number === 'object' &&
Array.isArray(number.words)) {
return number;
}
this.sign = false;
this.words = null;
this.length = 0;
// Reduction context
this.red = null;
if (base === 'le' || base === 'be') {
endian = base;
base = 10;
}
if (number !== null)
this._init(number || 0, base || 10, endian || 'be');
}
if (typeof module === 'object')
module.exports = BN;
else
exports.BN = BN;
BN.BN = BN;
BN.wordSize = 26;
BN.max = function max(left, right) {
if (left.cmp(right) > 0)
return left;
else
return right;
};
BN.min = function min(left, right) {
if (left.cmp(right) < 0)
return left;
else
return right;
};
BN.prototype._init = function init(number, base, endian) {
if (typeof number === 'number') {
return this._initNumber(number, base, endian);
} else if (typeof number === 'object') {
return this._initArray(number, base, endian);
}
if (base === 'hex')
base = 16;
assert(base === (base | 0) && base >= 2 && base <= 36);
number = number.toString().replace(/\s+/g, '');
var start = 0;
if (number[0] === '-')
start++;
if (base === 16)
this._parseHex(number, start);
else
this._parseBase(number, base, start);
if (number[0] === '-')
this.sign = true;
this.strip();
if (endian !== 'le')
return;
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initNumber = function _initNumber(number, base, endian) {
if (number < 0) {
this.sign = true;
number = -number;
}
if (number < 0x4000000) {
this.words = [ number & 0x3ffffff ];
this.length = 1;
} else if (number < 0x10000000000000) {
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff
];
this.length = 2;
} else {
assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
this.words = [
number & 0x3ffffff,
(number / 0x4000000) & 0x3ffffff,
1
];
this.length = 3;
}
if (endian !== 'le')
return;
// Reverse the bytes
this._initArray(this.toArray(), base, endian);
};
BN.prototype._initArray = function _initArray(number, base, endian) {
// Perhaps a Uint8Array
assert(typeof number.length === 'number');
if (number.length <= 0) {
this.words = [ 0 ];
this.length = 1;
return this;
}
this.length = Math.ceil(number.length / 3);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++)
this.words[i] = 0;
var off = 0;
if (endian === 'be') {
for (var i = number.length - 1, j = 0; i >= 0; i -= 3) {
var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
} else if (endian === 'le') {
for (var i = 0, j = 0; i < number.length; i += 3) {
var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
}
return this.strip();
};
function parseHex(str, start, end) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r <<= 4;
// 'a' - 'f'
if (c >= 49 && c <= 54)
r |= c - 49 + 0xa;
// 'A' - 'F'
else if (c >= 17 && c <= 22)
r |= c - 17 + 0xa;
// '0' - '9'
else
r |= c & 0xf;
}
return r;
}
BN.prototype._parseHex = function _parseHex(number, start) {
// Create possibly bigger array to ensure that it fits the number
this.length = Math.ceil((number.length - start) / 6);
this.words = new Array(this.length);
for (var i = 0; i < this.length; i++)
this.words[i] = 0;
// Scan 24-bit chunks and add them to the number
var off = 0;
for (var i = number.length - 6, j = 0; i >= start; i -= 6) {
var w = parseHex(number, i, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
off += 24;
if (off >= 26) {
off -= 26;
j++;
}
}
if (i + 6 !== start) {
var w = parseHex(number, start, i + 6);
this.words[j] |= (w << off) & 0x3ffffff;
this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
}
this.strip();
};
function parseBase(str, start, end, mul) {
var r = 0;
var len = Math.min(str.length, end);
for (var i = start; i < len; i++) {
var c = str.charCodeAt(i) - 48;
r *= mul;
// 'a'
if (c >= 49)
r += c - 49 + 0xa;
// 'A'
else if (c >= 17)
r += c - 17 + 0xa;
// '0' - '9'
else
r += c;
}
return r;
}
BN.prototype._parseBase = function _parseBase(number, base, start) {
// Initialize as zero
this.words = [ 0 ];
this.length = 1;
// Find length of limb in base
for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base)
limbLen++;
limbLen--;
limbPow = (limbPow / base) | 0;
var total = number.length - start;
var mod = total % limbLen;
var end = Math.min(total, total - mod) + start;
var word = 0;
for (var i = start; i < end; i += limbLen) {
word = parseBase(number, i, i + limbLen, base);
this.imuln(limbPow);
if (this.words[0] + word < 0x4000000)
this.words[0] += word;
else
this._iaddn(word);
}
if (mod !== 0) {
var pow = 1;
var word = parseBase(number, i, number.length, base);
for (var i = 0; i < mod; i++)
pow *= base;
this.imuln(pow);
if (this.words[0] + word < 0x4000000)
this.words[0] += word;
else
this._iaddn(word);
}
};
BN.prototype.copy = function copy(dest) {
dest.words = new Array(this.length);
for (var i = 0; i < this.length; i++)
dest.words[i] = this.words[i];
dest.length = this.length;
dest.sign = this.sign;
dest.red = this.red;
};
BN.prototype.clone = function clone() {
var r = new BN(null);
this.copy(r);
return r;
};
// Remove leading `0` from `this`
BN.prototype.strip = function strip() {
while (this.length > 1 && this.words[this.length - 1] === 0)
this.length--;
return this._normSign();
};
BN.prototype._normSign = function _normSign() {
// -0 = 0
if (this.length === 1 && this.words[0] === 0)
this.sign = false;
return this;
};
BN.prototype.inspect = function inspect() {
return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
};
/*
var zeros = [];
var groupSizes = [];
var groupBases = [];
var s = '';
var i = -1;
while (++i < BN.wordSize) {
zeros[i] = s;
s += '0';
}
groupSizes[0] = 0;
groupSizes[1] = 0;
groupBases[0] = 0;
groupBases[1] = 0;
var base = 2 - 1;
while (++base < 36 + 1) {
var groupSize = 0;
var groupBase = 1;
while (groupBase < (1 << BN.wordSize) / base) {
groupBase *= base;
groupSize += 1;
}
groupSizes[base] = groupSize;
groupBases[base] = groupBase;
}
*/
var zeros = [
'',
'0',
'00',
'000',
'0000',
'00000',
'000000',
'0000000',
'00000000',
'000000000',
'0000000000',
'00000000000',
'000000000000',
'0000000000000',
'00000000000000',
'000000000000000',
'0000000000000000',
'00000000000000000',
'000000000000000000',
'0000000000000000000',
'00000000000000000000',
'000000000000000000000',
'0000000000000000000000',
'00000000000000000000000',
'000000000000000000000000',
'0000000000000000000000000'
];
var groupSizes = [
0, 0,
25, 16, 12, 11, 10, 9, 8,
8, 7, 7, 7, 7, 6, 6,
6, 6, 6, 6, 6, 5, 5,
5, 5, 5, 5, 5, 5, 5,
5, 5, 5, 5, 5, 5, 5
];
var groupBases = [
0, 0,
33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
];
BN.prototype.toString = function toString(base, padding) {
base = base || 10;
var padding = padding | 0 || 1;
if (base === 16 || base === 'hex') {
var out = '';
var off = 0;
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i];
var word = (((w << off) | carry) & 0xffffff).toString(16);
carry = (w >>> (24 - off)) & 0xffffff;
if (carry !== 0 || i !== this.length - 1)
out = zeros[6 - word.length] + word + out;
else
out = word + out;
off += 2;
if (off >= 26) {
off -= 26;
i--;
}
}
if (carry !== 0)
out = carry.toString(16) + out;
while (out.length % padding !== 0)
out = '0' + out;
if (this.sign)
out = '-' + out;
return out;
} else if (base === (base | 0) && base >= 2 && base <= 36) {
// var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
var groupSize = groupSizes[base];
// var groupBase = Math.pow(base, groupSize);
var groupBase = groupBases[base];
var out = '';
var c = this.clone();
c.sign = false;
while (c.cmpn(0) !== 0) {
var r = c.modn(groupBase).toString(base);
c = c.idivn(groupBase);
if (c.cmpn(0) !== 0)
out = zeros[groupSize - r.length] + r + out;
else
out = r + out;
}
if (this.cmpn(0) === 0)
out = '0' + out;
while (out.length % padding !== 0)
out = '0' + out;
if (this.sign)
out = '-' + out;
return out;
} else {
assert(false, 'Base should be between 2 and 36');
}
};
BN.prototype.toJSON = function toJSON() {
return this.toString(16);
};
BN.prototype.toArray = function toArray(endian, length) {
this.strip();
var littleEndian = endian === 'le';
var res = new Array(this.byteLength());
res[0] = 0;
var q = this.clone();
if (!littleEndian) {
// Assume big-endian
for (var i = 0; q.cmpn(0) !== 0; i++) {
var b = q.andln(0xff);
q.iushrn(8);
res[res.length - i - 1] = b;
}
} else {
for (var i = 0; q.cmpn(0) !== 0; i++) {
var b = q.andln(0xff);
q.iushrn(8);
res[i] = b;
}
}
if (length) {
assert(res.length <= length, 'byte array longer than desired length');
while (res.length < length) {
if (littleEndian)
res.push(0);
else
res.unshift(0);
}
}
return res;
};
if (Math.clz32) {
BN.prototype._countBits = function _countBits(w) {
return 32 - Math.clz32(w);
};
} else {
BN.prototype._countBits = function _countBits(w) {
var t = w;
var r = 0;
if (t >= 0x1000) {
r += 13;
t >>>= 13;
}
if (t >= 0x40) {
r += 7;
t >>>= 7;
}
if (t >= 0x8) {
r += 4;
t >>>= 4;
}
if (t >= 0x02) {
r += 2;
t >>>= 2;
}
return r + t;
};
}
BN.prototype._zeroBits = function _zeroBits(w) {
// Short-cut
if (w === 0)
return 26;
var t = w;
var r = 0;
if ((t & 0x1fff) === 0) {
r += 13;
t >>>= 13;
}
if ((t & 0x7f) === 0) {
r += 7;
t >>>= 7;
}
if ((t & 0xf) === 0) {
r += 4;
t >>>= 4;
}
if ((t & 0x3) === 0) {
r += 2;
t >>>= 2;
}
if ((t & 0x1) === 0)
r++;
return r;
};
// Return number of used bits in a BN
BN.prototype.bitLength = function bitLength() {
var hi = 0;
var w = this.words[this.length - 1];
var hi = this._countBits(w);
return (this.length - 1) * 26 + hi;
};
function toBitArray(num) {
var w = new Array(num.bitLength());
for (var bit = 0; bit < w.length; bit++) {
var off = (bit / 26) | 0;
var wbit = bit % 26;
w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
}
return w;
}
// Number of trailing zero bits
BN.prototype.zeroBits = function zeroBits() {
if (this.cmpn(0) === 0)
return 0;
var r = 0;
for (var i = 0; i < this.length; i++) {
var b = this._zeroBits(this.words[i]);
r += b;
if (b !== 26)
break;
}
return r;
};
BN.prototype.byteLength = function byteLength() {
return Math.ceil(this.bitLength() / 8);
};
// Return negative clone of `this`
BN.prototype.neg = function neg() {
if (this.cmpn(0) === 0)
return this.clone();
var r = this.clone();
r.sign = !this.sign;
return r;
};
// Or `num` with `this` in-place
BN.prototype.iuor = function iuor(num) {
while (this.length < num.length)
this.words[this.length++] = 0;
for (var i = 0; i < num.length; i++)
this.words[i] = this.words[i] | num.words[i];
return this.strip();
};
BN.prototype.ior = function ior(num) {
assert(!this.sign && !num.sign);
return this.iuor(num);
};
// Or `num` with `this`
BN.prototype.or = function or(num) {
if (this.length > num.length)
return this.clone().ior(num);
else
return num.clone().ior(this);
};
BN.prototype.uor = function uor(num) {
if (this.length > num.length)
return this.clone().iuor(num);
else
return num.clone().iuor(this);
};
// And `num` with `this` in-place
BN.prototype.iuand = function iuand(num) {
// b = min-length(num, this)
var b;
if (this.length > num.length)
b = num;
else
b = this;
for (var i = 0; i < b.length; i++)
this.words[i] = this.words[i] & num.words[i];
this.length = b.length;
return this.strip();
};
BN.prototype.iand = function iand(num) {
assert(!this.sign && !num.sign);
return this.iuand(num);
};
// And `num` with `this`
BN.prototype.and = function and(num) {
if (this.length > num.length)
return this.clone().iand(num);
else
return num.clone().iand(this);
};
BN.prototype.uand = function uand(num) {
if (this.length > num.length)
return this.clone().iuand(num);
else
return num.clone().iuand(this);
};
// Xor `num` with `this` in-place
BN.prototype.iuxor = function iuxor(num) {
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
for (var i = 0; i < b.length; i++)
this.words[i] = a.words[i] ^ b.words[i];
if (this !== a)
for (; i < a.length; i++)
this.words[i] = a.words[i];
this.length = a.length;
return this.strip();
};
BN.prototype.ixor = function ixor(num) {
assert(!this.sign && !num.sign);
return this.iuxor(num);
};
// Xor `num` with `this`
BN.prototype.xor = function xor(num) {
if (this.length > num.length)
return this.clone().ixor(num);
else
return num.clone().ixor(this);
};
BN.prototype.uxor = function uxor(num) {
if (this.length > num.length)
return this.clone().iuxor(num);
else
return num.clone().iuxor(this);
};
// Set `bit` of `this`
BN.prototype.setn = function setn(bit, val) {
assert(typeof bit === 'number' && bit >= 0);
var off = (bit / 26) | 0;
var wbit = bit % 26;
while (this.length <= off)
this.words[this.length++] = 0;
if (val)
this.words[off] = this.words[off] | (1 << wbit);
else
this.words[off] = this.words[off] & ~(1 << wbit);
return this.strip();
};
// Add `num` to `this` in-place
BN.prototype.iadd = function iadd(num) {
// negative + positive
if (this.sign && !num.sign) {
this.sign = false;
var r = this.isub(num);
this.sign = !this.sign;
return this._normSign();
// positive + negative
} else if (!this.sign && num.sign) {
num.sign = false;
var r = this.isub(num);
num.sign = true;
return r._normSign();
}
// a.length > b.length
var a;
var b;
if (this.length > num.length) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
var r = a.words[i] + b.words[i] + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
for (; carry !== 0 && i < a.length; i++) {
var r = a.words[i] + carry;
this.words[i] = r & 0x3ffffff;
carry = r >>> 26;
}
this.length = a.length;
if (carry !== 0) {
this.words[this.length] = carry;
this.length++;
// Copy the rest of the words
} else if (a !== this) {
for (; i < a.length; i++)
this.words[i] = a.words[i];
}
return this;
};
// Add `num` to `this`
BN.prototype.add = function add(num) {
if (num.sign && !this.sign) {
num.sign = false;
var res = this.sub(num);
num.sign = true;
return res;
} else if (!num.sign && this.sign) {
this.sign = false;
var res = num.sub(this);
this.sign = true;
return res;
}
if (this.length > num.length)
return this.clone().iadd(num);
else
return num.clone().iadd(this);
};
// Subtract `num` from `this` in-place
BN.prototype.isub = function isub(num) {
// this - (-num) = this + num
if (num.sign) {
num.sign = false;
var r = this.iadd(num);
num.sign = true;
return r._normSign();
// -this - num = -(this + num)
} else if (this.sign) {
this.sign = false;
this.iadd(num);
this.sign = true;
return this._normSign();
}
// At this point both numbers are positive
var cmp = this.cmp(num);
// Optimization - zeroify
if (cmp === 0) {
this.sign = false;
this.length = 1;
this.words[0] = 0;
return this;
}
// a > b
var a;
var b;
if (cmp > 0) {
a = this;
b = num;
} else {
a = num;
b = this;
}
var carry = 0;
for (var i = 0; i < b.length; i++) {
var r = a.words[i] - b.words[i] + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
for (; carry !== 0 && i < a.length; i++) {
var r = a.words[i] + carry;
carry = r >> 26;
this.words[i] = r & 0x3ffffff;
}
// Copy rest of the words
if (carry === 0 && i < a.length && a !== this)
for (; i < a.length; i++)
this.words[i] = a.words[i];
this.length = Math.max(this.length, i);
if (a !== this)
this.sign = true;
return this.strip();
};
// Subtract `num` from `this`
BN.prototype.sub = function sub(num) {
return this.clone().isub(num);
};
/*
// NOTE: This could be potentionally used to generate loop-less multiplications
function _genCombMulTo(alen, blen) {
var len = alen + blen - 1;
var src = [
'var a = this.words, b = num.words, o = out.words, c = 0, w, ' +
'mask = 0x3ffffff, shift = 0x4000000;',
'out.length = ' + len + ';'
];
for (var k = 0; k < len; k++) {
var minJ = Math.max(0, k - alen + 1);
var maxJ = Math.min(k, blen - 1);
for (var j = minJ; j <= maxJ; j++) {
var i = k - j;
var mul = 'a[' + i + '] * b[' + j + ']';
if (j === minJ) {
src.push('w = ' + mul + ' + c;');
src.push('c = (w / shift) | 0;');
} else {
src.push('w += ' + mul + ';');
src.push('c += (w / shift) | 0;');
}
src.push('w &= mask;');
}
src.push('o[' + k + '] = w;');
}
src.push('if (c !== 0) {',
' o[' + k + '] = c;',
' out.length++;',
'}',
'return out;');
return src.join('\n');
}
*/
BN.prototype._smallMulTo = function _smallMulTo(num, out) {
out.sign = num.sign !== this.sign;
out.length = this.length + num.length;
var carry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = carry >>> 26;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = this.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
}
out.words[k] = rword;
carry = ncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out.strip();
};
BN.prototype._bigMulTo = function _bigMulTo(num, out) {
out.sign = num.sign !== this.sign;
out.length = this.length + num.length;
var carry = 0;
var hncarry = 0;
for (var k = 0; k < out.length - 1; k++) {
// Sum all words with the same `i + j = k` and accumulate `ncarry`,
// note that ncarry could be >= 0x3ffffff
var ncarry = hncarry;
hncarry = 0;
var rword = carry & 0x3ffffff;
var maxJ = Math.min(k, num.length - 1);
for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) {
var i = k - j;
var a = this.words[i] | 0;
var b = num.words[j] | 0;
var r = a * b;
var lo = r & 0x3ffffff;
ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
lo = (lo + rword) | 0;
rword = lo & 0x3ffffff;
ncarry = (ncarry + (lo >>> 26)) | 0;
hncarry += ncarry >>> 26;
ncarry &= 0x3ffffff;
}
out.words[k] = rword;
carry = ncarry;
ncarry = hncarry;
}
if (carry !== 0) {
out.words[k] = carry;
} else {
out.length--;
}
return out.strip();
};
BN.prototype.mulTo = function mulTo(num, out) {
var res;
if (this.length + num.length < 63)
res = this._smallMulTo(num, out);
else
res = this._bigMulTo(num, out);
return res;
};
// Multiply `this` by `num`
BN.prototype.mul = function mul(num) {
var out = new BN(null);
out.words = new Array(this.length + num.length);
return this.mulTo(num, out);
};
// In-place Multiplication
BN.prototype.imul = function imul(num) {
if (this.cmpn(0) === 0 || num.cmpn(0) === 0) {
this.words[0] = 0;
this.length = 1;
return this;
}
var tlen = this.length;
var nlen = num.length;
this.sign = num.sign !== this.sign;
this.length = this.length + num.length;
this.words[this.length - 1] = 0;
for (var k = this.length - 2; k >= 0; k--) {
// Sum all words with the same `i + j = k` and accumulate `carry`,
// note that carry could be >= 0x3ffffff
var carry = 0;
var rword = 0;
var maxJ = Math.min(k, nlen - 1);
for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) {
var i = k - j;
var a = this.words[i];
var b = num.words[j];
var r = a * b;
var lo = r & 0x3ffffff;
carry += (r / 0x4000000) | 0;
lo += rword;
rword = lo & 0x3ffffff;
carry += lo >>> 26;
}
this.words[k] = rword;
this.words[k + 1] += carry;
carry = 0;
}
// Propagate overflows
var carry = 0;
for (var i = 1; i < this.length; i++) {
var w = this.words[i] + carry;
this.words[i] = w & 0x3ffffff;
carry = w >>> 26;
}
return this.strip();
};
BN.prototype.imuln = function imuln(num) {
assert(typeof num === 'number');
// Carry
var carry = 0;
for (var i = 0; i < this.length; i++) {
var w = this.words[i] * num;
var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
carry >>= 26;
carry += (w / 0x4000000) | 0;
// NOTE: lo is 27bit maximum
carry += lo >>> 26;
this.words[i] = lo & 0x3ffffff;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.muln = function muln(num) {
return this.clone().imuln(num);
};
// `this` * `this`
BN.prototype.sqr = function sqr() {
return this.mul(this);
};
// `this` * `this` in-place
BN.prototype.isqr = function isqr() {
return this.mul(this);
};
// Math.pow(`this`, `num`)
BN.prototype.pow = function pow(num) {
var w = toBitArray(num);
if (w.length === 0)
return new BN(1);
// Skip leading zeroes
var res = this;
for (var i = 0; i < w.length; i++, res = res.sqr())
if (w[i] !== 0)
break;
if (++i < w.length) {
for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
if (w[i] === 0)
continue;
res = res.mul(q);
}
}
return res;
};
// Shift-left in-place
BN.prototype.iushln = function iushln(bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
if (r !== 0) {
var carry = 0;
for (var i = 0; i < this.length; i++) {
var newCarry = this.words[i] & carryMask;
var c = (this.words[i] - newCarry) << r;
this.words[i] = c | carry;
carry = newCarry >>> (26 - r);
}
if (carry) {
this.words[i] = carry;
this.length++;
}
}
if (s !== 0) {
for (var i = this.length - 1; i >= 0; i--)
this.words[i + s] = this.words[i];
for (var i = 0; i < s; i++)
this.words[i] = 0;
this.length += s;
}
return this.strip();
};
BN.prototype.ishln = function ishln(bits) {
// TODO(indutny): implement me
assert(!this.sign);
return this.iushln(bits);
};
// Shift-right in-place
// NOTE: `hint` is a lowest bit before trailing zeroes
// NOTE: if `extended` is present - it will be filled with destroyed bits
BN.prototype.iushrn = function iushrn(bits, hint, extended) {
assert(typeof bits === 'number' && bits >= 0);
var h;
if (hint)
h = (hint - (hint % 26)) / 26;
else
h = 0;
var r = bits % 26;
var s = Math.min((bits - r) / 26, this.length);
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
var maskedWords = extended;
h -= s;
h = Math.max(0, h);
// Extended mode, copy masked part
if (maskedWords) {
for (var i = 0; i < s; i++)
maskedWords.words[i] = this.words[i];
maskedWords.length = s;
}
if (s === 0) {
// No-op, we should not move anything at all
} else if (this.length > s) {
this.length -= s;
for (var i = 0; i < this.length; i++)
this.words[i] = this.words[i + s];
} else {
this.words[0] = 0;
this.length = 1;
}
var carry = 0;
for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
var word = this.words[i];
this.words[i] = (carry << (26 - r)) | (word >>> r);
carry = word & mask;
}
// Push carried bits as a mask
if (maskedWords && carry !== 0)
maskedWords.words[maskedWords.length++] = carry;
if (this.length === 0) {
this.words[0] = 0;
this.length = 1;
}
this.strip();
return this;
};
BN.prototype.ishrn = function ishrn(bits, hint, extended) {
// TODO(indutny): implement me
assert(!this.sign);
return this.iushrn(bits, hint, extended);
};
// Shift-left
BN.prototype.shln = function shln(bits) {
return this.clone().ishln(bits);
};
BN.prototype.ushln = function ushln(bits) {
return this.clone().iushln(bits);
};
// Shift-right
BN.prototype.shrn = function shrn(bits) {
return this.clone().ishrn(bits);
};
BN.prototype.ushrn = function ushrn(bits) {
return this.clone().iushrn(bits);
};
// Test if n bit is set
BN.prototype.testn = function testn(bit) {
assert(typeof bit === 'number' && bit >= 0);
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
return false;
}
// Check bit and return
var w = this.words[s];
return !!(w & q);
};
// Return only lowers bits of number (in-place)
BN.prototype.imaskn = function imaskn(bits) {
assert(typeof bits === 'number' && bits >= 0);
var r = bits % 26;
var s = (bits - r) / 26;
assert(!this.sign, 'imaskn works only with positive numbers');
if (r !== 0)
s++;
this.length = Math.min(s, this.length);
if (r !== 0) {
var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
this.words[this.length - 1] &= mask;
}
return this.strip();
};
// Return only lowers bits of number
BN.prototype.maskn = function maskn(bits) {
return this.clone().imaskn(bits);
};
// Add plain number `num` to `this`
BN.prototype.iaddn = function iaddn(num) {
assert(typeof num === 'number');
if (num < 0)
return this.isubn(-num);
// Possible sign change
if (this.sign) {
if (this.length === 1 && this.words[0] < num) {
this.words[0] = num - this.words[0];
this.sign = false;
return this;
}
this.sign = false;
this.isubn(num);
this.sign = true;
return this;
}
// Add without checks
return this._iaddn(num);
};
BN.prototype._iaddn = function _iaddn(num) {
this.words[0] += num;
// Carry
for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
this.words[i] -= 0x4000000;
if (i === this.length - 1)
this.words[i + 1] = 1;
else
this.words[i + 1]++;
}
this.length = Math.max(this.length, i + 1);
return this;
};
// Subtract plain number `num` from `this`
BN.prototype.isubn = function isubn(num) {
assert(typeof num === 'number');
if (num < 0)
return this.iaddn(-num);
if (this.sign) {
this.sign = false;
this.iaddn(num);
this.sign = true;
return this;
}
this.words[0] -= num;
// Carry
for (var i = 0; i < this.length && this.words[i] < 0; i++) {
this.words[i] += 0x4000000;
this.words[i + 1] -= 1;
}
return this.strip();
};
BN.prototype.addn = function addn(num) {
return this.clone().iaddn(num);
};
BN.prototype.subn = function subn(num) {
return this.clone().isubn(num);
};
BN.prototype.iabs = function iabs() {
this.sign = false;
return this;
};
BN.prototype.abs = function abs() {
return this.clone().iabs();
};
BN.prototype._ishlnsubmul = function _ishlnsubmul(num, mul, shift) {
// Bigger storage is needed
var len = num.length + shift;
var i;
if (this.words.length < len) {
var t = new Array(len);
for (var i = 0; i < this.length; i++)
t[i] = this.words[i];
this.words = t;
} else {
i = this.length;
}
// Zeroify rest
this.length = Math.max(this.length, len);
for (; i < this.length; i++)
this.words[i] = 0;
var carry = 0;
for (var i = 0; i < num.length; i++) {
var w = this.words[i + shift] + carry;
var right = num.words[i] * mul;
w -= right & 0x3ffffff;
carry = (w >> 26) - ((right / 0x4000000) | 0);
this.words[i + shift] = w & 0x3ffffff;
}
for (; i < this.length - shift; i++) {
var w = this.words[i + shift] + carry;
carry = w >> 26;
this.words[i + shift] = w & 0x3ffffff;
}
if (carry === 0)
return this.strip();
// Subtraction overflow
assert(carry === -1);
carry = 0;
for (var i = 0; i < this.length; i++) {
var w = -this.words[i] + carry;
carry = w >> 26;
this.words[i] = w & 0x3ffffff;
}
this.sign = true;
return this.strip();
};
BN.prototype._wordDiv = function _wordDiv(num, mode) {
var shift = this.length - num.length;
var a = this.clone();
var b = num;
// Normalize
var bhi = b.words[b.length - 1];
var bhiBits = this._countBits(bhi);
shift = 26 - bhiBits;
if (shift !== 0) {
b = b.ushln(shift);
a.iushln(shift);
bhi = b.words[b.length - 1];
}
// Initialize quotient
var m = a.length - b.length;
var q;
if (mode !== 'mod') {
q = new BN(null);
q.length = m + 1;
q.words = new Array(q.length);
for (var i = 0; i < q.length; i++)
q.words[i] = 0;
}
var diff = a.clone()._ishlnsubmul(b, 1, m);
if (!diff.sign) {
a = diff;
if (q)
q.words[m] = 1;
}
for (var j = m - 1; j >= 0; j--) {
var qj = a.words[b.length + j] * 0x4000000 + a.words[b.length + j - 1];
// NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
// (0x7ffffff)
qj = Math.min((qj / bhi) | 0, 0x3ffffff);
a._ishlnsubmul(b, qj, j);
while (a.sign) {
qj--;
a.sign = false;
a._ishlnsubmul(b, 1, j);
if (a.cmpn(0) !== 0)
a.sign = !a.sign;
}
if (q)
q.words[j] = qj;
}
if (q)
q.strip();
a.strip();
// Denormalize
if (mode !== 'div' && shift !== 0)
a.iushrn(shift);
return { div: q ? q : null, mod: a };
};
BN.prototype.divmod = function divmod(num, mode, positive) {
assert(num.cmpn(0) !== 0);
if (this.sign && !num.sign) {
var res = this.neg().divmod(num, mode);
var div;
var mod;
if (mode !== 'mod')
div = res.div.neg();
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.neg)
mod = mod.add(num);
}
return {
div: div,
mod: mod
};
} else if (!this.sign && num.sign) {
var res = this.divmod(num.neg(), mode);
var div;
if (mode !== 'mod')
div = res.div.neg();
return { div: div, mod: res.mod };
} else if (this.sign && num.sign) {
var res = this.neg().divmod(num.neg(), mode);
var mod;
if (mode !== 'div') {
mod = res.mod.neg();
if (positive && mod.neg)
mod = mod.isub(num);
}
return {
div: res.div,
mod: mod
};
}
// Both numbers are positive at this point
// Strip both numbers to approximate shift value
if (num.length > this.length || this.cmp(num) < 0)
return { div: new BN(0), mod: this };
// Very short reduction
if (num.length === 1) {
if (mode === 'div')
return { div: this.divn(num.words[0]), mod: null };
else if (mode === 'mod')
return { div: null, mod: new BN(this.modn(num.words[0])) };
return {
div: this.divn(num.words[0]),
mod: new BN(this.modn(num.words[0]))
};
}
return this._wordDiv(num, mode);
};
// Find `this` / `num`
BN.prototype.div = function div(num) {
return this.divmod(num, 'div', false).div;
};
// Find `this` % `num`
BN.prototype.mod = function mod(num) {
return this.divmod(num, 'mod', false).mod;
};
BN.prototype.umod = function umod(num) {
return this.divmod(num, 'mod', true).mod;
};
// Find Round(`this` / `num`)
BN.prototype.divRound = function divRound(num) {
var dm = this.divmod(num);
// Fast case - exact division
if (dm.mod.cmpn(0) === 0)
return dm.div;
var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod;
var half = num.ushrn(1);
var r2 = num.andln(1);
var cmp = mod.cmp(half);
// Round down
if (cmp < 0 || r2 === 1 && cmp === 0)
return dm.div;
// Round up
return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1);
};
BN.prototype.modn = function modn(num) {
assert(num <= 0x3ffffff);
var p = (1 << 26) % num;
var acc = 0;
for (var i = this.length - 1; i >= 0; i--)
acc = (p * acc + this.words[i]) % num;
return acc;
};
// In-place division by number
BN.prototype.idivn = function idivn(num) {
assert(num <= 0x3ffffff);
var carry = 0;
for (var i = this.length - 1; i >= 0; i--) {
var w = this.words[i] + carry * 0x4000000;
this.words[i] = (w / num) | 0;
carry = w % num;
}
return this.strip();
};
BN.prototype.divn = function divn(num) {
return this.clone().idivn(num);
};
BN.prototype.egcd = function egcd(p) {
assert(!p.sign);
assert(p.cmpn(0) !== 0);
var x = this;
var y = p.clone();
if (x.sign)
x = x.umod(p);
else
x = x.clone();
// A * x + B * y = x
var A = new BN(1);
var B = new BN(0);
// C * x + D * y = y
var C = new BN(0);
var D = new BN(1);
var g = 0;
while (x.isEven() && y.isEven()) {
x.iushrn(1);
y.iushrn(1);
++g;
}
var yp = y.clone();
var xp = x.clone();
while (x.cmpn(0) !== 0) {
while (x.isEven()) {
x.iushrn(1);
if (A.isEven() && B.isEven()) {
A.iushrn(1);
B.iushrn(1);
} else {
A.iadd(yp).iushrn(1);
B.isub(xp).iushrn(1);
}
}
while (y.isEven()) {
y.iushrn(1);
if (C.isEven() && D.isEven()) {
C.iushrn(1);
D.iushrn(1);
} else {
C.iadd(yp).iushrn(1);
D.isub(xp).iushrn(1);
}
}
if (x.cmp(y) >= 0) {
x.isub(y);
A.isub(C);
B.isub(D);
} else {
y.isub(x);
C.isub(A);
D.isub(B);
}
}
return {
a: C,
b: D,
gcd: y.iushln(g)
};
};
// This is reduced incarnation of the binary EEA
// above, designated to invert members of the
// _prime_ fields F(p) at a maximal speed
BN.prototype._invmp = function _invmp(p) {
assert(!p.sign);
assert(p.cmpn(0) !== 0);
var a = this;
var b = p.clone();
if (a.sign)
a = a.umod(p);
else
a = a.clone();
var x1 = new BN(1);
var x2 = new BN(0);
var delta = b.clone();
while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
while (a.isEven()) {
a.iushrn(1);
if (x1.isEven())
x1.iushrn(1);
else
x1.iadd(delta).iushrn(1);
}
while (b.isEven()) {
b.iushrn(1);
if (x2.isEven())
x2.iushrn(1);
else
x2.iadd(delta).iushrn(1);
}
if (a.cmp(b) >= 0) {
a.isub(b);
x1.isub(x2);
} else {
b.isub(a);
x2.isub(x1);
}
}
var res;
if (a.cmpn(1) === 0)
res = x1;
else
res = x2;
if (res.cmpn(0) < 0)
res.iadd(p);
return res;
};
BN.prototype.gcd = function gcd(num) {
if (this.cmpn(0) === 0)
return num.clone();
if (num.cmpn(0) === 0)
return this.clone();
var a = this.clone();
var b = num.clone();
a.sign = false;
b.sign = false;
// Remove common factor of two
for (var shift = 0; a.isEven() && b.isEven(); shift++) {
a.iushrn(1);
b.iushrn(1);
}
do {
while (a.isEven())
a.iushrn(1);
while (b.isEven())
b.iushrn(1);
var r = a.cmp(b);
if (r < 0) {
// Swap `a` and `b` to make `a` always bigger than `b`
var t = a;
a = b;
b = t;
} else if (r === 0 || b.cmpn(1) === 0) {
break;
}
a.isub(b);
} while (true);
return b.iushln(shift);
};
// Invert number in the field F(num)
BN.prototype.invm = function invm(num) {
return this.egcd(num).a.umod(num);
};
BN.prototype.isEven = function isEven() {
return (this.words[0] & 1) === 0;
};
BN.prototype.isOdd = function isOdd() {
return (this.words[0] & 1) === 1;
};
// And first word and num
BN.prototype.andln = function andln(num) {
return this.words[0] & num;
};
// Increment at the bit position in-line
BN.prototype.bincn = function bincn(bit) {
assert(typeof bit === 'number');
var r = bit % 26;
var s = (bit - r) / 26;
var q = 1 << r;
// Fast case: bit is much higher than all existing words
if (this.length <= s) {
for (var i = this.length; i < s + 1; i++)
this.words[i] = 0;
this.words[s] |= q;
this.length = s + 1;
return this;
}
// Add bit and propagate, if needed
var carry = q;
for (var i = s; carry !== 0 && i < this.length; i++) {
var w = this.words[i];
w += carry;
carry = w >>> 26;
w &= 0x3ffffff;
this.words[i] = w;
}
if (carry !== 0) {
this.words[i] = carry;
this.length++;
}
return this;
};
BN.prototype.cmpn = function cmpn(num) {
var sign = num < 0;
if (sign)
num = -num;
if (this.sign && !sign)
return -1;
else if (!this.sign && sign)
return 1;
num &= 0x3ffffff;
this.strip();
var res;
if (this.length > 1) {
res = 1;
} else {
var w = this.words[0];
res = w === num ? 0 : w < num ? -1 : 1;
}
if (this.sign)
res = -res;
return res;
};
// Compare two numbers and return:
// 1 - if `this` > `num`
// 0 - if `this` == `num`
// -1 - if `this` < `num`
BN.prototype.cmp = function cmp(num) {
if (this.sign && !num.sign)
return -1;
else if (!this.sign && num.sign)
return 1;
var res = this.ucmp(num);
if (this.sign)
return -res;
else
return res;
};
// Unsigned comparison
BN.prototype.ucmp = function ucmp(num) {
// At this point both numbers have the same sign
if (this.length > num.length)
return 1;
else if (this.length < num.length)
return -1;
var res = 0;
for (var i = this.length - 1; i >= 0; i--) {
var a = this.words[i];
var b = num.words[i];
if (a === b)
continue;
if (a < b)
res = -1;
else if (a > b)
res = 1;
break;
}
return res;
};
//
// A reduce context, could be using montgomery or something better, depending
// on the `m` itself.
//
BN.red = function red(num) {
return new Red(num);
};
BN.prototype.toRed = function toRed(ctx) {
assert(!this.red, 'Already a number in reduction context');
assert(!this.sign, 'red works only with positives');
return ctx.convertTo(this)._forceRed(ctx);
};
BN.prototype.fromRed = function fromRed() {
assert(this.red, 'fromRed works only with numbers in reduction context');
return this.red.convertFrom(this);
};
BN.prototype._forceRed = function _forceRed(ctx) {
this.red = ctx;
return this;
};
BN.prototype.forceRed = function forceRed(ctx) {
assert(!this.red, 'Already a number in reduction context');
return this._forceRed(ctx);
};
BN.prototype.redAdd = function redAdd(num) {
assert(this.red, 'redAdd works only with red numbers');
return this.red.add(this, num);
};
BN.prototype.redIAdd = function redIAdd(num) {
assert(this.red, 'redIAdd works only with red numbers');
return this.red.iadd(this, num);
};
BN.prototype.redSub = function redSub(num) {
assert(this.red, 'redSub works only with red numbers');
return this.red.sub(this, num);
};
BN.prototype.redISub = function redISub(num) {
assert(this.red, 'redISub works only with red numbers');
return this.red.isub(this, num);
};
BN.prototype.redShl = function redShl(num) {
assert(this.red, 'redShl works only with red numbers');
return this.red.ushl(this, num);
};
BN.prototype.redMul = function redMul(num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.mul(this, num);
};
BN.prototype.redIMul = function redIMul(num) {
assert(this.red, 'redMul works only with red numbers');
this.red._verify2(this, num);
return this.red.imul(this, num);
};
BN.prototype.redSqr = function redSqr() {
assert(this.red, 'redSqr works only with red numbers');
this.red._verify1(this);
return this.red.sqr(this);
};
BN.prototype.redISqr = function redISqr() {
assert(this.red, 'redISqr works only with red numbers');
this.red._verify1(this);
return this.red.isqr(this);
};
// Square root over p
BN.prototype.redSqrt = function redSqrt() {
assert(this.red, 'redSqrt works only with red numbers');
this.red._verify1(this);
return this.red.sqrt(this);
};
BN.prototype.redInvm = function redInvm() {
assert(this.red, 'redInvm works only with red numbers');
this.red._verify1(this);
return this.red.invm(this);
};
// Return negative clone of `this` % `red modulo`
BN.prototype.redNeg = function redNeg() {
assert(this.red, 'redNeg works only with red numbers');
this.red._verify1(this);
return this.red.neg(this);
};
BN.prototype.redPow = function redPow(num) {
assert(this.red && !num.red, 'redPow(normalNum)');
this.red._verify1(this);
return this.red.pow(this, num);
};
// Prime numbers with efficient reduction
var primes = {
k256: null,
p224: null,
p192: null,
p25519: null
};
// Pseudo-Mersenne prime
function MPrime(name, p) {
// P = 2 ^ N - K
this.name = name;
this.p = new BN(p, 16);
this.n = this.p.bitLength();
this.k = new BN(1).iushln(this.n).isub(this.p);
this.tmp = this._tmp();
}
MPrime.prototype._tmp = function _tmp() {
var tmp = new BN(null);
tmp.words = new Array(Math.ceil(this.n / 13));
return tmp;
};
MPrime.prototype.ireduce = function ireduce(num) {
// Assumes that `num` is less than `P^2`
// num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
var r = num;
var rlen;
do {
this.split(r, this.tmp);
r = this.imulK(r);
r = r.iadd(this.tmp);
rlen = r.bitLength();
} while (rlen > this.n);
var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
if (cmp === 0) {
r.words[0] = 0;
r.length = 1;
} else if (cmp > 0) {
r.isub(this.p);
} else {
r.strip();
}
return r;
};
MPrime.prototype.split = function split(input, out) {
input.iushrn(this.n, 0, out);
};
MPrime.prototype.imulK = function imulK(num) {
return num.imul(this.k);
};
function K256() {
MPrime.call(
this,
'k256',
'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
}
inherits(K256, MPrime);
K256.prototype.split = function split(input, output) {
// 256 = 9 * 26 + 22
var mask = 0x3fffff;
var outLen = Math.min(input.length, 9);
for (var i = 0; i < outLen; i++)
output.words[i] = input.words[i];
output.length = outLen;
if (input.length <= 9) {
input.words[0] = 0;
input.length = 1;
return;
}
// Shift by 9 limbs
var prev = input.words[9];
output.words[output.length++] = prev & mask;
for (var i = 10; i < input.length; i++) {
var next = input.words[i];
input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
prev = next;
}
input.words[i - 10] = prev >>> 22;
input.length -= 9;
};
K256.prototype.imulK = function imulK(num) {
// K = 0x1000003d1 = [ 0x40, 0x3d1 ]
num.words[num.length] = 0;
num.words[num.length + 1] = 0;
num.length += 2;
// bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
var hi;
var lo = 0;
for (var i = 0; i < num.length; i++) {
var w = num.words[i];
hi = w * 0x40;
lo += w * 0x3d1;
hi += (lo / 0x4000000) | 0;
lo &= 0x3ffffff;
num.words[i] = lo;
lo = hi;
}
// Fast length reduction
if (num.words[num.length - 1] === 0) {
num.length--;
if (num.words[num.length - 1] === 0)
num.length--;
}
return num;
};
function P224() {
MPrime.call(
this,
'p224',
'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
}
inherits(P224, MPrime);
function P192() {
MPrime.call(
this,
'p192',
'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
}
inherits(P192, MPrime);
function P25519() {
// 2 ^ 255 - 19
MPrime.call(
this,
'25519',
'7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
}
inherits(P25519, MPrime);
P25519.prototype.imulK = function imulK(num) {
// K = 0x13
var carry = 0;
for (var i = 0; i < num.length; i++) {
var hi = num.words[i] * 0x13 + carry;
var lo = hi & 0x3ffffff;
hi >>>= 26;
num.words[i] = lo;
carry = hi;
}
if (carry !== 0)
num.words[num.length++] = carry;
return num;
};
// Exported mostly for testing purposes, use plain name instead
BN._prime = function prime(name) {
// Cached version of prime
if (primes[name])
return primes[name];
var prime;
if (name === 'k256')
prime = new K256();
else if (name === 'p224')
prime = new P224();
else if (name === 'p192')
prime = new P192();
else if (name === 'p25519')
prime = new P25519();
else
throw new Error('Unknown prime ' + name);
primes[name] = prime;
return prime;
};
//
// Base reduction engine
//
function Red(m) {
if (typeof m === 'string') {
var prime = BN._prime(m);
this.m = prime.p;
this.prime = prime;
} else {
this.m = m;
this.prime = null;
}
}
Red.prototype._verify1 = function _verify1(a) {
assert(!a.sign, 'red works only with positives');
assert(a.red, 'red works only with red numbers');
};
Red.prototype._verify2 = function _verify2(a, b) {
assert(!a.sign && !b.sign, 'red works only with positives');
assert(a.red && a.red === b.red,
'red works only with red numbers');
};
Red.prototype.imod = function imod(a) {
if (this.prime)
return this.prime.ireduce(a)._forceRed(this);
return a.umod(this.m)._forceRed(this);
};
Red.prototype.neg = function neg(a) {
var r = a.clone();
r.sign = !r.sign;
return r.iadd(this.m)._forceRed(this);
};
Red.prototype.add = function add(a, b) {
this._verify2(a, b);
var res = a.add(b);
if (res.cmp(this.m) >= 0)
res.isub(this.m);
return res._forceRed(this);
};
Red.prototype.iadd = function iadd(a, b) {
this._verify2(a, b);
var res = a.iadd(b);
if (res.cmp(this.m) >= 0)
res.isub(this.m);
return res;
};
Red.prototype.sub = function sub(a, b) {
this._verify2(a, b);
var res = a.sub(b);
if (res.cmpn(0) < 0)
res.iadd(this.m);
return res._forceRed(this);
};
Red.prototype.isub = function isub(a, b) {
this._verify2(a, b);
var res = a.isub(b);
if (res.cmpn(0) < 0)
res.iadd(this.m);
return res;
};
Red.prototype.shl = function shl(a, num) {
this._verify1(a);
return this.imod(a.ushln(num));
};
Red.prototype.imul = function imul(a, b) {
this._verify2(a, b);
return this.imod(a.imul(b));
};
Red.prototype.mul = function mul(a, b) {
this._verify2(a, b);
return this.imod(a.mul(b));
};
Red.prototype.isqr = function isqr(a) {
return this.imul(a, a);
};
Red.prototype.sqr = function sqr(a) {
return this.mul(a, a);
};
Red.prototype.sqrt = function sqrt(a) {
if (a.cmpn(0) === 0)
return a.clone();
var mod3 = this.m.andln(3);
assert(mod3 % 2 === 1);
// Fast case
if (mod3 === 3) {
var pow = this.m.add(new BN(1)).iushrn(2);
var r = this.pow(a, pow);
return r;
}
// Tonelli-Shanks algorithm (Totally unoptimized and slow)
//
// Find Q and S, that Q * 2 ^ S = (P - 1)
var q = this.m.subn(1);
var s = 0;
while (q.cmpn(0) !== 0 && q.andln(1) === 0) {
s++;
q.iushrn(1);
}
assert(q.cmpn(0) !== 0);
var one = new BN(1).toRed(this);
var nOne = one.redNeg();
// Find quadratic non-residue
// NOTE: Max is such because of generalized Riemann hypothesis.
var lpow = this.m.subn(1).iushrn(1);
var z = this.m.bitLength();
z = new BN(2 * z * z).toRed(this);
while (this.pow(z, lpow).cmp(nOne) !== 0)
z.redIAdd(nOne);
var c = this.pow(z, q);
var r = this.pow(a, q.addn(1).iushrn(1));
var t = this.pow(a, q);
var m = s;
while (t.cmp(one) !== 0) {
var tmp = t;
for (var i = 0; tmp.cmp(one) !== 0; i++)
tmp = tmp.redSqr();
assert(i < m);
var b = this.pow(c, new BN(1).iushln(m - i - 1));
r = r.redMul(b);
c = b.redSqr();
t = t.redMul(c);
m = i;
}
return r;
};
Red.prototype.invm = function invm(a) {
var inv = a._invmp(this.m);
if (inv.sign) {
inv.sign = false;
return this.imod(inv).redNeg();
} else {
return this.imod(inv);
}
};
Red.prototype.pow = function pow(a, num) {
var w = toBitArray(num);
if (w.length === 0)
return new BN(1);
// Skip leading zeroes
var res = a;
for (var i = 0; i < w.length; i++, res = this.sqr(res))
if (w[i] !== 0)
break;
if (++i < w.length) {
for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) {
if (w[i] === 0)
continue;
res = this.mul(res, q);
}
}
return res;
};
Red.prototype.convertTo = function convertTo(num) {
var r = num.umod(this.m);
if (r === num)
return r.clone();
else
return r;
};
Red.prototype.convertFrom = function convertFrom(num) {
var res = num.clone();
res.red = null;
return res;
};
//
// Montgomery method engine
//
BN.mont = function mont(num) {
return new Mont(num);
};
function Mont(m) {
Red.call(this, m);
this.shift = this.m.bitLength();
if (this.shift % 26 !== 0)
this.shift += 26 - (this.shift % 26);
this.r = new BN(1).iushln(this.shift);
this.r2 = this.imod(this.r.sqr());
this.rinv = this.r._invmp(this.m);
this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
this.minv = this.minv.umod(this.r);
this.minv = this.r.sub(this.minv);
}
inherits(Mont, Red);
Mont.prototype.convertTo = function convertTo(num) {
return this.imod(num.ushln(this.shift));
};
Mont.prototype.convertFrom = function convertFrom(num) {
var r = this.imod(num.mul(this.rinv));
r.red = null;
return r;
};
Mont.prototype.imul = function imul(a, b) {
if (a.cmpn(0) === 0 || b.cmpn(0) === 0) {
a.words[0] = 0;
a.length = 1;
return a;
}
var t = a.imul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0)
res = u.isub(this.m);
else if (u.cmpn(0) < 0)
res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.mul = function mul(a, b) {
if (a.cmpn(0) === 0 || b.cmpn(0) === 0)
return new BN(0)._forceRed(this);
var t = a.mul(b);
var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
var u = t.isub(c).iushrn(this.shift);
var res = u;
if (u.cmp(this.m) >= 0)
res = u.isub(this.m);
else if (u.cmpn(0) < 0)
res = u.iadd(this.m);
return res._forceRed(this);
};
Mont.prototype.invm = function invm(a) {
// (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
var res = this.imod(a._invmp(this.m).mul(this.r2));
return res._forceRed(this);
};
})(typeof module === 'undefined' || module, this);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(40)(module)))
/***/ }),
/* 65 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const assert = __webpack_require__(2);
function mergeIntervals(intervals) {
const stack = [[-Infinity, -Infinity]];
_.sortBy(intervals, x => x[0]).forEach(interval => {
const lastInterval = stack.pop();
if (interval[0] <= lastInterval[1] + 1) {
stack.push([lastInterval[0], Math.max(interval[1], lastInterval[1])]);
}
else {
stack.push(lastInterval);
stack.push(interval);
}
});
return stack.slice(1);
}
class RangeSet {
constructor() {
this.reset();
}
reset() {
this.ranges = [];
}
serialize() {
return this.ranges.map(range => range[0].toString() + '-' + range[1].toString()).join(',');
}
addRange(start, end) {
assert(start <= end, 'invalid range');
this.ranges = mergeIntervals(this.ranges.concat([[start, end]]));
}
addValue(value) {
this.addRange(value, value);
}
parseAndAddRanges(rangesString) {
const rangeStrings = rangesString.split(',');
_.forEach(rangeStrings, rangeString => {
const range = rangeString.split('-').map(Number);
this.addRange(range[0], range.length === 1 ? range[0] : range[1]);
});
}
containsRange(start, end) {
return _.some(this.ranges, range => range[0] <= start && range[1] >= end);
}
containsValue(value) {
return this.containsRange(value, value);
}
}
exports.default = RangeSet;
/***/ }),
/* 66 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var hasOwn = Object.prototype.hasOwnProperty;
var toStr = Object.prototype.toString;
var isArray = function isArray(arr) {
if (typeof Array.isArray === 'function') {
return Array.isArray(arr);
}
return toStr.call(arr) === '[object Array]';
};
var isPlainObject = function isPlainObject(obj) {
if (!obj || toStr.call(obj) !== '[object Object]') {
return false;
}
var hasOwnConstructor = hasOwn.call(obj, 'constructor');
var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
// Not own constructor property must be Object
if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for (key in obj) { /**/ }
return typeof key === 'undefined' || hasOwn.call(obj, key);
};
module.exports = function extend() {
var options, name, src, copy, copyIsArray, clone;
var target = arguments[0];
var i = 1;
var length = arguments.length;
var deep = false;
// Handle a deep copy situation
if (typeof target === 'boolean') {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
target = {};
}
for (; i < length; ++i) {
options = arguments[i];
// Only deal with non-null/undefined values
if (options != null) {
// Extend the base object
for (name in options) {
src = target[name];
copy = options[name];
// Prevent never-ending loop
if (target !== copy) {
// Recurse if we're merging plain objects or arrays
if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
if (copyIsArray) {
copyIsArray = false;
clone = src && isArray(src) ? src : [];
} else {
clone = src && isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[name] = extend(deep, clone, copy);
// Don't bring in undefined values
} else if (typeof copy !== 'undefined') {
target[name] = copy;
}
}
}
}
}
// Return the modified object
return target;
};
/***/ }),
/* 67 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var ClientRequest = __webpack_require__(253)
var IncomingMessage = __webpack_require__(69)
var extend = __webpack_require__(260)
var statusCodes = __webpack_require__(261)
var url = __webpack_require__(22)
var http = exports
http.request = function (opts, cb) {
if (typeof opts === 'string')
opts = url.parse(opts)
else
opts = extend(opts)
// Normally, the page is loaded from http or https, so not specifying a protocol
// will result in a (valid) protocol-relative url. However, this won't work if
// the protocol is something else, like 'file:'
var defaultProtocol = global.location.protocol.search(/^https?:$/) === -1 ? 'http:' : ''
var protocol = opts.protocol || defaultProtocol
var host = opts.hostname || opts.host
var port = opts.port
var path = opts.path || '/'
// Necessary for IPv6 addresses
if (host && host.indexOf(':') !== -1)
host = '[' + host + ']'
// This may be a relative url. The browser should always be able to interpret it correctly.
opts.url = (host ? (protocol + '//' + host) : '') + (port ? ':' + port : '') + path
opts.method = (opts.method || 'GET').toUpperCase()
opts.headers = opts.headers || {}
// Also valid opts.auth, opts.mode
var req = new ClientRequest(opts)
if (cb)
req.on('response', cb)
return req
}
http.get = function get (opts, cb) {
var req = http.request(opts, cb)
req.end()
return req
}
http.ClientRequest = ClientRequest
http.IncomingMessage = IncomingMessage
http.Agent = function () {}
http.Agent.defaultMaxSockets = 4
http.STATUS_CODES = statusCodes
http.METHODS = [
'CHECKOUT',
'CONNECT',
'COPY',
'DELETE',
'GET',
'HEAD',
'LOCK',
'M-SEARCH',
'MERGE',
'MKACTIVITY',
'MKCOL',
'MOVE',
'NOTIFY',
'OPTIONS',
'PATCH',
'POST',
'PROPFIND',
'PROPPATCH',
'PURGE',
'PUT',
'REPORT',
'SEARCH',
'SUBSCRIBE',
'TRACE',
'UNLOCK',
'UNSUBSCRIBE'
]
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ }),
/* 68 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {exports.fetch = isFunction(global.fetch) && isFunction(global.ReadableStream)
exports.writableStream = isFunction(global.WritableStream)
exports.abortController = isFunction(global.AbortController)
exports.blobConstructor = false
try {
new Blob([new ArrayBuffer(1)])
exports.blobConstructor = true
} catch (e) {}
// The xhr request to example.com may violate some restrictive CSP configurations,
// so if we're running in a browser that supports `fetch`, avoid calling getXHR()
// and assume support for certain features below.
var xhr
function getXHR () {
// Cache the xhr value
if (xhr !== undefined) return xhr
if (global.XMLHttpRequest) {
xhr = new global.XMLHttpRequest()
// If XDomainRequest is available (ie only, where xhr might not work
// cross domain), use the page location. Otherwise use example.com
// Note: this doesn't actually make an http request.
try {
xhr.open('GET', global.XDomainRequest ? '/' : 'https://example.com')
} catch(e) {
xhr = null
}
} else {
// Service workers don't have XHR
xhr = null
}
return xhr
}
function checkTypeSupport (type) {
var xhr = getXHR()
if (!xhr) return false
try {
xhr.responseType = type
return xhr.responseType === type
} catch (e) {}
return false
}
// For some strange reason, Safari 7.0 reports typeof global.ArrayBuffer === 'object'.
// Safari 7.1 appears to have fixed this bug.
var haveArrayBuffer = typeof global.ArrayBuffer !== 'undefined'
var haveSlice = haveArrayBuffer && isFunction(global.ArrayBuffer.prototype.slice)
// If fetch is supported, then arraybuffer will be supported too. Skip calling
// checkTypeSupport(), since that calls getXHR().
exports.arraybuffer = exports.fetch || (haveArrayBuffer && checkTypeSupport('arraybuffer'))
// These next two tests unavoidably show warnings in Chrome. Since fetch will always
// be used if it's available, just return false for these to avoid the warnings.
exports.msstream = !exports.fetch && haveSlice && checkTypeSupport('ms-stream')
exports.mozchunkedarraybuffer = !exports.fetch && haveArrayBuffer &&
checkTypeSupport('moz-chunked-arraybuffer')
// If fetch is supported, then overrideMimeType will be supported too. Skip calling
// getXHR().
exports.overrideMimeType = exports.fetch || (getXHR() ? isFunction(getXHR().overrideMimeType) : false)
exports.vbArray = isFunction(global.VBArray)
function isFunction (value) {
return typeof value === 'function'
}
xhr = null // Help gc
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ }),
/* 69 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(process, Buffer, global) {var capability = __webpack_require__(68)
var inherits = __webpack_require__(3)
var stream = __webpack_require__(70)
var rStates = exports.readyStates = {
UNSENT: 0,
OPENED: 1,
HEADERS_RECEIVED: 2,
LOADING: 3,
DONE: 4
}
var IncomingMessage = exports.IncomingMessage = function (xhr, response, mode) {
var self = this
stream.Readable.call(self)
self._mode = mode
self.headers = {}
self.rawHeaders = []
self.trailers = {}
self.rawTrailers = []
// Fake the 'close' event, but only once 'end' fires
self.on('end', function () {
// The nextTick is necessary to prevent the 'request' module from causing an infinite loop
process.nextTick(function () {
self.emit('close')
})
})
if (mode === 'fetch') {
self._fetchResponse = response
self.url = response.url
self.statusCode = response.status
self.statusMessage = response.statusText
response.headers.forEach(function (header, key){
self.headers[key.toLowerCase()] = header
self.rawHeaders.push(key, header)
})
if (capability.writableStream) {
var writable = new WritableStream({
write: function (chunk) {
return new Promise(function (resolve, reject) {
if (self._destroyed) {
return
} else if(self.push(new Buffer(chunk))) {
resolve()
} else {
self._resumeFetch = resolve
}
})
},
close: function () {
if (!self._destroyed)
self.push(null)
},
abort: function (err) {
if (!self._destroyed)
self.emit('error', err)
}
})
try {
response.body.pipeTo(writable)
return
} catch (e) {} // pipeTo method isn't defined. Can't find a better way to feature test this
}
// fallback for when writableStream or pipeTo aren't available
var reader = response.body.getReader()
function read () {
reader.read().then(function (result) {
if (self._destroyed)
return
if (result.done) {
self.push(null)
return
}
self.push(new Buffer(result.value))
read()
}).catch(function(err) {
if (!self._destroyed)
self.emit('error', err)
})
}
read()
} else {
self._xhr = xhr
self._pos = 0
self.url = xhr.responseURL
self.statusCode = xhr.status
self.statusMessage = xhr.statusText
var headers = xhr.getAllResponseHeaders().split(/\r?\n/)
headers.forEach(function (header) {
var matches = header.match(/^([^:]+):\s*(.*)/)
if (matches) {
var key = matches[1].toLowerCase()
if (key === 'set-cookie') {
if (self.headers[key] === undefined) {
self.headers[key] = []
}
self.headers[key].push(matches[2])
} else if (self.headers[key] !== undefined) {
self.headers[key] += ', ' + matches[2]
} else {
self.headers[key] = matches[2]
}
self.rawHeaders.push(matches[1], matches[2])
}
})
self._charset = 'x-user-defined'
if (!capability.overrideMimeType) {
var mimeType = self.rawHeaders['mime-type']
if (mimeType) {
var charsetMatch = mimeType.match(/;\s*charset=([^;])(;|$)/)
if (charsetMatch) {
self._charset = charsetMatch[1].toLowerCase()
}
}
if (!self._charset)
self._charset = 'utf-8' // best guess
}
}
}
inherits(IncomingMessage, stream.Readable)
IncomingMessage.prototype._read = function () {
var self = this
var resolve = self._resumeFetch
if (resolve) {
self._resumeFetch = null
resolve()
}
}
IncomingMessage.prototype._onXHRProgress = function () {
var self = this
var xhr = self._xhr
var response = null
switch (self._mode) {
case 'text:vbarray': // For IE9
if (xhr.readyState !== rStates.DONE)
break
try {
// This fails in IE8
response = new global.VBArray(xhr.responseBody).toArray()
} catch (e) {}
if (response !== null) {
self.push(new Buffer(response))
break
}
// Falls through in IE8
case 'text':
try { // This will fail when readyState = 3 in IE9. Switch mode and wait for readyState = 4
response = xhr.responseText
} catch (e) {
self._mode = 'text:vbarray'
break
}
if (response.length > self._pos) {
var newData = response.substr(self._pos)
if (self._charset === 'x-user-defined') {
var buffer = new Buffer(newData.length)
for (var i = 0; i < newData.length; i++)
buffer[i] = newData.charCodeAt(i) & 0xff
self.push(buffer)
} else {
self.push(newData, self._charset)
}
self._pos = response.length
}
break
case 'arraybuffer':
if (xhr.readyState !== rStates.DONE || !xhr.response)
break
response = xhr.response
self.push(new Buffer(new Uint8Array(response)))
break
case 'moz-chunked-arraybuffer': // take whole
response = xhr.response
if (xhr.readyState !== rStates.LOADING || !response)
break
self.push(new Buffer(new Uint8Array(response)))
break
case 'ms-stream':
response = xhr.response
if (xhr.readyState !== rStates.LOADING)
break
var reader = new global.MSStreamReader()
reader.onprogress = function () {
if (reader.result.byteLength > self._pos) {
self.push(new Buffer(new Uint8Array(reader.result.slice(self._pos))))
self._pos = reader.result.byteLength
}
}
reader.onload = function () {
self.push(null)
}
// reader.onerror = ??? // TODO: this
reader.readAsArrayBuffer(response)
break
}
// The ms-stream case handles end separately in reader.onload()
if (self._xhr.readyState === rStates.DONE && self._mode !== 'ms-stream') {
self.push(null)
}
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9), __webpack_require__(5).Buffer, __webpack_require__(7)))
/***/ }),
/* 70 */
/***/ (function(module, exports, __webpack_require__) {
exports = module.exports = __webpack_require__(71);
exports.Stream = exports;
exports.Readable = exports;
exports.Writable = __webpack_require__(74);
exports.Duplex = __webpack_require__(27);
exports.Transform = __webpack_require__(77);
exports.PassThrough = __webpack_require__(258);
/***/ }),
/* 71 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = __webpack_require__(254);
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = __webpack_require__(17).EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = __webpack_require__(72);
/*</replacement>*/
// TODO(bmeurer): Change this back to const once hole checks are
// properly optimized away early in Ignition+TurboFan.
/*<replacement>*/
var Buffer = __webpack_require__(8).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
/*<replacement>*/
var debugUtil = __webpack_require__(255);
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = __webpack_require__(256);
var destroyImpl = __webpack_require__(73);
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') {
return emitter.prependListener(event, fn);
} else {
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
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]];
}
}
function ReadableState(options, stream) {
Duplex = Duplex || __webpack_require__(27);
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = __webpack_require__(37).StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || __webpack_require__(27);
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = __webpack_require__(37).StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
processNextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
processNextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
processNextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) self.push(chunk);
}
self.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
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);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
processNextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(9)))
/***/ }),
/* 72 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(17).EventEmitter;
/***/ }),
/* 73 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
processNextTick(emitErrorNT, this, err);
}
return;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
processNextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
/***/ }),
/* 74 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// A bit simpler than readable streams.
// Implement an async ._write(chunk, encoding, cb), and it'll handle all
// the drain event emission and buffering.
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
module.exports = Writable;
/* <replacement> */
function WriteReq(chunk, encoding, cb) {
this.chunk = chunk;
this.encoding = encoding;
this.callback = cb;
this.next = null;
}
// It seems a linked list but it is not
// there will be only 2 of these for each stream
function CorkedRequest(state) {
var _this = this;
this.next = null;
this.entry = null;
this.finish = function () {
onCorkedFinish(_this, state);
};
}
/* </replacement> */
/*<replacement>*/
var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Writable.WritableState = WritableState;
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
/*<replacement>*/
var internalUtil = {
deprecate: __webpack_require__(76)
};
/*</replacement>*/
/*<replacement>*/
var Stream = __webpack_require__(72);
/*</replacement>*/
/*<replacement>*/
var Buffer = __webpack_require__(8).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
var destroyImpl = __webpack_require__(73);
util.inherits(Writable, Stream);
function nop() {}
function WritableState(options, stream) {
Duplex = Duplex || __webpack_require__(27);
options = options || {};
// object stream flag to indicate whether or not this stream
// contains buffers or objects.
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
// the point at which write() starts returning false
// Note: 0 is a valid value, means that we always return false if
// the entire buffer is not flushed immediately on write()
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// if _final has been called
this.finalCalled = false;
// drain event flag.
this.needDrain = false;
// at the start of calling end()
this.ending = false;
// when end() has been called, and returned
this.ended = false;
// when 'finish' is emitted
this.finished = false;
// has it been destroyed
this.destroyed = false;
// should we decode strings into buffers before passing to _write?
// this is here so that some node-core streams can optimize string
// handling at a lower level.
var noDecode = options.decodeStrings === false;
this.decodeStrings = !noDecode;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// not an actual buffer we keep track of, but a measurement
// of how much we're waiting to get pushed to some underlying
// socket or file.
this.length = 0;
// a flag to see when we're in the middle of a write.
this.writing = false;
// when true all writes will be buffered until .uncork() call
this.corked = 0;
// a flag to be able to tell if the onwrite cb is called immediately,
// or on a later tick. We set this to true at first, because any
// actions that shouldn't happen until "later" should generally also
// not happen before the first write call.
this.sync = true;
// a flag to know if we're processing previously buffered items, which
// may call the _write() callback in the same tick, so that we don't
// end up in an overlapped onwrite situation.
this.bufferProcessing = false;
// the callback that's passed to _write(chunk,cb)
this.onwrite = function (er) {
onwrite(stream, er);
};
// the callback that the user supplies to write(chunk,encoding,cb)
this.writecb = null;
// the amount that is being written when _write is called.
this.writelen = 0;
this.bufferedRequest = null;
this.lastBufferedRequest = null;
// number of pending user-supplied write callbacks
// this must be 0 before 'finish' can be emitted
this.pendingcb = 0;
// emit prefinish if the only thing we're waiting for is _write cbs
// This is relevant for synchronous Transform streams
this.prefinished = false;
// True if the error was already emitted and should not be thrown again
this.errorEmitted = false;
// count buffered requests
this.bufferedRequestCount = 0;
// allocate the first CorkedRequest, there is always
// one allocated and free to use, and we maintain at most two
this.corkedRequestsFree = new CorkedRequest(this);
}
WritableState.prototype.getBuffer = function getBuffer() {
var current = this.bufferedRequest;
var out = [];
while (current) {
out.push(current);
current = current.next;
}
return out;
};
(function () {
try {
Object.defineProperty(WritableState.prototype, 'buffer', {
get: internalUtil.deprecate(function () {
return this.getBuffer();
}, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
});
} catch (_) {}
})();
// Test _writableState for inheritance to account for Duplex streams,
// whose prototype chain only points to Readable.
var realHasInstance;
if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
realHasInstance = Function.prototype[Symbol.hasInstance];
Object.defineProperty(Writable, Symbol.hasInstance, {
value: function (object) {
if (realHasInstance.call(this, object)) return true;
return object && object._writableState instanceof WritableState;
}
});
} else {
realHasInstance = function (object) {
return object instanceof this;
};
}
function Writable(options) {
Duplex = Duplex || __webpack_require__(27);
// Writable ctor is applied to Duplexes, too.
// `realHasInstance` is necessary because using plain `instanceof`
// would return false, as no `_writableState` property is attached.
// Trying to use the custom `instanceof` for Writable here will also break the
// Node.js LazyTransform implementation, which has a non-trivial getter for
// `_writableState` that would lead to infinite recursion.
if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
return new Writable(options);
}
this._writableState = new WritableState(options, this);
// legacy.
this.writable = true;
if (options) {
if (typeof options.write === 'function') this._write = options.write;
if (typeof options.writev === 'function') this._writev = options.writev;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
if (typeof options.final === 'function') this._final = options.final;
}
Stream.call(this);
}
// Otherwise people can pipe Writable streams, which is just wrong.
Writable.prototype.pipe = function () {
this.emit('error', new Error('Cannot pipe, not readable'));
};
function writeAfterEnd(stream, cb) {
var er = new Error('write after end');
// TODO: defer error events consistently everywhere, not just the cb
stream.emit('error', er);
processNextTick(cb, er);
}
// Checks that a user-supplied chunk is valid, especially for the particular
// mode the stream is in. Currently this means that `null` is never accepted
// and undefined/non-string values are only allowed in object mode.
function validChunk(stream, state, chunk, cb) {
var valid = true;
var er = false;
if (chunk === null) {
er = new TypeError('May not write null values to stream');
} else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
if (er) {
stream.emit('error', er);
processNextTick(cb, er);
valid = false;
}
return valid;
}
Writable.prototype.write = function (chunk, encoding, cb) {
var state = this._writableState;
var ret = false;
var isBuf = _isUint8Array(chunk) && !state.objectMode;
if (isBuf && !Buffer.isBuffer(chunk)) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
if (typeof cb !== 'function') cb = nop;
if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
state.pendingcb++;
ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
}
return ret;
};
Writable.prototype.cork = function () {
var state = this._writableState;
state.corked++;
};
Writable.prototype.uncork = function () {
var state = this._writableState;
if (state.corked) {
state.corked--;
if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
}
};
Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
// node::ParseEncoding() requires lower case.
if (typeof encoding === 'string') encoding = encoding.toLowerCase();
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);
this._writableState.defaultEncoding = encoding;
return this;
};
function decodeChunk(state, chunk, encoding) {
if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
chunk = Buffer.from(chunk, encoding);
}
return chunk;
}
// if we're already writing something, then just put this
// in the queue, and wait our turn. Otherwise, call _write
// If we return false, then we need a drain event, so set that flag.
function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
if (!isBuf) {
var newChunk = decodeChunk(state, chunk, encoding);
if (chunk !== newChunk) {
isBuf = true;
encoding = 'buffer';
chunk = newChunk;
}
}
var len = state.objectMode ? 1 : chunk.length;
state.length += len;
var ret = state.length < state.highWaterMark;
// we must ensure that previous needDrain will not be reset to false.
if (!ret) state.needDrain = true;
if (state.writing || state.corked) {
var last = state.lastBufferedRequest;
state.lastBufferedRequest = {
chunk: chunk,
encoding: encoding,
isBuf: isBuf,
callback: cb,
next: null
};
if (last) {
last.next = state.lastBufferedRequest;
} else {
state.bufferedRequest = state.lastBufferedRequest;
}
state.bufferedRequestCount += 1;
} else {
doWrite(stream, state, false, len, chunk, encoding, cb);
}
return ret;
}
function doWrite(stream, state, writev, len, chunk, encoding, cb) {
state.writelen = len;
state.writecb = cb;
state.writing = true;
state.sync = true;
if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
state.sync = false;
}
function onwriteError(stream, state, sync, er, cb) {
--state.pendingcb;
if (sync) {
// defer the callback if we are being called synchronously
// to avoid piling up things on the stack
processNextTick(cb, er);
// this can emit finish, and it will always happen
// after error
processNextTick(finishMaybe, stream, state);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
} else {
// the caller expect this to happen before if
// it is async
cb(er);
stream._writableState.errorEmitted = true;
stream.emit('error', er);
// this can emit finish, but finish must
// always follow error
finishMaybe(stream, state);
}
}
function onwriteStateUpdate(state) {
state.writing = false;
state.writecb = null;
state.length -= state.writelen;
state.writelen = 0;
}
function onwrite(stream, er) {
var state = stream._writableState;
var sync = state.sync;
var cb = state.writecb;
onwriteStateUpdate(state);
if (er) onwriteError(stream, state, sync, er, cb);else {
// Check if we're actually ready to finish, but don't emit yet
var finished = needFinish(state);
if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
clearBuffer(stream, state);
}
if (sync) {
/*<replacement>*/
asyncWrite(afterWrite, stream, state, finished, cb);
/*</replacement>*/
} else {
afterWrite(stream, state, finished, cb);
}
}
}
function afterWrite(stream, state, finished, cb) {
if (!finished) onwriteDrain(stream, state);
state.pendingcb--;
cb();
finishMaybe(stream, state);
}
// Must force callback to be called on nextTick, so that we don't
// emit 'drain' before the write() consumer gets the 'false' return
// value, and has a chance to attach a 'drain' listener.
function onwriteDrain(stream, state) {
if (state.length === 0 && state.needDrain) {
state.needDrain = false;
stream.emit('drain');
}
}
// if there's something in the buffer waiting, then process it
function clearBuffer(stream, state) {
state.bufferProcessing = true;
var entry = state.bufferedRequest;
if (stream._writev && entry && entry.next) {
// Fast case, write everything using _writev()
var l = state.bufferedRequestCount;
var buffer = new Array(l);
var holder = state.corkedRequestsFree;
holder.entry = entry;
var count = 0;
var allBuffers = true;
while (entry) {
buffer[count] = entry;
if (!entry.isBuf) allBuffers = false;
entry = entry.next;
count += 1;
}
buffer.allBuffers = allBuffers;
doWrite(stream, state, true, state.length, buffer, '', holder.finish);
// doWrite is almost always async, defer these to save a bit of time
// as the hot path ends with doWrite
state.pendingcb++;
state.lastBufferedRequest = null;
if (holder.next) {
state.corkedRequestsFree = holder.next;
holder.next = null;
} else {
state.corkedRequestsFree = new CorkedRequest(state);
}
} else {
// Slow case, write chunks one-by-one
while (entry) {
var chunk = entry.chunk;
var encoding = entry.encoding;
var cb = entry.callback;
var len = state.objectMode ? 1 : chunk.length;
doWrite(stream, state, false, len, chunk, encoding, cb);
entry = entry.next;
// if we didn't call the onwrite immediately, then
// it means that we need to wait until it does.
// also, that means that the chunk and cb are currently
// being processed, so move the buffer counter past them.
if (state.writing) {
break;
}
}
if (entry === null) state.lastBufferedRequest = null;
}
state.bufferedRequestCount = 0;
state.bufferedRequest = entry;
state.bufferProcessing = false;
}
Writable.prototype._write = function (chunk, encoding, cb) {
cb(new Error('_write() is not implemented'));
};
Writable.prototype._writev = null;
Writable.prototype.end = function (chunk, encoding, cb) {
var state = this._writableState;
if (typeof chunk === 'function') {
cb = chunk;
chunk = null;
encoding = null;
} else if (typeof encoding === 'function') {
cb = encoding;
encoding = null;
}
if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
// .end() fully uncorks
if (state.corked) {
state.corked = 1;
this.uncork();
}
// ignore unnecessary end() calls.
if (!state.ending && !state.finished) endWritable(this, state, cb);
};
function needFinish(state) {
return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
}
function callFinal(stream, state) {
stream._final(function (err) {
state.pendingcb--;
if (err) {
stream.emit('error', err);
}
state.prefinished = true;
stream.emit('prefinish');
finishMaybe(stream, state);
});
}
function prefinish(stream, state) {
if (!state.prefinished && !state.finalCalled) {
if (typeof stream._final === 'function') {
state.pendingcb++;
state.finalCalled = true;
processNextTick(callFinal, stream, state);
} else {
state.prefinished = true;
stream.emit('prefinish');
}
}
}
function finishMaybe(stream, state) {
var need = needFinish(state);
if (need) {
prefinish(stream, state);
if (state.pendingcb === 0) {
state.finished = true;
stream.emit('finish');
}
}
return need;
}
function endWritable(stream, state, cb) {
state.ending = true;
finishMaybe(stream, state);
if (cb) {
if (state.finished) processNextTick(cb);else stream.once('finish', cb);
}
state.ended = true;
stream.writable = false;
}
function onCorkedFinish(corkReq, state, err) {
var entry = corkReq.entry;
corkReq.entry = null;
while (entry) {
var cb = entry.callback;
state.pendingcb--;
cb(err);
entry = entry.next;
}
if (state.corkedRequestsFree) {
state.corkedRequestsFree.next = corkReq;
} else {
state.corkedRequestsFree = corkReq;
}
}
Object.defineProperty(Writable.prototype, 'destroyed', {
get: function () {
if (this._writableState === undefined) {
return false;
}
return this._writableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._writableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._writableState.destroyed = value;
}
});
Writable.prototype.destroy = destroyImpl.destroy;
Writable.prototype._undestroy = destroyImpl.undestroy;
Writable.prototype._destroy = function (err, cb) {
this.end();
cb(err);
};
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(9), __webpack_require__(75).setImmediate, __webpack_require__(7)))
/***/ }),
/* 75 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {var apply = Function.prototype.apply;
// DOM APIs, for completeness
exports.setTimeout = function() {
return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
};
exports.setInterval = function() {
return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
};
exports.clearTimeout =
exports.clearInterval = function(timeout) {
if (timeout) {
timeout.close();
}
};
function Timeout(id, clearFn) {
this._id = id;
this._clearFn = clearFn;
}
Timeout.prototype.unref = Timeout.prototype.ref = function() {};
Timeout.prototype.close = function() {
this._clearFn.call(window, this._id);
};
// Does not start the time, just sets up the members needed.
exports.enroll = function(item, msecs) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = msecs;
};
exports.unenroll = function(item) {
clearTimeout(item._idleTimeoutId);
item._idleTimeout = -1;
};
exports._unrefActive = exports.active = function(item) {
clearTimeout(item._idleTimeoutId);
var msecs = item._idleTimeout;
if (msecs >= 0) {
item._idleTimeoutId = setTimeout(function onTimeout() {
if (item._onTimeout)
item._onTimeout();
}, msecs);
}
};
// setimmediate attaches itself to the global object
__webpack_require__(257);
// On some exotic environments, it's not clear which object `setimmeidate` was
// able to install onto. Search each possibility in the same order as the
// `setimmediate` library.
exports.setImmediate = (typeof self !== "undefined" && self.setImmediate) ||
(typeof global !== "undefined" && global.setImmediate) ||
(this && this.setImmediate);
exports.clearImmediate = (typeof self !== "undefined" && self.clearImmediate) ||
(typeof global !== "undefined" && global.clearImmediate) ||
(this && this.clearImmediate);
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ }),
/* 76 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(global) {
/**
* Module exports.
*/
module.exports = deprecate;
/**
* Mark that a method should not be used.
* Returns a modified function which warns once by default.
*
* If `localStorage.noDeprecation = true` is set, then it is a no-op.
*
* If `localStorage.throwDeprecation = true` is set, then deprecated functions
* will throw an Error when invoked.
*
* If `localStorage.traceDeprecation = true` is set, then deprecated functions
* will invoke `console.trace()` instead of `console.error()`.
*
* @param {Function} fn - the function to deprecate
* @param {String} msg - the string to print to the console when `fn` is invoked
* @returns {Function} a new "deprecated" version of `fn`
* @api public
*/
function deprecate (fn, msg) {
if (config('noDeprecation')) {
return fn;
}
var warned = false;
function deprecated() {
if (!warned) {
if (config('throwDeprecation')) {
throw new Error(msg);
} else if (config('traceDeprecation')) {
console.trace(msg);
} else {
console.warn(msg);
}
warned = true;
}
return fn.apply(this, arguments);
}
return deprecated;
}
/**
* Checks `localStorage` for boolean values for the given `name`.
*
* @param {String} name
* @returns {Boolean}
* @api private
*/
function config (name) {
// accessing global.localStorage can trigger a DOMException in sandboxed iframes
try {
if (!global.localStorage) return false;
} catch (_) {
return false;
}
var val = global.localStorage[name];
if (null == val) return false;
return String(val).toLowerCase() === 'true';
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7)))
/***/ }),
/* 77 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = __webpack_require__(27);
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
this.writeencoding = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return stream.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined) stream.push(data);
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(this);
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.once('prefinish', function () {
if (typeof this._flush === 'function') this._flush(function (er, data) {
done(stream, er, data);
});else done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data !== null && data !== undefined) stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length) throw new Error('Calling transform done when ws.length != 0');
if (ts.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
/***/ }),
/* 78 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const utils = __webpack_require__(19);
const transaction_1 = __webpack_require__(47);
const common_1 = __webpack_require__(0);
function attachTransactionDate(connection, tx) {
if (tx.date) {
return Promise.resolve(tx);
}
const ledgerVersion = tx.ledger_index || tx.LedgerSequence;
if (!ledgerVersion) {
return new Promise(() => {
throw new common_1.errors.NotFoundError('ledger_index and LedgerSequence not found in tx');
});
}
const request = {
command: 'ledger',
ledger_index: ledgerVersion
};
return connection.request(request).then(data => {
if (typeof data.ledger.close_time === 'number') {
return _.assign({ date: data.ledger.close_time }, tx);
}
throw new common_1.errors.UnexpectedError('Ledger missing close_time');
}).catch(error => {
if (error instanceof common_1.errors.UnexpectedError) {
throw error;
}
throw new common_1.errors.NotFoundError('Transaction ledger not found');
});
}
function isTransactionInRange(tx, options) {
return (!options.minLedgerVersion
|| tx.ledger_index >= options.minLedgerVersion)
&& (!options.maxLedgerVersion
|| tx.ledger_index <= options.maxLedgerVersion);
}
function convertError(connection, options, error) {
const _error = (error.message === 'txnNotFound') ?
new common_1.errors.NotFoundError('Transaction not found') : error;
if (_error instanceof common_1.errors.NotFoundError) {
return utils.hasCompleteLedgerRange(connection, options.minLedgerVersion, options.maxLedgerVersion).then(hasCompleteLedgerRange => {
if (!hasCompleteLedgerRange) {
return utils.isPendingLedgerVersion(connection, options.maxLedgerVersion)
.then(isPendingLedgerVersion => {
return isPendingLedgerVersion ?
new common_1.errors.PendingLedgerVersionError() :
new common_1.errors.MissingLedgerHistoryError();
});
}
return _error;
});
}
return Promise.resolve(_error);
}
function formatResponse(options, tx) {
if (tx.validated !== true || !isTransactionInRange(tx, options)) {
throw new common_1.errors.NotFoundError('Transaction not found');
}
return transaction_1.default(tx);
}
function getTransaction(id, options = {}) {
common_1.validate.getTransaction({ id, options });
const request = {
command: 'tx',
transaction: id,
binary: false
};
return utils.ensureLedgerVersion.call(this, options).then(_options => {
return this.connection.request(request).then((tx) => attachTransactionDate(this.connection, tx)).then(_.partial(formatResponse, _options))
.catch(error => {
return convertError(this.connection, _options, error).then(_error => {
throw _error;
});
});
});
}
exports.default = getTransaction;
/***/ }),
/* 79 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _ = __webpack_require__(1)
var BigNumber = __webpack_require__(6)
var normalizeNodes = __webpack_require__(42).normalizeNodes
var dropsToXRP = __webpack_require__(42).dropsToXRP
function groupByAddress(balanceChanges) {
var grouped = _.groupBy(balanceChanges, function(node) {
return node.address
})
return _.mapValues(grouped, function(group) {
return _.map(group, function(node) {
return node.balance
})
})
}
function parseValue(value) {
return new BigNumber(value.value || value)
}
function computeBalanceChange(node) {
var value = null
if (node.newFields.Balance) {
value = parseValue(node.newFields.Balance)
} else if (node.previousFields.Balance && node.finalFields.Balance) {
value = parseValue(node.finalFields.Balance).minus(
parseValue(node.previousFields.Balance))
}
return value === null ? null : value.isZero() ? null : value
}
function parseFinalBalance(node) {
if (node.newFields.Balance) {
return parseValue(node.newFields.Balance)
} else if (node.finalFields.Balance) {
return parseValue(node.finalFields.Balance)
}
return null
}
function parseXRPQuantity(node, valueParser) {
var value = valueParser(node)
if (value === null) {
return null
}
return {
address: node.finalFields.Account || node.newFields.Account,
balance: {
counterparty: '',
currency: 'XRP',
value: dropsToXRP(value).toString()
}
}
}
function flipTrustlinePerspective(quantity) {
var negatedBalance = (new BigNumber(quantity.balance.value)).negated()
return {
address: quantity.balance.counterparty,
balance: {
counterparty: quantity.address,
currency: quantity.balance.currency,
value: negatedBalance.toString()
}
}
}
function parseTrustlineQuantity(node, valueParser) {
var value = valueParser(node)
if (value === null) {
return null
}
/*
* A trustline can be created with a non-zero starting balance
* If an offer is placed to acquire an asset with no existing trustline,
* the trustline can be created when the ofer is taken.
*/
var fields = _.isEmpty(node.newFields) ? node.finalFields : node.newFields
// the balance is always from low node's perspective
var result = {
address: fields.LowLimit.issuer,
balance: {
counterparty: fields.HighLimit.issuer,
currency: fields.Balance.currency,
value: value.toString()
}
}
return [result, flipTrustlinePerspective(result)]
}
function parseQuantities(metadata, valueParser) {
var values = normalizeNodes(metadata).map(function(node) {
if (node.entryType === 'AccountRoot') {
return [parseXRPQuantity(node, valueParser)]
} else if (node.entryType === 'RippleState') {
return parseTrustlineQuantity(node, valueParser)
}
return []
})
return groupByAddress(_.compact(_.flatten(values)))
}
/**
* Computes the complete list of every balance that changed in the ledger
* as a result of the given transaction.
*
* @param {Object} metadata Transaction metada
* @returns {Object} parsed balance changes
*/
function parseBalanceChanges(metadata) {
return parseQuantities(metadata, computeBalanceChange)
}
/**
* Computes the complete list of every final balance in the ledger
* as a result of the given transaction.
*
* @param {Object} metadata Transaction metada
* @returns {Object} parsed balances
*/
function parseFinalBalances(metadata) {
return parseQuantities(metadata, parseFinalBalance)
}
module.exports.parseBalanceChanges = parseBalanceChanges
module.exports.parseFinalBalances = parseFinalBalances
/***/ }),
/* 80 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const bignumber_js_1 = __webpack_require__(6);
const common_1 = __webpack_require__(0);
const AccountFields = common_1.constants.AccountFields;
function parseField(info, value) {
if (info.encoding === 'hex' && !info.length) {
return new Buffer(value, 'hex').toString('ascii');
}
if (info.shift) {
return (new bignumber_js_1.default(value)).shift(-info.shift).toNumber();
}
return value;
}
function parseFields(data) {
const settings = {};
for (const fieldName in AccountFields) {
const fieldValue = data[fieldName];
if (fieldValue !== undefined) {
const info = AccountFields[fieldName];
settings[info.name] = parseField(info, fieldValue);
}
}
if (data.RegularKey) {
settings.regularKey = data.RegularKey;
}
// Since an account can own at most one SignerList,
// this array must have exactly one member if it is present.
if (data.signer_lists && data.signer_lists.length === 1) {
settings.signers = {};
if (data.signer_lists[0].SignerQuorum) {
settings.signers.threshold = data.signer_lists[0].SignerQuorum;
}
if (data.signer_lists[0].SignerEntries) {
settings.signers.weights = _.map(data.signer_lists[0].SignerEntries, (entry) => {
return {
address: entry.SignerEntry.Account,
weight: entry.SignerEntry.SignerWeight
};
});
}
}
return settings;
}
exports.default = parseFields;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 81 */
/***/ (function(module, exports, __webpack_require__) {
var __WEBPACK_AMD_DEFINE_RESULT__;/*! decimal.js v5.0.8 https://github.com/MikeMcl/decimal.js/LICENCE */
;(function (globalScope) {
'use strict';
/*
* decimal.js v5.0.8
* An arbitrary-precision Decimal type for JavaScript.
* https://github.com/MikeMcl/decimal.js
* Copyright (c) 2016 Michael Mclaughlin <M8ch88l@gmail.com>
* MIT Expat Licence
*/
// ----------------------------------- EDITABLE DEFAULTS ------------------------------------ //
// The maximum exponent magnitude.
// The limit on the value of `toExpNeg`, `toExpPos`, `minE` and `maxE`.
var EXP_LIMIT = 9e15, // 0 to 9e15
// The limit on the value of `precision`, and on the value of the first argument to
// `toDecimalPlaces`, `toExponential`, `toFixed`, `toPrecision` and `toSignificantDigits`.
MAX_DIGITS = 1e9, // 0 to 1e9
// The base 88 alphabet used by `toJSON` and `fromJSON`.
// 7 printable ASCII characters omitted (space) \ " & ' < >
NUMERALS = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%()*+,-./:;=?@[]^_`{|}~',
// The natural logarithm of 10 (1025 digits).
LN10 = '2.3025850929940456840179914546843642076011014886287729760333279009675726096773524802359972050895982983419677840422862486334095254650828067566662873690987816894829072083255546808437998948262331985283935053089653777326288461633662222876982198867465436674744042432743651550489343149393914796194044002221051017141748003688084012647080685567743216228355220114804663715659121373450747856947683463616792101806445070648000277502684916746550586856935673420670581136429224554405758925724208241314695689016758940256776311356919292033376587141660230105703089634572075440370847469940168269282808481184289314848524948644871927809676271275775397027668605952496716674183485704422507197965004714951050492214776567636938662976979522110718264549734772662425709429322582798502585509785265383207606726317164309505995087807523710333101197857547331541421808427543863591778117054309827482385045648019095610299291824318237525357709750539565187697510374970888692180205189339507238539205144634197265287286965110862571492198849978748873771345686209167058',
// Pi (1025 digits).
PI = '3.1415926535897932384626433832795028841971693993751058209749445923078164062862089986280348253421170679821480865132823066470938446095505822317253594081284811174502841027019385211055596446229489549303819644288109756659334461284756482337867831652712019091456485669234603486104543266482133936072602491412737245870066063155881748815209209628292540917153643678925903600113305305488204665213841469519415116094330572703657595919530921861173819326117931051185480744623799627495673518857527248912279381830119491298336733624406566430860213949463952247371907021798609437027705392171762931767523846748184676694051320005681271452635608277857713427577896091736371787214684409012249534301465495853710507922796892589235420199561121290219608640344181598136297747713099605187072113499999983729780499510597317328160963185950244594553469083026425223082533446850352619311881710100031378387528865875332083814206171776691473035982534904287554687311595628638823537875937519577818577805321712268066130019278766111959092164201989380952572010654858632789',
// The initial configuration properties of the Decimal constructor.
Decimal = {
// These values must be integers within the stated ranges (inclusive).
// Most of these values can be changed during run-time using `Decimal.config`.
// The maximum number of significant digits of the result of a calculation or base conversion.
// E.g. `Decimal.config({ precision: 20 });`
precision: 20, // 1 to MAX_DIGITS
// The rounding mode used when rounding to `precision`.
//
// ROUND_UP 0 Away from zero.
// ROUND_DOWN 1 Towards zero.
// ROUND_CEIL 2 Towards +Infinity.
// ROUND_FLOOR 3 Towards -Infinity.
// ROUND_HALF_UP 4 Towards nearest neighbour. If equidistant, up.
// ROUND_HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
// ROUND_HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
// ROUND_HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
// ROUND_HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
//
// E.g.
// `Decimal.rounding = 4;`
// `Decimal.rounding = Decimal.ROUND_HALF_UP;`
rounding: 4, // 0 to 8
// The modulo mode used when calculating the modulus: a mod n.
// The quotient (q = a / n) is calculated according to the corresponding rounding mode.
// The remainder (r) is calculated as: r = a - n * q.
//
// UP 0 The remainder is positive if the dividend is negative, else is negative.
// DOWN 1 The remainder has the same sign as the dividend (JavaScript %).
// FLOOR 3 The remainder has the same sign as the divisor (Python %).
// HALF_EVEN 6 The IEEE 754 remainder function.
// EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)). Always positive.
//
// Truncated division (1), floored division (3), the IEEE 754 remainder (6), and Euclidian
// division (9) are commonly used for the modulus operation. The other rounding modes can also
// be used, but they may not give useful results.
modulo: 1, // 0 to 9
// The exponent value at and beneath which `toString` returns exponential notation.
// JavaScript numbers: -7
toExpNeg: -7, // 0 to -EXP_LIMIT
// The exponent value at and above which `toString` returns exponential notation.
// JavaScript numbers: 21
toExpPos: 21, // 0 to EXP_LIMIT
// The minimum exponent value, beneath which underflow to zero occurs.
// JavaScript numbers: -324 (5e-324)
minE: -EXP_LIMIT, // -1 to -EXP_LIMIT
// The maximum exponent value, above which overflow to Infinity occurs.
// JavaScript numbers: 308 (1.7976931348623157e+308)
maxE: EXP_LIMIT, // 1 to EXP_LIMIT
// Whether to use cryptographically-secure random number generation, if available.
crypto: void 0 // true/false/undefined
},
// ----------------------------------- END OF EDITABLE DEFAULTS ------------------------------- //
inexact, noConflict, quadrant,
cryptoObject = typeof crypto != 'undefined' ? crypto : null,
external = true,
decimalError = '[DecimalError] ',
invalidArgument = decimalError + 'Invalid argument: ',
precisionLimitExceeded = decimalError + 'Precision limit exceeded',
mathfloor = Math.floor,
mathpow = Math.pow,
isBinary = /^0b([01]+(\.[01]*)?|\.[01]+)(p[+-]?\d+)?$/i,
isHex = /^0x([0-9a-f]+(\.[0-9a-f]*)?|\.[0-9a-f]+)(p[+-]?\d+)?$/i,
isOctal = /^0o([0-7]+(\.[0-7]*)?|\.[0-7]+)(p[+-]?\d+)?$/i,
isDecimal = /^(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
BASE = 1e7,
LOG_BASE = 7,
MAX_SAFE_INTEGER = 9007199254740991,
LN10_PRECISION = LN10.length - 1,
PI_PRECISION = PI.length - 1,
// Decimal.prototype object
P = {};
// Decimal prototype methods
/*
* absoluteValue abs
* ceil
* comparedTo cmp
* cosine cos
* cubeRoot cbrt
* decimalPlaces dp
* dividedBy div
* dividedToIntegerBy divToInt
* equals eq
* floor
* greaterThan gt
* greaterThanOrEqualTo gte
* hyperbolicCosine cosh
* hyperbolicSine sinh
* hyperbolicTangent tanh
* inverseCosine acos
* inverseHyperbolicCosine acosh
* inverseHyperbolicSine asinh
* inverseHyperbolicTangent atanh
* inverseSine asin
* inverseTangent atan
* isFinite
* isInteger isInt
* isNaN
* isNegative isNeg
* isPositive isPos
* isZero
* lessThan lt
* lessThanOrEqualTo lte
* logarithm log
* [maximum] [max]
* [minimum] [min]
* minus sub
* modulo mod
* naturalExponential exp
* naturalLogarithm ln
* negated neg
* plus add
* precision sd
* round
* sine sin
* squareRoot sqrt
* tangent tan
* times mul
* toBinary
* toDecimalPlaces toDP
* toExponential
* toFixed
* toFraction
* toHexadecimal toHex
* toJSON
* toNearest
* toNumber
* toOctal
* toPower pow
* toPrecision
* toSignificantDigits toSD
* toString
* truncated trunc
* valueOf
*/
/*
* Return a new Decimal whose value is the absolute value of this Decimal.
*
*/
P.absoluteValue = P.abs = function () {
var x = new this.constructor(this);
if (x.s < 0) x.s = 1;
return finalise(x);
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
* direction of positive Infinity.
*
*/
P.ceil = function () {
return finalise(new this.constructor(this), this.e + 1, 2);
};
/*
* Return
* 1 if the value of this Decimal is greater than the value of `y`,
* -1 if the value of this Decimal is less than the value of `y`,
* 0 if they have the same value,
* NaN if the value of either Decimal is NaN.
*
*/
P.comparedTo = P.cmp = function (y) {
var i, j, xdL, ydL,
x = this,
xd = x.d,
yd = (y = new x.constructor(y)).d,
xs = x.s,
ys = y.s;
// Either NaN or ±Infinity?
if (!xd || !yd) {
return !xs || !ys ? NaN : xs !== ys ? xs : xd === yd ? 0 : !xd ^ xs < 0 ? 1 : -1;
}
// Either zero?
if (!xd[0] || !yd[0]) return xd[0] ? xs : yd[0] ? -ys : 0;
// Signs differ?
if (xs !== ys) return xs;
// Compare exponents.
if (x.e !== y.e) return x.e > y.e ^ xs < 0 ? 1 : -1;
xdL = xd.length;
ydL = yd.length;
// Compare digit by digit.
for (i = 0, j = xdL < ydL ? xdL : ydL; i < j; ++i) {
if (xd[i] !== yd[i]) return xd[i] > yd[i] ^ xs < 0 ? 1 : -1;
}
// Compare lengths.
return xdL === ydL ? 0 : xdL > ydL ^ xs < 0 ? 1 : -1;
};
/*
* Return a new Decimal whose value is the cosine of the value in radians of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-1, 1]
*
* cos(0) = 1
* cos(-0) = 1
* cos(Infinity) = NaN
* cos(-Infinity) = NaN
* cos(NaN) = NaN
*
*/
P.cosine = P.cos = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.d) return new Ctor(NaN);
// cos(0) = cos(-0) = 1
if (!x.d[0]) return new Ctor(1);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
Ctor.rounding = 1;
x = cosine(Ctor, toLessThanHalfPi(Ctor, x));
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(quadrant == 2 || quadrant == 3 ? x.neg() : x, pr, rm, true);
};
/*
*
* Return a new Decimal whose value is the cube root of the value of this Decimal, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* cbrt(0) = 0
* cbrt(-0) = -0
* cbrt(1) = 1
* cbrt(-1) = -1
* cbrt(N) = N
* cbrt(-I) = -I
* cbrt(I) = I
*
* Math.cbrt(x) = (x < 0 ? -Math.pow(-x, 1/3) : Math.pow(x, 1/3))
*
*/
P.cubeRoot = P.cbrt = function () {
var e, m, n, r, rep, s, sd, t, t3, t3plusx,
x = this,
Ctor = x.constructor;
if (!x.isFinite() || x.isZero()) return new Ctor(x);
external = false;
// Initial estimate.
s = x.s * Math.pow(x.s * x, 1 / 3);
// Math.cbrt underflow/overflow?
// Pass x to Math.pow as integer, then adjust the exponent of the result.
if (!s || Math.abs(s) == 1 / 0) {
n = digitsToString(x.d);
e = x.e;
// Adjust n exponent so it is a multiple of 3 away from x exponent.
if (s = (e - n.length + 1) % 3) n += (s == 1 || s == -2 ? '0' : '00');
s = Math.pow(n, 1 / 3);
// Rarely, e may be one less than the result exponent value.
e = mathfloor((e + 1) / 3) - (e % 3 == (e < 0 ? -1 : 2));
if (s == 1 / 0) {
n = '5e' + e;
} else {
n = s.toExponential();
n = n.slice(0, n.indexOf('e') + 1) + e;
}
r = new Ctor(n);
r.s = x.s;
} else {
r = new Ctor(s.toString());
}
sd = (e = Ctor.precision) + 3;
// Halley's method.
// TODO? Compare Newton's method.
for (;;) {
t = r;
t3 = t.times(t).times(t);
t3plusx = t3.plus(x);
r = divide(t3plusx.plus(x).times(t), t3plusx.plus(t3), sd + 2, 1);
// TODO? Replace with for-loop and checkRoundingDigits.
if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
n = n.slice(sd - 3, sd + 1);
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or 4999
// , i.e. approaching a rounding boundary, continue the iteration.
if (n == '9999' || !rep && n == '4999') {
// On the first iteration only, check to see if rounding up gives the exact result as the
// nines may infinitely repeat.
if (!rep) {
finalise(t, e + 1, 0);
if (t.times(t).times(t).eq(x)) {
r = t;
break;
}
}
sd += 4;
rep = 1;
} else {
// If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
// If not, then there are further digits and m will be truthy.
if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
// Truncate to the first rounding digit.
finalise(r, e + 1, 1);
m = !r.times(r).times(r).eq(x);
}
break;
}
}
}
external = true;
return finalise(r, e, Ctor.rounding, m);
};
/*
* Return the number of decimal places of the value of this Decimal.
*
*/
P.decimalPlaces = P.dp = function () {
var w,
d = this.d,
n = NaN;
if (d) {
w = d.length - 1;
n = (w - mathfloor(this.e / LOG_BASE)) * LOG_BASE;
// Subtract the number of trailing zeros of the last word.
w = d[w];
if (w) for (; w % 10 == 0; w /= 10) n--;
if (n < 0) n = 0;
}
return n;
};
/*
* n / 0 = I
* n / N = N
* n / I = 0
* 0 / n = 0
* 0 / 0 = N
* 0 / N = N
* 0 / I = 0
* N / n = N
* N / 0 = N
* N / N = N
* N / I = N
* I / n = I
* I / 0 = I
* I / N = N
* I / I = N
*
* Return a new Decimal whose value is the value of this Decimal divided by `y`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
*/
P.dividedBy = P.div = function (y) {
return divide(this, new this.constructor(y));
};
/*
* Return a new Decimal whose value is the integer part of dividing the value of this Decimal
* by the value of `y`, rounded to `precision` significant digits using rounding mode `rounding`.
*
*/
P.dividedToIntegerBy = P.divToInt = function (y) {
var x = this,
Ctor = x.constructor;
return finalise(divide(x, new Ctor(y), 0, 1, 1), Ctor.precision, Ctor.rounding);
};
/*
* Return true if the value of this Decimal is equal to the value of `y`, otherwise return false.
*
*/
P.equals = P.eq = function (y) {
return this.cmp(y) === 0;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a whole number in the
* direction of negative Infinity.
*
*/
P.floor = function () {
return finalise(new this.constructor(this), this.e + 1, 3);
};
/*
* Return true if the value of this Decimal is greater than the value of `y`, otherwise return
* false.
*
*/
P.greaterThan = P.gt = function (y) {
return this.cmp(y) > 0;
};
/*
* Return true if the value of this Decimal is greater than or equal to the value of `y`,
* otherwise return false.
*
*/
P.greaterThanOrEqualTo = P.gte = function (y) {
var k = this.cmp(y);
return k == 1 || k === 0;
};
/*
* Return a new Decimal whose value is the hyperbolic cosine of the value in radians of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [1, Infinity]
*
* cosh(x) = 1 + x^2/2! + x^4/4! + x^6/6! + ...
*
* cosh(0) = 1
* cosh(-0) = 1
* cosh(Infinity) = Infinity
* cosh(-Infinity) = Infinity
* cosh(NaN) = NaN
*
* x time taken (ms) result
* 1000 9 9.8503555700852349694e+433
* 10000 25 4.4034091128314607936e+4342
* 100000 171 1.4033316802130615897e+43429
* 1000000 3817 1.5166076984010437725e+434294
* 10000000 abandoned after 2 minute wait
*
* TODO? Compare performance of cosh(x) = 0.5 * (exp(x) + exp(-x))
*
*/
P.hyperbolicCosine = P.cosh = function () {
var k, n, pr, rm, len,
x = this,
Ctor = x.constructor,
one = new Ctor(1);
if (!x.isFinite()) return new Ctor(x.s ? 1 / 0 : NaN);
if (x.isZero()) return one;
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
Ctor.rounding = 1;
len = x.d.length;
// Argument reduction: cos(4x) = 1 - 8cos^2(x) + 8cos^4(x) + 1
// i.e. cos(x) = 1 - cos^2(x/4)(8 - 8cos^2(x/4))
// Estimate the optimum number of times to use the argument reduction.
// TODO? Estimation reused from cosine() and may not be optimal here.
if (len < 32) {
k = Math.ceil(len / 3);
n = Math.pow(4, -k).toString();
} else {
k = 16;
n = '2.3283064365386962890625e-10';
}
x = taylorSeries(Ctor, 1, x.times(n), new Ctor(1), true);
// Reverse argument reduction
var cosh2_x,
i = k,
d8 = new Ctor(8);
for (; i--;) {
cosh2_x = x.times(x);
x = one.minus(cosh2_x.times(d8.minus(cosh2_x.times(d8))));
}
return finalise(x, Ctor.precision = pr, Ctor.rounding = rm, true);
};
/*
* Return a new Decimal whose value is the hyperbolic sine of the value in radians of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-Infinity, Infinity]
*
* sinh(x) = x + x^3/3! + x^5/5! + x^7/7! + ...
*
* sinh(0) = 0
* sinh(-0) = -0
* sinh(Infinity) = Infinity
* sinh(-Infinity) = -Infinity
* sinh(NaN) = NaN
*
* x time taken (ms)
* 10 2 ms
* 100 5 ms
* 1000 14 ms
* 10000 82 ms
* 100000 886 ms 1.4033316802130615897e+43429
* 200000 2613 ms
* 300000 5407 ms
* 400000 8824 ms
* 500000 13026 ms 8.7080643612718084129e+217146
* 1000000 48543 ms
*
* TODO? Compare performance of sinh(x) = 0.5 * (exp(x) - exp(-x))
*
*/
P.hyperbolicSine = P.sinh = function () {
var k, pr, rm, len,
x = this,
Ctor = x.constructor;
if (!x.isFinite() || x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + 4;
Ctor.rounding = 1;
len = x.d.length;
if (len < 3) {
x = taylorSeries(Ctor, 2, x, x, true);
} else {
// Alternative argument reduction: sinh(3x) = sinh(x)(3 + 4sinh^2(x))
// i.e. sinh(x) = sinh(x/3)(3 + 4sinh^2(x/3))
// 3 multiplications and 1 addition
// Argument reduction: sinh(5x) = sinh(x)(5 + sinh^2(x)(20 + 16sinh^2(x)))
// i.e. sinh(x) = sinh(x/5)(5 + sinh^2(x/5)(20 + 16sinh^2(x/5)))
// 4 multiplications and 2 additions
// Estimate the optimum number of times to use the argument reduction.
k = 1.4 * Math.sqrt(len);
k = k > 16 ? 16 : k | 0;
x = x.times(Math.pow(5, -k));
x = taylorSeries(Ctor, 2, x, x, true);
// Reverse argument reduction
var sinh2_x,
d5 = new Ctor(5),
d16 = new Ctor(16),
d20 = new Ctor(20);
for (; k--;) {
sinh2_x = x.times(x);
x = x.times(d5.plus(sinh2_x.times(d16.times(sinh2_x).plus(d20))));
}
}
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(x, pr, rm, true);
};
/*
* Return a new Decimal whose value is the hyperbolic tangent of the value in radians of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-1, 1]
*
* tanh(x) = sinh(x) / cosh(x)
*
* tanh(0) = 0
* tanh(-0) = -0
* tanh(Infinity) = 1
* tanh(-Infinity) = -1
* tanh(NaN) = NaN
*
*/
P.hyperbolicTangent = P.tanh = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(x.s);
if (x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + 7;
Ctor.rounding = 1;
return divide(x.sinh(), x.cosh(), Ctor.precision = pr, Ctor.rounding = rm);
};
/*
* Return a new Decimal whose value is the arccosine (inverse cosine) in radians of the value of
* this Decimal.
*
* Domain: [-1, 1]
* Range: [0, pi]
*
* acos(x) = pi/2 - asin(x)
*
* acos(0) = pi/2
* acos(-0) = pi/2
* acos(1) = 0
* acos(-1) = pi
* acos(1/2) = pi/3
* acos(-1/2) = 2*pi/3
* acos(|x| > 1) = NaN
* acos(NaN) = NaN
*
*/
P.inverseCosine = P.acos = function () {
var halfPi,
x = this,
Ctor = x.constructor,
k = x.abs().cmp(1),
pr = Ctor.precision,
rm = Ctor.rounding;
if (k !== -1) {
return k === 0
// |x| is 1
? x.isNeg() ? getPi(Ctor, pr, rm) : new Ctor(0)
// |x| > 1 or x is NaN
: new Ctor(NaN);
}
if (x.isZero()) return getPi(Ctor, pr + 4, rm).times(0.5);
// TODO? Special case acos(0.5) = pi/3 and acos(-0.5) = 2*pi/3
Ctor.precision = pr + 6;
Ctor.rounding = 1;
x = x.asin();
halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
Ctor.precision = pr;
Ctor.rounding = rm;
return halfPi.minus(x);
};
/*
* Return a new Decimal whose value is the inverse of the hyperbolic cosine in radians of the
* value of this Decimal.
*
* Domain: [1, Infinity]
* Range: [0, Infinity]
*
* acosh(x) = ln(x + sqrt(x^2 - 1))
*
* acosh(x < 1) = NaN
* acosh(NaN) = NaN
* acosh(Infinity) = Infinity
* acosh(-Infinity) = NaN
* acosh(0) = NaN
* acosh(-0) = NaN
* acosh(1) = 0
* acosh(-1) = NaN
*
*/
P.inverseHyperbolicCosine = P.acosh = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (x.lte(1)) return new Ctor(x.eq(1) ? 0 : NaN);
if (!x.isFinite()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(Math.abs(x.e), x.sd()) + 4;
Ctor.rounding = 1;
external = false;
x = x.times(x).minus(1).sqrt().plus(x);
external = true;
Ctor.precision = pr;
Ctor.rounding = rm;
return x.ln();
};
/*
* Return a new Decimal whose value is the inverse of the hyperbolic sine in radians of the value
* of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-Infinity, Infinity]
*
* asinh(x) = ln(x + sqrt(x^2 + 1))
*
* asinh(NaN) = NaN
* asinh(Infinity) = Infinity
* asinh(-Infinity) = -Infinity
* asinh(0) = 0
* asinh(-0) = -0
*
*/
P.inverseHyperbolicSine = P.asinh = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite() || x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + 2 * Math.max(Math.abs(x.e), x.sd()) + 6;
Ctor.rounding = 1;
external = false;
x = x.times(x).plus(1).sqrt().plus(x);
external = true;
Ctor.precision = pr;
Ctor.rounding = rm;
return x.ln();
};
/*
* Return a new Decimal whose value is the inverse of the hyperbolic tangent in radians of the
* value of this Decimal.
*
* Domain: [-1, 1]
* Range: [-Infinity, Infinity]
*
* atanh(x) = 0.5 * ln((1 + x) / (1 - x))
*
* atanh(|x| > 1) = NaN
* atanh(NaN) = NaN
* atanh(Infinity) = NaN
* atanh(-Infinity) = NaN
* atanh(0) = 0
* atanh(-0) = -0
* atanh(1) = Infinity
* atanh(-1) = -Infinity
*
*/
P.inverseHyperbolicTangent = P.atanh = function () {
var pr, rm, wpr, xsd,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(NaN);
if (x.e >= 0) return new Ctor(x.abs().eq(1) ? x.s / 0 : x.isZero() ? x : NaN);
pr = Ctor.precision;
rm = Ctor.rounding;
xsd = x.sd();
if (Math.max(xsd, pr) < 2 * -x.e - 1) return finalise(new Ctor(x), pr, rm, true);
Ctor.precision = wpr = xsd - x.e;
x = divide(x.plus(1), new Ctor(1).minus(x), wpr + pr, 1);
Ctor.precision = pr + 4;
Ctor.rounding = 1;
x = x.ln();
Ctor.precision = pr;
Ctor.rounding = rm;
return x.times(0.5);
};
/*
* Return a new Decimal whose value is the arcsine (inverse sine) in radians of the value of this
* Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-pi/2, pi/2]
*
* asin(x) = 2*atan(x/(1 + sqrt(1 - x^2)))
*
* asin(0) = 0
* asin(-0) = -0
* asin(1/2) = pi/6
* asin(-1/2) = -pi/6
* asin(1) = pi/2
* asin(-1) = -pi/2
* asin(|x| > 1) = NaN
* asin(NaN) = NaN
*
* TODO? Compare performance of Taylor series.
*
*/
P.inverseSine = P.asin = function () {
var halfPi, k,
pr, rm,
x = this,
Ctor = x.constructor;
if (x.isZero()) return new Ctor(x);
k = x.abs().cmp(1);
pr = Ctor.precision;
rm = Ctor.rounding;
if (k !== -1) {
// |x| is 1
if (k === 0) {
halfPi = getPi(Ctor, pr + 4, rm).times(0.5);
halfPi.s = x.s;
return halfPi;
}
// |x| > 1 or x is NaN
return new Ctor(NaN);
}
// TODO? Special case asin(1/2) = pi/6 and asin(-1/2) = -pi/6
Ctor.precision = pr + 6;
Ctor.rounding = 1;
x = x.div(new Ctor(1).minus(x.times(x)).sqrt().plus(1)).atan();
Ctor.precision = pr;
Ctor.rounding = rm;
return x.times(2);
};
/*
* Return a new Decimal whose value is the arctangent (inverse tangent) in radians of the value
* of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-pi/2, pi/2]
*
* atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
*
* atan(0) = 0
* atan(-0) = -0
* atan(1) = pi/4
* atan(-1) = -pi/4
* atan(Infinity) = pi/2
* atan(-Infinity) = -pi/2
* atan(NaN) = NaN
*
*/
P.inverseTangent = P.atan = function () {
var i, j, k, n, px, t, r, wpr, x2,
x = this,
Ctor = x.constructor,
pr = Ctor.precision,
rm = Ctor.rounding;
if (!x.isFinite()) {
if (!x.s) return new Ctor(NaN);
if (pr + 4 <= PI_PRECISION) {
r = getPi(Ctor, pr + 4, rm).times(0.5);
r.s = x.s;
return r;
}
} else if (x.isZero()) {
return new Ctor(x);
} else if (x.abs().eq(1) && pr + 4 <= PI_PRECISION) {
r = getPi(Ctor, pr + 4, rm).times(0.25);
r.s = x.s;
return r;
}
Ctor.precision = wpr = pr + 10;
Ctor.rounding = 1;
// TODO? if (x >= 1 && pr <= PI_PRECISION) atan(x) = halfPi * x.s - atan(1 / x);
// Argument reduction
// Ensure |x| < 0.42
// atan(x) = 2 * atan(x / (1 + sqrt(1 + x^2)))
k = Math.min(28, wpr / LOG_BASE + 2 | 0);
for (i = k; i; --i) x = x.div(x.times(x).plus(1).sqrt().plus(1));
external = false;
j = Math.ceil(wpr / LOG_BASE);
n = 1;
x2 = x.times(x);
r = new Ctor(x);
px = x;
// atan(x) = x - x^3/3 + x^5/5 - x^7/7 + ...
for (; i !== -1;) {
px = px.times(x2);
t = r.minus(px.div(n += 2));
px = px.times(x2);
r = t.plus(px.div(n += 2));
if (r.d[j] !== void 0) for (i = j; r.d[i] === t.d[i] && i--;);
}
if (k) r = r.times(2 << (k - 1));
external = true;
return finalise(r, Ctor.precision = pr, Ctor.rounding = rm, true);
};
/*
* Return true if the value of this Decimal is a finite number, otherwise return false.
*
*/
P.isFinite = function () {
return !!this.d;
};
/*
* Return true if the value of this Decimal is an integer, otherwise return false.
*
*/
P.isInteger = P.isInt = function () {
return !!this.d && mathfloor(this.e / LOG_BASE) > this.d.length - 2;
};
/*
* Return true if the value of this Decimal is NaN, otherwise return false.
*
*/
P.isNaN = function () {
return !this.s;
};
/*
* Return true if the value of this Decimal is negative, otherwise return false.
*
*/
P.isNegative = P.isNeg = function () {
return this.s < 0;
};
/*
* Return true if the value of this Decimal is positive, otherwise return false.
*
*/
P.isPositive = P.isPos = function () {
return this.s > 0;
};
/*
* Return true if the value of this Decimal is 0 or -0, otherwise return false.
*
*/
P.isZero = function () {
return !!this.d && this.d[0] === 0;
};
/*
* Return true if the value of this Decimal is less than `y`, otherwise return false.
*
*/
P.lessThan = P.lt = function (y) {
return this.cmp(y) < 0;
};
/*
* Return true if the value of this Decimal is less than or equal to `y`, otherwise return false.
*
*/
P.lessThanOrEqualTo = P.lte = function (y) {
return this.cmp(y) < 1;
};
/*
* Return the logarithm of the value of this Decimal to the specified base, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* If no base is specified, return log[10](arg).
*
* log[base](arg) = ln(arg) / ln(base)
*
* The result will always be correctly rounded if the base of the log is 10, and 'almost always'
* otherwise:
*
* Depending on the rounding mode, the result may be incorrectly rounded if the first fifteen
* rounding digits are [49]99999999999999 or [50]00000000000000. In that case, the maximum error
* between the result and the correctly rounded result will be one ulp (unit in the last place).
*
* log[-b](a) = NaN
* log[0](a) = NaN
* log[1](a) = NaN
* log[NaN](a) = NaN
* log[Infinity](a) = NaN
* log[b](0) = -Infinity
* log[b](-0) = -Infinity
* log[b](-a) = NaN
* log[b](1) = 0
* log[b](Infinity) = Infinity
* log[b](NaN) = NaN
*
* [base] {number|string|Decimal} The base of the logarithm.
*
*/
P.logarithm = P.log = function (base) {
var isBase10, d, denominator, k, inf, num, sd, r,
arg = this,
Ctor = arg.constructor,
pr = Ctor.precision,
rm = Ctor.rounding,
guard = 5;
// Default base is 10.
if (base == null) {
base = new Ctor(10);
isBase10 = true;
} else {
base = new Ctor(base);
d = base.d;
// Return NaN if base is negative, or non-finite, or is 0 or 1.
if (base.s < 0 || !d || !d[0] || base.eq(1)) return new Ctor(NaN);
isBase10 = base.eq(10);
}
d = arg.d;
// Is arg negative, non-finite, 0 or 1?
if (arg.s < 0 || !d || !d[0] || arg.eq(1)) {
return new Ctor(d && !d[0] ? -1 / 0 : arg.s != 1 ? NaN : d ? 0 : 1 / 0);
}
// The result will have a non-terminating decimal expansion if base is 10 and arg is not an
// integer power of 10.
if (isBase10) {
if (d.length > 1) {
inf = true;
} else {
for (k = d[0]; k % 10 === 0;) k /= 10;
inf = k !== 1;
}
}
external = false;
sd = pr + guard;
num = naturalLogarithm(arg, sd);
denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
// The result will have 5 rounding digits.
r = divide(num, denominator, sd, 1);
// If at a rounding boundary, i.e. the result's rounding digits are [49]9999 or [50]0000,
// calculate 10 further digits.
//
// If the result is known to have an infinite decimal expansion, repeat this until it is clear
// that the result is above or below the boundary. Otherwise, if after calculating the 10
// further digits, the last 14 are nines, round up and assume the result is exact.
// Also assume the result is exact if the last 14 are zero.
//
// Example of a result that will be incorrectly rounded:
// log[1048576](4503599627370502) = 2.60000000000000009610279511444746...
// The above result correctly rounded using ROUND_CEIL to 1 decimal place should be 2.7, but it
// will be given as 2.6 as there are 15 zeros immediately after the requested decimal place, so
// the exact result would be assumed to be 2.6, which rounded using ROUND_CEIL to 1 decimal
// place is still 2.6.
if (checkRoundingDigits(r.d, k = pr, rm)) {
do {
sd += 10;
num = naturalLogarithm(arg, sd);
denominator = isBase10 ? getLn10(Ctor, sd + 10) : naturalLogarithm(base, sd);
r = divide(num, denominator, sd, 1);
if (!inf) {
// Check for 14 nines from the 2nd rounding digit, as the first may be 4.
if (+digitsToString(r.d).slice(k + 1, k + 15) + 1 == 1e14) {
r = finalise(r, pr + 1, 0);
}
break;
}
} while (checkRoundingDigits(r.d, k += 10, rm));
}
external = true;
return finalise(r, pr, rm);
};
/*
* Return a new Decimal whose value is the maximum of the arguments and the value of this Decimal.
*
* arguments {number|string|Decimal}
*
P.max = function () {
Array.prototype.push.call(arguments, this);
return maxOrMin(this.constructor, arguments, 'lt');
};
*/
/*
* Return a new Decimal whose value is the minimum of the arguments and the value of this Decimal.
*
* arguments {number|string|Decimal}
*
P.min = function () {
Array.prototype.push.call(arguments, this);
return maxOrMin(this.constructor, arguments, 'gt');
};
*/
/*
* n - 0 = n
* n - N = N
* n - I = -I
* 0 - n = -n
* 0 - 0 = 0
* 0 - N = N
* 0 - I = -I
* N - n = N
* N - 0 = N
* N - N = N
* N - I = N
* I - n = I
* I - 0 = I
* I - N = N
* I - I = N
*
* Return a new Decimal whose value is the value of this Decimal minus `y`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
*/
P.minus = P.sub = function (y) {
var d, e, i, j, k, len, pr, rm, xd, xe, xLTy, yd,
x = this,
Ctor = x.constructor;
y = new Ctor(y);
// If either is not finite...
if (!x.d || !y.d) {
// Return NaN if either is NaN.
if (!x.s || !y.s) y = new Ctor(NaN);
// Return y negated if x is finite and y is ±Infinity.
else if (x.d) y.s = -y.s;
// Return x if y is finite and x is ±Infinity.
// Return x if both are ±Infinity with different signs.
// Return NaN if both are ±Infinity with the same sign.
else y = new Ctor(y.d || x.s !== y.s ? x : NaN);
return y;
}
// If signs differ...
if (x.s != y.s) {
y.s = -y.s;
return x.plus(y);
}
xd = x.d;
yd = y.d;
pr = Ctor.precision;
rm = Ctor.rounding;
// If either is zero...
if (!xd[0] || !yd[0]) {
// Return y negated if x is zero and y is non-zero.
if (yd[0]) y.s = -y.s;
// Return x if y is zero and x is non-zero.
else if (xd[0]) y = new Ctor(x);
// Return zero if both are zero.
// From IEEE 754 (2008) 6.3: 0 - 0 = -0 - -0 = -0 when rounding to -Infinity.
else return new Ctor(rm === 3 ? -0 : 0);
return external ? finalise(y, pr, rm) : y;
}
// x and y are finite, non-zero numbers with the same sign.
// Calculate base 1e7 exponents.
e = mathfloor(y.e / LOG_BASE);
xe = mathfloor(x.e / LOG_BASE);
xd = xd.slice();
k = xe - e;
// If base 1e7 exponents differ...
if (k) {
xLTy = k < 0;
if (xLTy) {
d = xd;
k = -k;
len = yd.length;
} else {
d = yd;
e = xe;
len = xd.length;
}
// Numbers with massively different exponents would result in a very high number of
// zeros needing to be prepended, but this can be avoided while still ensuring correct
// rounding by limiting the number of zeros to `Math.ceil(pr / LOG_BASE) + 2`.
i = Math.max(Math.ceil(pr / LOG_BASE), len) + 2;
if (k > i) {
k = i;
d.length = 1;
}
// Prepend zeros to equalise exponents.
d.reverse();
for (i = k; i--;) d.push(0);
d.reverse();
// Base 1e7 exponents equal.
} else {
// Check digits to determine which is the bigger number.
i = xd.length;
len = yd.length;
xLTy = i < len;
if (xLTy) len = i;
for (i = 0; i < len; i++) {
if (xd[i] != yd[i]) {
xLTy = xd[i] < yd[i];
break;
}
}
k = 0;
}
if (xLTy) {
d = xd;
xd = yd;
yd = d;
y.s = -y.s;
}
len = xd.length;
// Append zeros to `xd` if shorter.
// Don't add zeros to `yd` if shorter as subtraction only needs to start at `yd` length.
for (i = yd.length - len; i > 0; --i) xd[len++] = 0;
// Subtract yd from xd.
for (i = yd.length; i > k;) {
if (xd[--i] < yd[i]) {
for (j = i; j && xd[--j] === 0;) xd[j] = BASE - 1;
--xd[j];
xd[i] += BASE;
}
xd[i] -= yd[i];
}
// Remove trailing zeros.
for (; xd[--len] === 0;) xd.pop();
// Remove leading zeros and adjust exponent accordingly.
for (; xd[0] === 0; xd.shift()) --e;
// Zero?
if (!xd[0]) return new Ctor(rm === 3 ? -0 : 0);
y.d = xd;
y.e = getBase10Exponent(xd, e);
return external ? finalise(y, pr, rm) : y;
};
/*
* n % 0 = N
* n % N = N
* n % I = n
* 0 % n = 0
* -0 % n = -0
* 0 % 0 = N
* 0 % N = N
* 0 % I = 0
* N % n = N
* N % 0 = N
* N % N = N
* N % I = N
* I % n = N
* I % 0 = N
* I % N = N
* I % I = N
*
* Return a new Decimal whose value is the value of this Decimal modulo `y`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* The result depends on the modulo mode.
*
*/
P.modulo = P.mod = function (y) {
var q,
x = this,
Ctor = x.constructor;
y = new Ctor(y);
// Return NaN if x is ±Infinity or NaN, or y is NaN or ±0.
if (!x.d || !y.s || y.d && !y.d[0]) return new Ctor(NaN);
// Return x if y is ±Infinity or x is ±0.
if (!y.d || x.d && !x.d[0]) {
return finalise(new Ctor(x), Ctor.precision, Ctor.rounding);
}
// Prevent rounding of intermediate calculations.
external = false;
if (Ctor.modulo == 9) {
// Euclidian division: q = sign(y) * floor(x / abs(y))
// result = x - q * y where 0 <= result < abs(y)
q = divide(x, y.abs(), 0, 3, 1);
q.s *= y.s;
} else {
q = divide(x, y, 0, Ctor.modulo, 1);
}
q = q.times(y);
external = true;
return x.minus(q);
};
/*
* Return a new Decimal whose value is the natural exponential of the value of this Decimal,
* i.e. the base e raised to the power the value of this Decimal, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
*/
P.naturalExponential = P.exp = function () {
return naturalExponential(this);
};
/*
* Return a new Decimal whose value is the natural logarithm of the value of this Decimal,
* rounded to `precision` significant digits using rounding mode `rounding`.
*
*/
P.naturalLogarithm = P.ln = function () {
return naturalLogarithm(this);
};
/*
* Return a new Decimal whose value is the value of this Decimal negated, i.e. as if multiplied by
* -1.
*
*/
P.negated = P.neg = function () {
var x = new this.constructor(this);
x.s = -x.s;
return finalise(x);
};
/*
* n + 0 = n
* n + N = N
* n + I = I
* 0 + n = n
* 0 + 0 = 0
* 0 + N = N
* 0 + I = I
* N + n = N
* N + 0 = N
* N + N = N
* N + I = N
* I + n = I
* I + 0 = I
* I + N = N
* I + I = I
*
* Return a new Decimal whose value is the value of this Decimal plus `y`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
*/
P.plus = P.add = function (y) {
var carry, d, e, i, k, len, pr, rm, xd, yd,
x = this,
Ctor = x.constructor;
y = new Ctor(y);
// If either is not finite...
if (!x.d || !y.d) {
// Return NaN if either is NaN.
if (!x.s || !y.s) y = new Ctor(NaN);
// Return x if y is finite and x is ±Infinity.
// Return x if both are ±Infinity with the same sign.
// Return NaN if both are ±Infinity with different signs.
// Return y if x is finite and y is ±Infinity.
else if (!x.d) y = new Ctor(y.d || x.s === y.s ? x : NaN);
return y;
}
// If signs differ...
if (x.s != y.s) {
y.s = -y.s;
return x.minus(y);
}
xd = x.d;
yd = y.d;
pr = Ctor.precision;
rm = Ctor.rounding;
// If either is zero...
if (!xd[0] || !yd[0]) {
// Return x if y is zero.
// Return y if y is non-zero.
if (!yd[0]) y = new Ctor(x);
return external ? finalise(y, pr, rm) : y;
}
// x and y are finite, non-zero numbers with the same sign.
// Calculate base 1e7 exponents.
k = mathfloor(x.e / LOG_BASE);
e = mathfloor(y.e / LOG_BASE);
xd = xd.slice();
i = k - e;
// If base 1e7 exponents differ...
if (i) {
if (i < 0) {
d = xd;
i = -i;
len = yd.length;
} else {
d = yd;
e = k;
len = xd.length;
}
// Limit number of zeros prepended to max(ceil(pr / LOG_BASE), len) + 1.
k = Math.ceil(pr / LOG_BASE);
len = k > len ? k + 1 : len + 1;
if (i > len) {
i = len;
d.length = 1;
}
// Prepend zeros to equalise exponents. Note: Faster to use reverse then do unshifts.
d.reverse();
for (; i--;) d.push(0);
d.reverse();
}
len = xd.length;
i = yd.length;
// If yd is longer than xd, swap xd and yd so xd points to the longer array.
if (len - i < 0) {
i = len;
d = yd;
yd = xd;
xd = d;
}
// Only start adding at yd.length - 1 as the further digits of xd can be left as they are.
for (carry = 0; i;) {
carry = (xd[--i] = xd[i] + yd[i] + carry) / BASE | 0;
xd[i] %= BASE;
}
if (carry) {
xd.unshift(carry);
++e;
}
// Remove trailing zeros.
// No need to check for zero, as +x + +y != 0 && -x + -y != 0
for (len = xd.length; xd[--len] == 0;) xd.pop();
y.d = xd;
y.e = getBase10Exponent(xd, e);
return external ? finalise(y, pr, rm) : y;
};
/*
* Return the number of significant digits of the value of this Decimal.
*
* [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
*
*/
P.precision = P.sd = function (z) {
var k,
x = this;
if (z !== void 0 && z !== !!z && z !== 1 && z !== 0) throw Error(invalidArgument + z);
if (x.d) {
k = getPrecision(x.d);
if (z && x.e + 1 > k) k = x.e + 1;
} else {
k = NaN;
}
return k;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a whole number using
* rounding mode `rounding`.
*
*/
P.round = function () {
var x = this,
Ctor = x.constructor;
return finalise(new Ctor(x), x.e + 1, Ctor.rounding);
};
/*
* Return a new Decimal whose value is the sine of the value in radians of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-1, 1]
*
* sin(x) = x - x^3/3! + x^5/5! - ...
*
* sin(0) = 0
* sin(-0) = -0
* sin(Infinity) = NaN
* sin(-Infinity) = NaN
* sin(NaN) = NaN
*
*/
P.sine = P.sin = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(NaN);
if (x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + Math.max(x.e, x.sd()) + LOG_BASE;
Ctor.rounding = 1;
x = sine(Ctor, toLessThanHalfPi(Ctor, x));
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(quadrant > 2 ? x.neg() : x, pr, rm, true);
};
/*
* Return a new Decimal whose value is the square root of this Decimal, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* sqrt(-n) = N
* sqrt(N) = N
* sqrt(-I) = N
* sqrt(I) = I
* sqrt(0) = 0
* sqrt(-0) = -0
*
*/
P.squareRoot = P.sqrt = function () {
var m, n, sd, r, rep, t,
x = this,
d = x.d,
e = x.e,
s = x.s,
Ctor = x.constructor;
// Negative/NaN/Infinity/zero?
if (s !== 1 || !d || !d[0]) {
return new Ctor(!s || s < 0 && (!d || d[0]) ? NaN : d ? x : 1 / 0);
}
external = false;
// Initial estimate.
s = Math.sqrt(+x);
// Math.sqrt underflow/overflow?
// Pass x to Math.sqrt as integer, then adjust the exponent of the result.
if (s == 0 || s == 1 / 0) {
n = digitsToString(d);
if ((n.length + e) % 2 == 0) n += '0';
s = Math.sqrt(n);
e = mathfloor((e + 1) / 2) - (e < 0 || e % 2);
if (s == 1 / 0) {
n = '1e' + e;
} else {
n = s.toExponential();
n = n.slice(0, n.indexOf('e') + 1) + e;
}
r = new Ctor(n);
} else {
r = new Ctor(s.toString());
}
sd = (e = Ctor.precision) + 3;
// Newton-Raphson iteration.
for (;;) {
t = r;
r = t.plus(divide(x, t, sd + 2, 1)).times(0.5);
// TODO? Replace with for-loop and checkRoundingDigits.
if (digitsToString(t.d).slice(0, sd) === (n = digitsToString(r.d)).slice(0, sd)) {
n = n.slice(sd - 3, sd + 1);
// The 4th rounding digit may be in error by -1 so if the 4 rounding digits are 9999 or
// 4999, i.e. approaching a rounding boundary, continue the iteration.
if (n == '9999' || !rep && n == '4999') {
// On the first iteration only, check to see if rounding up gives the exact result as the
// nines may infinitely repeat.
if (!rep) {
finalise(t, e + 1, 0);
if (t.times(t).eq(x)) {
r = t;
break;
}
}
sd += 4;
rep = 1;
} else {
// If the rounding digits are null, 0{0,4} or 50{0,3}, check for an exact result.
// If not, then there are further digits and m will be truthy.
if (!+n || !+n.slice(1) && n.charAt(0) == '5') {
// Truncate to the first rounding digit.
finalise(r, e + 1, 1);
m = !r.times(r).eq(x);
}
break;
}
}
}
external = true;
return finalise(r, e, Ctor.rounding, m);
};
/*
* Return a new Decimal whose value is the tangent of the value in radians of this Decimal.
*
* Domain: [-Infinity, Infinity]
* Range: [-Infinity, Infinity]
*
* tan(0) = 0
* tan(-0) = -0
* tan(Infinity) = NaN
* tan(-Infinity) = NaN
* tan(NaN) = NaN
*
*/
P.tangent = P.tan = function () {
var pr, rm,
x = this,
Ctor = x.constructor;
if (!x.isFinite()) return new Ctor(NaN);
if (x.isZero()) return new Ctor(x);
pr = Ctor.precision;
rm = Ctor.rounding;
Ctor.precision = pr + 10;
Ctor.rounding = 1;
x = x.sin();
x.s = 1;
x = divide(x, new Ctor(1).minus(x.times(x)).sqrt(), pr + 10, 0);
Ctor.precision = pr;
Ctor.rounding = rm;
return finalise(quadrant == 2 || quadrant == 4 ? x.neg() : x, pr, rm, true);
};
/*
* n * 0 = 0
* n * N = N
* n * I = I
* 0 * n = 0
* 0 * 0 = 0
* 0 * N = N
* 0 * I = N
* N * n = N
* N * 0 = N
* N * N = N
* N * I = N
* I * n = I
* I * 0 = N
* I * N = N
* I * I = I
*
* Return a new Decimal whose value is this Decimal times `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
*/
P.times = P.mul = function (y) {
var carry, e, i, k, r, rL, t, xdL, ydL,
x = this,
Ctor = x.constructor,
xd = x.d,
yd = (y = new Ctor(y)).d;
y.s *= x.s;
// If either is NaN, ±Infinity or ±0...
if (!xd || !xd[0] || !yd || !yd[0]) {
return new Ctor(!y.s || xd && !xd[0] && !yd || yd && !yd[0] && !xd
// Return NaN if either is NaN.
// Return NaN if x is ±0 and y is ±Infinity, or y is ±0 and x is ±Infinity.
? NaN
// Return ±Infinity if either is ±Infinity.
// Return ±0 if either is ±0.
: !xd || !yd ? y.s / 0 : y.s * 0);
}
e = mathfloor(x.e / LOG_BASE) + mathfloor(y.e / LOG_BASE);
xdL = xd.length;
ydL = yd.length;
// Ensure xd points to the longer array.
if (xdL < ydL) {
r = xd;
xd = yd;
yd = r;
rL = xdL;
xdL = ydL;
ydL = rL;
}
// Initialise the result array with zeros.
r = [];
rL = xdL + ydL;
for (i = rL; i--;) r.push(0);
// Multiply!
for (i = ydL; --i >= 0;) {
carry = 0;
for (k = xdL + i; k > i;) {
t = r[k] + yd[i] * xd[k - i - 1] + carry;
r[k--] = t % BASE | 0;
carry = t / BASE | 0;
}
r[k] = (r[k] + carry) % BASE | 0;
}
// Remove trailing zeros.
for (; !r[--rL];) r.pop();
if (carry) ++e;
else r.shift();
// Remove trailing zeros.
for (i = r.length; !r[--i];) r.pop();
y.d = r;
y.e = getBase10Exponent(r, e);
return external ? finalise(y, Ctor.precision, Ctor.rounding) : y;
};
/*
* Return a string representing the value of this Decimal in base 2, round to `sd` significant
* digits using rounding mode `rm`.
*
* If the optional `sd` argument is present then return binary exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toBinary = function (sd, rm) {
return toStringBinary(this, 2, sd, rm);
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `dp`
* decimal places using rounding mode `rm` or `rounding` if `rm` is omitted.
*
* If `dp` is omitted, return a new Decimal whose value is the value of this Decimal.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toDecimalPlaces = P.toDP = function (dp, rm) {
var x = this,
Ctor = x.constructor;
x = new Ctor(x);
if (dp === void 0) return x;
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
return finalise(x, dp + x.e + 1, rm);
};
/*
* Return a string representing the value of this Decimal in exponential notation rounded to
* `dp` fixed decimal places using rounding mode `rounding`.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toExponential = function (dp, rm) {
var str,
x = this,
Ctor = x.constructor;
if (dp === void 0) {
str = finiteToString(x, true);
} else {
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
x = finalise(new Ctor(x), dp + 1, rm);
str = finiteToString(x, true, dp + 1);
}
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return a string representing the value of this Decimal in normal (fixed-point) notation to
* `dp` fixed decimal places and rounded using rounding mode `rm` or `rounding` if `rm` is
* omitted.
*
* As with JavaScript numbers, (-0).toFixed(0) is '0', but e.g. (-0.00001).toFixed(0) is '-0'.
*
* [dp] {number} Decimal places. Integer, 0 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* (-0).toFixed(0) is '0', but (-0.1).toFixed(0) is '-0'.
* (-0).toFixed(1) is '0.0', but (-0.01).toFixed(1) is '-0.0'.
* (-0).toFixed(3) is '0.000'.
* (-0.5).toFixed(0) is '-0'.
*
*/
P.toFixed = function (dp, rm) {
var str, y,
x = this,
Ctor = x.constructor;
if (dp === void 0) {
str = finiteToString(x);
} else {
checkInt32(dp, 0, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
y = finalise(new Ctor(x), dp + x.e + 1, rm);
str = finiteToString(y, false, dp + y.e + 1);
}
// To determine whether to add the minus sign look at the value before it was rounded,
// i.e. look at `x` rather than `y`.
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return an array representing the value of this Decimal as a simple fraction with an integer
* numerator and an integer denominator.
*
* The denominator will be a positive non-zero value less than or equal to the specified maximum
* denominator. If a maximum denominator is not specified, the denominator will be the lowest
* value necessary to represent the number exactly.
*
* [maxD] {number|string|Decimal} Maximum denominator. Integer >= 1 and < Infinity.
*
*/
P.toFraction = function (maxD) {
var d, d0, d1, d2, e, k, n, n0, n1, pr, q, r,
x = this,
xd = x.d,
Ctor = x.constructor;
if (!xd) return new Ctor(x);
n1 = d0 = new Ctor(1);
d1 = n0 = new Ctor(0);
d = new Ctor(d1);
e = d.e = getPrecision(xd) - x.e - 1;
k = e % LOG_BASE;
d.d[0] = mathpow(10, k < 0 ? LOG_BASE + k : k);
if (maxD == null) {
// d is 10**e, the minimum max-denominator needed.
maxD = e > 0 ? d : n1;
} else {
n = new Ctor(maxD);
if (!n.isInt() || n.lt(n1)) throw Error(invalidArgument + n);
maxD = n.gt(d) ? (e > 0 ? d : n1) : n;
}
external = false;
n = new Ctor(digitsToString(xd));
pr = Ctor.precision;
Ctor.precision = e = xd.length * LOG_BASE * 2;
for (;;) {
q = divide(n, d, 0, 1, 1);
d2 = d0.plus(q.times(d1));
if (d2.cmp(maxD) == 1) break;
d0 = d1;
d1 = d2;
d2 = n1;
n1 = n0.plus(q.times(d2));
n0 = d2;
d2 = d;
d = n.minus(q.times(d2));
n = d2;
}
d2 = divide(maxD.minus(d0), d1, 0, 1, 1);
n0 = n0.plus(d2.times(n1));
d0 = d0.plus(d2.times(d1));
n0.s = n1.s = x.s;
// Determine which fraction is closer to x, n0/d0 or n1/d1?
r = divide(n1, d1, e, 1).minus(x).abs().cmp(divide(n0, d0, e, 1).minus(x).abs()) < 1
? [n1, d1] : [n0, d0];
Ctor.precision = pr;
external = true;
return r;
};
/*
* Return a string representing the value of this Decimal in base 16, round to `sd` significant
* digits using rounding mode `rm`.
*
* If the optional `sd` argument is present then return binary exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toHexadecimal = P.toHex = function (sd, rm) {
return toStringBinary(this, 16, sd, rm);
};
/*
* Return a string representing the exact value of this Decimal in a compact base-88 based format.
*
* The number of characters of the string will always be equal to or less than the number of
* characters returned by `toString` or `toExponential` - usually just over half as many.
*
* The original Decimal value can be recreated by passing the string to `Decimal.fromJSON`.
*
* Base 88 alphabet:
* 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%()*+,-./:;=?@[]^_`{|}~
*
* The following 7 printable ASCII characters are not used
* (space) \ " & ' < >
* so the return value is safe for strings, HTML, JSON, and XML.
*
* 0 0 g 16 w 32 M 48 $ 64 ] 80
* 1 1 h 17 x 33 N 49 % 65 ^ 81
* 2 2 i 18 y 34 O 50 ( 66 _ 82
* 3 3 j 19 z 35 P 51 ) 67 ` 83
* 4 4 k 20 A 36 Q 52 * 68 { 84
* 5 5 l 21 B 37 R 53 + 69 | 85
* 6 6 m 22 C 38 S 54 , 70 } 86
* 7 7 n 23 D 39 T 55 - 71 ~ 87
* 8 8 o 24 E 40 U 56 . 72
* 9 9 p 25 F 41 V 57 / 73
* a 10 q 26 G 42 W 58 : 74
* b 11 r 27 H 43 X 59 ; 75
* c 12 s 28 I 44 Y 60 = 76
* d 13 t 29 J 45 Z 61 ? 77
* e 14 u 30 K 46 ! 62 @ 78
* f 15 v 31 L 47 # 63 [ 79
*
* If the return value is just one character, it represents:
* 0-81 [[0, 40][-0, -40]]
* 82 -Infinity
* 83 +Infinity
* 84 NaN
* 85-87 free
*
* 64 32 16 8 4 2 1
* 1 0 1 0 1 1 1 = 87
*
*/
P.toJSON = function () {
var arr, e, i, k, len, n, r, str,
x = this,
isNeg = x.s < 0;
// -Infinity/Infinity/NaN.
if (!x.d) return NUMERALS.charAt(x.s ? isNeg ? 82 : 83 : 84);
e = x.e;
// Small integer.
if (x.d.length === 1 && e < 4 && e >= 0) {
n = x.d[0];
if (n < 2857) {
// One character.
// [[0, 40][-0, -40]]
if (n < 41) return NUMERALS.charAt(isNeg ? n + 41 : n);
// Two characters. High bit of first character unset.
// 0XXXXXX
// 63*88 + 87 = 5631 = 5632 values, 5632/2 = 2816
// [[0, 2815][2816, 5631]] (2816 * 2 = 5632 values)
// [[0, 2815][-0, -2815]]
// [[41, 2856][-41, -2856]]
n -= 41;
if (isNeg) n += 2816;
k = n / 88 | 0;
return NUMERALS.charAt(k) + NUMERALS.charAt(n - k * 88);
}
}
str = digitsToString(x.d);
r = '';
// Values with a small exponent. Set high bit.
// Positive value: 100XXXX
// 1 0 0 {exponent [0, 15] -> [-7, 8]}
if (!isNeg && e <= 8 && e >= -7) {
k = 64 + e + 7;
// Negative value: 1010XXX
// 1 0 1 0 {exponent [0, 7] -> [-3, 4]}
} else if (isNeg && e <= 4 && e >= -3) {
k = 64 + 16 + e + 3;
// Integer without trailing zeros: 0X00000
// 0 {is negative} 0 0 0 0 0
} else if (str.length === e + 1) {
k = 32 * isNeg;
// All remaining values: 0XXXXXX
// Result will have at least 3 characters.
// 0 {is negative} {is exponent negative} {exponent character count [1, 15]}
} else {
k = 32 * isNeg + 16 * (e < 0);
e = Math.abs(e);
// One character to represent the exponent.
if (e < 88) {
k += 1;
r = NUMERALS.charAt(e);
// Two characters to represent the exponent.
// 87*88 + 87 = 7743
} else if (e < 7744) {
k += 2;
n = e / 88 | 0;
r = NUMERALS.charAt(n) + NUMERALS.charAt(e - n * 88);
// More than two characters to represent the exponent.
} else {
arr = convertBase(String(e), 10, 88);
len = arr.length;
k += len;
for (i = 0; i < len; i++) r += NUMERALS.charAt(arr[i]);
}
}
// At this point r contains the characters in base 88 representing the exponent value.
// Prepend the first character, which describes the sign, the exponent sign, and the number of
// characters that follow which represent the exponent value.
r = NUMERALS.charAt(k) + r;
arr = convertBase(str, 10, 88);
len = arr.length;
// Add the base 88 characters that represent the significand.
for (i = 0; i < len; i++) r += NUMERALS.charAt(arr[i]);
return r;
};
/*
* Returns a new Decimal whose value is the nearest multiple of the magnitude of `y` to the value
* of this Decimal.
*
* If the value of this Decimal is equidistant from two multiples of `y`, the rounding mode `rm`,
* or `Decimal.rounding` if `rm` is omitted, determines the direction of the nearest multiple.
*
* In the context of this method, rounding mode 4 (ROUND_HALF_UP) is the same as rounding mode 0
* (ROUND_UP), and so on.
*
* The return value will always have the same sign as this Decimal, unless either this Decimal
* or `y` is NaN, in which case the return value will be also be NaN.
*
* The return value is not affected by the value of `precision`.
*
* y {number|string|Decimal} The magnitude to round to a multiple of.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toNearest() rounding mode not an integer: {rm}'
* 'toNearest() rounding mode out of range: {rm}'
*
*/
P.toNearest = function (y, rm) {
var x = this,
Ctor = x.constructor;
x = new Ctor(x);
if (y == null) {
// If x is not finite, return x.
if (!x.d) return x;
y = new Ctor(1);
rm = Ctor.rounding;
} else {
y = new Ctor(y);
if (rm !== void 0) checkInt32(rm, 0, 8);
// If x is not finite, return x if y is not NaN, else NaN.
if (!x.d) return y.s ? x : y;
// If y is not finite, return Infinity with the sign of x if y is Infinity, else NaN.
if (!y.d) {
if (y.s) y.s = x.s;
return y;
}
}
// If y is not zero, calculate the nearest multiple of y to x.
if (y.d[0]) {
external = false;
if (rm < 4) rm = [4, 5, 7, 8][rm];
x = divide(x, y, 0, rm, 1).times(y);
external = true;
finalise(x);
// If y is zero, return zero with the sign of x.
} else {
y.s = x.s;
x = y;
}
return x;
};
/*
* Return the value of this Decimal converted to a number primitive.
* Zero keeps its sign.
*
*/
P.toNumber = function () {
return +this;
};
/*
* Return a string representing the value of this Decimal in base 8, round to `sd` significant
* digits using rounding mode `rm`.
*
* If the optional `sd` argument is present then return binary exponential notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toOctal = function (sd, rm) {
return toStringBinary(this, 8, sd, rm);
};
/*
* Return a new Decimal whose value is the value of this Decimal raised to the power `y`, rounded
* to `precision` significant digits using rounding mode `rounding`.
*
* ECMAScript compliant.
*
* pow(x, NaN) = NaN
* pow(x, ±0) = 1
* pow(NaN, non-zero) = NaN
* pow(abs(x) > 1, +Infinity) = +Infinity
* pow(abs(x) > 1, -Infinity) = +0
* pow(abs(x) == 1, ±Infinity) = NaN
* pow(abs(x) < 1, +Infinity) = +0
* pow(abs(x) < 1, -Infinity) = +Infinity
* pow(+Infinity, y > 0) = +Infinity
* pow(+Infinity, y < 0) = +0
* pow(-Infinity, odd integer > 0) = -Infinity
* pow(-Infinity, even integer > 0) = +Infinity
* pow(-Infinity, odd integer < 0) = -0
* pow(-Infinity, even integer < 0) = +0
* pow(+0, y > 0) = +0
* pow(+0, y < 0) = +Infinity
* pow(-0, odd integer > 0) = -0
* pow(-0, even integer > 0) = +0
* pow(-0, odd integer < 0) = -Infinity
* pow(-0, even integer < 0) = +Infinity
* pow(finite x < 0, finite non-integer) = NaN
*
* For non-integer or very large exponents pow(x, y) is calculated using
*
* x^y = exp(y*ln(x))
*
* Assuming the first 15 rounding digits are each equally likely to be any digit 0-9, the
* probability of an incorrectly rounded result
* P([49]9{14} | [50]0{14}) = 2 * 0.2 * 10^-14 = 4e-15 = 1/2.5e+14
* i.e. 1 in 250,000,000,000,000
*
* If a result is incorrectly rounded the maximum error will be 1 ulp (unit in last place).
*
* y {number|string|Decimal} The power to which to raise this Decimal.
*
*/
P.toPower = P.pow = function (y) {
var e, k, pr, r, rm, sign, yIsInt,
x = this,
Ctor = x.constructor,
yn = +(y = new Ctor(y));
// Either ±Infinity, NaN or ±0?
if (!x.d || !y.d || !x.d[0] || !y.d[0]) return new Ctor(mathpow(+x, yn));
x = new Ctor(x);
if (x.eq(1)) return x;
pr = Ctor.precision;
rm = Ctor.rounding;
if (y.eq(1)) return finalise(x, pr, rm);
e = mathfloor(y.e / LOG_BASE);
k = y.d.length - 1;
yIsInt = e >= k;
sign = x.s;
if (!yIsInt) {
if (sign < 0) return new Ctor(NaN);
// If y is a small integer use the 'exponentiation by squaring' algorithm.
} else if ((k = yn < 0 ? -yn : yn) <= MAX_SAFE_INTEGER) {
r = intPow(Ctor, x, k, pr);
return y.s < 0 ? new Ctor(1).div(r) : finalise(r, pr, rm);
}
// Result is negative if x is negative and the last digit of integer y is odd.
sign = sign < 0 && y.d[Math.max(e, k)] & 1 ? -1 : 1;
// Estimate result exponent.
// x^y = 10^e, where e = y * log10(x)
// log10(x) = log10(x_significand) + x_exponent
// log10(x_significand) = ln(x_significand) / ln(10)
k = mathpow(+x, yn);
e = k == 0 || !isFinite(k)
? mathfloor(yn * (Math.log('0.' + digitsToString(x.d)) / Math.LN10 + x.e + 1))
: new Ctor(k + '').e;
// Estimate may be incorrect e.g. x: 0.999999999999999999, y: 2.29, e: 0, r.e: -1.
// Overflow/underflow?
if (e > Ctor.maxE + 1 || e < Ctor.minE - 1) return new Ctor(e > 0 ? sign / 0 : 0);
external = false;
Ctor.rounding = x.s = 1;
// Estimate the extra guard digits needed to ensure five correct rounding digits from
// naturalLogarithm(x). Example of failure without these extra digits (precision: 10):
// new Decimal(2.32456).pow('2087987436534566.46411')
// should be 1.162377823e+764914905173815, but is 1.162355823e+764914905173815
k = Math.min(12, (e + '').length);
// r = x^y = exp(y*ln(x))
r = naturalExponential(y.times(naturalLogarithm(x, pr + k)), pr);
// Truncate to the required precision plus five rounding digits.
r = finalise(r, pr + 5, 1);
// If the rounding digits are [49]9999 or [50]0000 increase the precision by 10 and recalculate
// the result.
if (checkRoundingDigits(r.d, pr, rm)) {
e = pr + 10;
// Truncate to the increased precision plus five rounding digits.
r = finalise(naturalExponential(y.times(naturalLogarithm(x, e + k)), e), e + 5, 1);
// Check for 14 nines from the 2nd rounding digit (the first rounding digit may be 4 or 9).
if (+digitsToString(r.d).slice(pr + 1, pr + 15) + 1 == 1e14) {
r = finalise(r, pr + 1, 0);
}
}
r.s = sign;
external = true;
Ctor.rounding = rm;
return finalise(r, pr, rm);
};
/*
* Return a string representing the value of this Decimal rounded to `sd` significant digits
* using rounding mode `rounding`.
*
* Return exponential notation if `sd` is less than the number of digits necessary to represent
* the integer part of the value in normal notation.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
*/
P.toPrecision = function (sd, rm) {
var str,
x = this,
Ctor = x.constructor;
if (sd === void 0) {
str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
} else {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
x = finalise(new Ctor(x), sd, rm);
str = finiteToString(x, sd <= x.e || x.e <= Ctor.toExpNeg, sd);
}
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return a new Decimal whose value is the value of this Decimal rounded to a maximum of `sd`
* significant digits using rounding mode `rm`, or to `precision` and `rounding` respectively if
* omitted.
*
* [sd] {number} Significant digits. Integer, 1 to MAX_DIGITS inclusive.
* [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
*
* 'toSD() digits out of range: {sd}'
* 'toSD() digits not an integer: {sd}'
* 'toSD() rounding mode not an integer: {rm}'
* 'toSD() rounding mode out of range: {rm}'
*
*/
P.toSignificantDigits = P.toSD = function (sd, rm) {
var x = this,
Ctor = x.constructor;
if (sd === void 0) {
sd = Ctor.precision;
rm = Ctor.rounding;
} else {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
}
return finalise(new Ctor(x), sd, rm);
};
/*
* Return a string representing the value of this Decimal.
*
* Return exponential notation if this Decimal has a positive exponent equal to or greater than
* `toExpPos`, or a negative exponent equal to or less than `toExpNeg`.
*
*/
P.toString = function () {
var x = this,
Ctor = x.constructor,
str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
return x.isNeg() && !x.isZero() ? '-' + str : str;
};
/*
* Return a new Decimal whose value is the value of this Decimal truncated to a whole number.
*
*/
P.truncated = P.trunc = function () {
return finalise(new this.constructor(this), this.e + 1, 1);
};
/*
* Return a string representing the value of this Decimal.
* Unlike `toString`, negative zero will include the minus sign.
*
*/
P.valueOf = function () {
var x = this,
Ctor = x.constructor,
str = finiteToString(x, x.e <= Ctor.toExpNeg || x.e >= Ctor.toExpPos);
return x.isNeg() ? '-' + str : str;
};
/*
// Add aliases to match BigDecimal method names.
// P.add = P.plus;
P.subtract = P.minus;
P.multiply = P.times;
P.divide = P.div;
P.remainder = P.mod;
P.compareTo = P.cmp;
P.negate = P.neg;
*/
// Helper functions for Decimal.prototype (P) and/or Decimal methods, and their callers.
/*
* digitsToString P.cubeRoot, P.logarithm, P.squareRoot, P.toFraction, P.toJSON,
* P.toPower, finiteToString, naturalExponential, naturalLogarithm
* checkInt32 P.toDecimalPlaces, P.toExponential, P.toFixed, P.toNearest,
* P.toPrecision, P.toSignificantDigits, toStringBinary, random
* checkRoundingDigits P.logarithm, P.toPower, naturalExponential, naturalLogarithm
* convertBase P.toJSON, toStringBinary, fromJSON, parseOther
* cos P.cos
* divide P.atanh, P.cubeRoot, P.dividedBy, P.dividedToIntegerBy,
* P.logarithm, P.modulo, P.squareRoot, P.tan, P.tanh, P.toFraction,
* P.toNearest, toStringBinary, naturalExponential, naturalLogarithm,
* taylorSeries, atan2, parseOther
* finalise P.absoluteValue, P.atan, P.atanh, P.ceil, P.cos, P.cosh,
* P.cubeRoot, P.dividedToIntegerBy, P.floor, P.logarithm, P.minus,
* P.modulo, P.negated, P.plus, P.round, P.sin, P.sinh, P.squareRoot,
* P.tan, P.times, P.toDecimalPlaces, P.toExponential, P.toFixed,
* P.toNearest, P.toPower, P.toPrecision, P.toSignificantDigits,
* P.truncated, divide, getLn10, getPi, naturalExponential,
* naturalLogarithm, ceil, floor, round, trunc
* finiteToString P.toExponential, P.toFixed, P.toPrecision, P.toString, P.valueOf,
* toStringBinary
* getBase10Exponent P.minus, P.plus, P.times, parseOther
* getLn10 P.logarithm, naturalLogarithm
* getPi P.acos, P.asin, P.atan, toLessThanHalfPi, atan2
* getPrecision P.precision, P.toFraction
* getZeroString digitsToString, finiteToString
* intPow P.toPower, parseOther
* isOdd toLessThanHalfPi
* maxOrMin max, min
* naturalExponential P.naturalExponential, P.toPower
* naturalLogarithm P.acosh, P.asinh, P.atanh, P.logarithm, P.naturalLogarithm,
* P.toPower, naturalExponential
* nonFiniteToString finiteToString, toStringBinary
* parseDecimal Decimal
* parseOther Decimal
* sin P.sin
* taylorSeries P.cosh, P.sinh, cos, sin
* toLessThanHalfPi P.cos, P.sin
* toStringBinary P.toBinary, P.toHexadecimal, P.toOctal
* truncate intPow
*
* Throws: P.logarithm, P.precision, P.toFraction, checkInt32, getLn10, getPi,
* naturalLogarithm, config, fromJSON, parseOther, random, Decimal *
*/
function digitsToString(d) {
var i, k, ws,
indexOfLastWord = d.length - 1,
str = '',
w = d[0];
if (indexOfLastWord > 0) {
str += w;
for (i = 1; i < indexOfLastWord; i++) {
ws = d[i] + '';
k = LOG_BASE - ws.length;
if (k) str += getZeroString(k);
str += ws;
}
w = d[i];
ws = w + '';
k = LOG_BASE - ws.length;
if (k) str += getZeroString(k);
} else if (w === 0) {
return '0';
}
// Remove trailing zeros of last w.
for (; w % 10 === 0;) w /= 10;
return str + w;
}
function checkInt32(i, min, max) {
if (i !== ~~i || i < min || i > max) {
throw Error(invalidArgument + i);
}
}
/*
* Check 5 rounding digits if `repeating` is null, 4 otherwise.
* `repeating == null` if caller is `log` or `pow`,
* `repeating != null` if caller is `naturalLogarithm` or `naturalExponential`.
*/
function checkRoundingDigits(d, i, rm, repeating) {
var di, k, r, rd;
// Get the length of the first word of the array d.
for (k = d[0]; k >= 10; k /= 10) --i;
// Is the rounding digit in the first word of d?
if (--i < 0) {
i += LOG_BASE;
di = 0;
} else {
di = Math.ceil((i + 1) / LOG_BASE);
i %= LOG_BASE;
}
// i is the index (0 - 6) of the rounding digit.
// E.g. if within the word 3487563 the first rounding digit is 5,
// then i = 4, k = 1000, rd = 3487563 % 1000 = 563
k = mathpow(10, LOG_BASE - i);
rd = d[di] % k | 0;
if (repeating == null) {
if (i < 3) {
if (i == 0) rd = rd / 100 | 0;
else if (i == 1) rd = rd / 10 | 0;
r = rm < 4 && rd == 99999 || rm > 3 && rd == 49999 || rd == 50000 || rd == 0;
} else {
r = (rm < 4 && rd + 1 == k || rm > 3 && rd + 1 == k / 2) &&
(d[di + 1] / k / 100 | 0) == mathpow(10, i - 2) - 1 ||
(rd == k / 2 || rd == 0) && (d[di + 1] / k / 100 | 0) == 0;
}
} else {
if (i < 4) {
if (i == 0) rd = rd / 1000 | 0;
else if (i == 1) rd = rd / 100 | 0;
else if (i == 2) rd = rd / 10 | 0;
r = (repeating || rm < 4) && rd == 9999 || !repeating && rm > 3 && rd == 4999;
} else {
r = ((repeating || rm < 4) && rd + 1 == k ||
(!repeating && rm > 3) && rd + 1 == k / 2) &&
(d[di + 1] / k / 1000 | 0) == mathpow(10, i - 3) - 1;
}
}
return r;
}
// Convert string of `baseIn` to an array of numbers of `baseOut`.
// Eg. convertBase('255', 10, 16) returns [15, 15].
// Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
function convertBase(str, baseIn, baseOut) {
var j,
arr = [0],
arrL,
i = 0,
strL = str.length;
for (; i < strL;) {
for (arrL = arr.length; arrL--;) arr[arrL] *= baseIn;
arr[0] += NUMERALS.indexOf(str.charAt(i++));
for (j = 0; j < arr.length; j++) {
if (arr[j] > baseOut - 1) {
if (arr[j + 1] === void 0) arr[j + 1] = 0;
arr[j + 1] += arr[j] / baseOut | 0;
arr[j] %= baseOut;
}
}
}
return arr.reverse();
}
/*
* cos(x) = 1 - x^2/2! + x^4/4! - ...
* |x| < pi/2
*
*/
function cosine(Ctor, x) {
var k, y,
len = x.d.length;
// Argument reduction: cos(4x) = 8*(cos^4(x) - cos^2(x)) + 1
// i.e. cos(x) = 8*(cos^4(x/4) - cos^2(x/4)) + 1
// Estimate the optimum number of times to use the argument reduction.
if (len < 32) {
k = Math.ceil(len / 3);
y = Math.pow(4, -k).toString();
} else {
k = 16;
y = '2.3283064365386962890625e-10';
}
Ctor.precision += k;
x = taylorSeries(Ctor, 1, x.times(y), new Ctor(1));
// Reverse argument reduction
for (var i = k; i--;) {
var cos2x = x.times(x);
x = cos2x.times(cos2x).minus(cos2x).times(8).plus(1);
}
Ctor.precision -= k;
return x;
}
/*
* Perform division in the specified base.
*/
var divide = (function () {
// Assumes non-zero x and k, and hence non-zero result.
function multiplyInteger(x, k, base) {
var temp,
carry = 0,
i = x.length;
for (x = x.slice(); i--;) {
temp = x[i] * k + carry;
x[i] = temp % base | 0;
carry = temp / base | 0;
}
if (carry) x.unshift(carry);
return x;
}
function compare(a, b, aL, bL) {
var i, r;
if (aL != bL) {
r = aL > bL ? 1 : -1;
} else {
for (i = r = 0; i < aL; i++) {
if (a[i] != b[i]) {
r = a[i] > b[i] ? 1 : -1;
break;
}
}
}
return r;
}
function subtract(a, b, aL, base) {
var i = 0;
// Subtract b from a.
for (; aL--;) {
a[aL] -= i;
i = a[aL] < b[aL] ? 1 : 0;
a[aL] = i * base + a[aL] - b[aL];
}
// Remove leading zeros.
for (; !a[0] && a.length > 1;) a.shift();
}
return function (x, y, pr, rm, dp, base) {
var cmp, e, i, k, logBase, more, prod, prodL, q, qd, rem, remL, rem0, sd, t, xi, xL, yd0,
yL, yz,
Ctor = x.constructor,
sign = x.s == y.s ? 1 : -1,
xd = x.d,
yd = y.d;
// Either NaN, Infinity or 0?
if (!xd || !xd[0] || !yd || !yd[0]) {
return new Ctor(// Return NaN if either NaN, or both Infinity or 0.
!x.s || !y.s || (xd ? yd && xd[0] == yd[0] : !yd) ? NaN :
// Return ±0 if x is 0 or y is ±Infinity, or return ±Infinity as y is 0.
xd && xd[0] == 0 || !yd ? sign * 0 : sign / 0);
}
if (base) {
logBase = 1;
e = x.e - y.e;
} else {
base = BASE;
logBase = LOG_BASE;
e = mathfloor(x.e / logBase) - mathfloor(y.e / logBase);
}
yL = yd.length;
xL = xd.length;
q = new Ctor(sign);
qd = q.d = [];
// Result exponent may be one less than e.
// The digit array of a Decimal from toStringBinary may have trailing zeros.
for (i = 0; yd[i] == (xd[i] || 0); i++);
if (yd[i] > (xd[i] || 0)) e--;
if (pr == null) {
sd = pr = Ctor.precision;
rm = Ctor.rounding;
} else if (dp) {
sd = pr + (x.e - y.e) + 1;
} else {
sd = pr;
}
if (sd < 0) {
qd.push(1);
more = true;
} else {
// Convert precision in number of base 10 digits to base 1e7 digits.
sd = sd / logBase + 2 | 0;
i = 0;
// divisor < 1e7
if (yL == 1) {
k = 0;
yd = yd[0];
sd++;
// k is the carry.
for (; (i < xL || k) && sd--; i++) {
t = k * base + (xd[i] || 0);
qd[i] = t / yd | 0;
k = t % yd | 0;
}
more = k || i < xL;
// divisor >= 1e7
} else {
// Normalise xd and yd so highest order digit of yd is >= base/2
k = base / (yd[0] + 1) | 0;
if (k > 1) {
yd = multiplyInteger(yd, k, base);
xd = multiplyInteger(xd, k, base);
yL = yd.length;
xL = xd.length;
}
xi = yL;
rem = xd.slice(0, yL);
remL = rem.length;
// Add zeros to make remainder as long as divisor.
for (; remL < yL;) rem[remL++] = 0;
yz = yd.slice();
yz.unshift(0);
yd0 = yd[0];
if (yd[1] >= base / 2) ++yd0;
do {
k = 0;
// Compare divisor and remainder.
cmp = compare(yd, rem, yL, remL);
// If divisor < remainder.
if (cmp < 0) {
// Calculate trial digit, k.
rem0 = rem[0];
if (yL != remL) rem0 = rem0 * base + (rem[1] || 0);
// k will be how many times the divisor goes into the current remainder.
k = rem0 / yd0 | 0;
// Algorithm:
// 1. product = divisor * trial digit (k)
// 2. if product > remainder: product -= divisor, k--
// 3. remainder -= product
// 4. if product was < remainder at 2:
// 5. compare new remainder and divisor
// 6. If remainder > divisor: remainder -= divisor, k++
if (k > 1) {
if (k >= base) k = base - 1;
// product = divisor * trial digit.
prod = multiplyInteger(yd, k, base);
prodL = prod.length;
remL = rem.length;
// Compare product and remainder.
cmp = compare(prod, rem, prodL, remL);
// product > remainder.
if (cmp == 1) {
k--;
// Subtract divisor from product.
subtract(prod, yL < prodL ? yz : yd, prodL, base);
}
} else {
// cmp is -1.
// If k is 0, there is no need to compare yd and rem again below, so change cmp to 1
// to avoid it. If k is 1 there is a need to compare yd and rem again below.
if (k == 0) cmp = k = 1;
prod = yd.slice();
}
prodL = prod.length;
if (prodL < remL) prod.unshift(0);
// Subtract product from remainder.
subtract(rem, prod, remL, base);
// If product was < previous remainder.
if (cmp == -1) {
remL = rem.length;
// Compare divisor and new remainder.
cmp = compare(yd, rem, yL, remL);
// If divisor < new remainder, subtract divisor from remainder.
if (cmp < 1) {
k++;
// Subtract divisor from remainder.
subtract(rem, yL < remL ? yz : yd, remL, base);
}
}
remL = rem.length;
} else if (cmp === 0) {
k++;
rem = [0];
} // if cmp === 1, k will be 0
// Add the next digit, k, to the result array.
qd[i++] = k;
// Update the remainder.
if (cmp && rem[0]) {
rem[remL++] = xd[xi] || 0;
} else {
rem = [xd[xi]];
remL = 1;
}
} while ((xi++ < xL || rem[0] !== void 0) && sd--);
more = rem[0] !== void 0;
}
// Leading zero?
if (!qd[0]) qd.shift();
}
// logBase is 1 when divide is being used for base conversion.
if (logBase == 1) {
q.e = e;
inexact = more;
} else {
// To calculate q.e, first get the number of digits of qd[0].
for (i = 1, k = qd[0]; k >= 10; k /= 10) i++;
q.e = i + e * logBase - 1;
finalise(q, dp ? pr + q.e + 1 : pr, rm, more);
}
return q;
};
})();
/*
* Round `x` to `sd` significant digits using rounding mode `rm`.
* Check for over/under-flow.
*/
function finalise(x, sd, rm, isTruncated) {
var digits, i, j, k, rd, roundUp, w, xd, xdi,
Ctor = x.constructor;
// Don't round if sd is null or undefined.
out: if (sd != null) {
xd = x.d;
// Infinity/NaN.
if (!xd) return x;
// rd: the rounding digit, i.e. the digit after the digit that may be rounded up.
// w: the word of xd containing rd, a base 1e7 number.
// xdi: the index of w within xd.
// digits: the number of digits of w.
// i: what would be the index of rd within w if all the numbers were 7 digits long (i.e. if
// they had leading zeros)
// j: if > 0, the actual index of rd within w (if < 0, rd is a leading zero).
// Get the length of the first word of the digits array xd.
for (digits = 1, k = xd[0]; k >= 10; k /= 10) digits++;
i = sd - digits;
// Is the rounding digit in the first word of xd?
if (i < 0) {
i += LOG_BASE;
j = sd;
w = xd[xdi = 0];
// Get the rounding digit at index j of w.
rd = w / mathpow(10, digits - j - 1) % 10 | 0;
} else {
xdi = Math.ceil((i + 1) / LOG_BASE);
k = xd.length;
if (xdi >= k) {
if (isTruncated) {
// Needed by `naturalExponential`, `naturalLogarithm` and `squareRoot`.
for (; k++ <= xdi;) xd.push(0);
w = rd = 0;
digits = 1;
i %= LOG_BASE;
j = i - LOG_BASE + 1;
} else {
break out;
}
} else {
w = k = xd[xdi];
// Get the number of digits of w.
for (digits = 1; k >= 10; k /= 10) digits++;
// Get the index of rd within w.
i %= LOG_BASE;
// Get the index of rd within w, adjusted for leading zeros.
// The number of leading zeros of w is given by LOG_BASE - digits.
j = i - LOG_BASE + digits;
// Get the rounding digit at index j of w.
rd = j < 0 ? 0 : w / mathpow(10, digits - j - 1) % 10 | 0;
}
}
// Are there any non-zero digits after the rounding digit?
isTruncated = isTruncated || sd < 0 ||
xd[xdi + 1] !== void 0 || (j < 0 ? w : w % mathpow(10, digits - j - 1));
// The expression `w % mathpow(10, digits - j - 1)` returns all the digits of w to the right
// of the digit at (left-to-right) index j, e.g. if w is 908714 and j is 2, the expression
// will give 714.
roundUp = rm < 4
? (rd || isTruncated) && (rm == 0 || rm == (x.s < 0 ? 3 : 2))
: rd > 5 || rd == 5 && (rm == 4 || isTruncated || rm == 6 &&
// Check whether the digit to the left of the rounding digit is odd.
((i > 0 ? j > 0 ? w / mathpow(10, digits - j) : 0 : xd[xdi - 1]) % 10) & 1 ||
rm == (x.s < 0 ? 8 : 7));
if (sd < 1 || !xd[0]) {
xd.length = 0;
if (roundUp) {
// Convert sd to decimal places.
sd -= x.e + 1;
// 1, 0.1, 0.01, 0.001, 0.0001 etc.
xd[0] = mathpow(10, (LOG_BASE - sd % LOG_BASE) % LOG_BASE);
x.e = -sd || 0;
} else {
// Zero.
xd[0] = x.e = 0;
}
return x;
}
// Remove excess digits.
if (i == 0) {
xd.length = xdi;
k = 1;
xdi--;
} else {
xd.length = xdi + 1;
k = mathpow(10, LOG_BASE - i);
// E.g. 56700 becomes 56000 if 7 is the rounding digit.
// j > 0 means i > number of leading zeros of w.
xd[xdi] = j > 0 ? (w / mathpow(10, digits - j) % mathpow(10, j) | 0) * k : 0;
}
if (roundUp) {
for (;;) {
// Is the digit to be rounded up in the first word of xd?
if (xdi == 0) {
// i will be the length of xd[0] before k is added.
for (i = 1, j = xd[0]; j >= 10; j /= 10) i++;
j = xd[0] += k;
for (k = 1; j >= 10; j /= 10) k++;
// if i != k the length has increased.
if (i != k) {
x.e++;
if (xd[0] == BASE) xd[0] = 1;
}
break;
} else {
xd[xdi] += k;
if (xd[xdi] != BASE) break;
xd[xdi--] = 0;
k = 1;
}
}
}
// Remove trailing zeros.
for (i = xd.length; xd[--i] === 0;) xd.pop();
}
if (external) {
// Overflow?
if (x.e > Ctor.maxE) {
// Infinity.
x.d = null;
x.e = NaN;
// Underflow?
} else if (x.e < Ctor.minE) {
// Zero.
x.e = 0;
x.d = [0];
// Ctor.underflow = true;
} // else Ctor.underflow = false;
}
return x;
}
function finiteToString(x, isExp, sd) {
if (!x.isFinite()) return nonFiniteToString(x);
var k,
e = x.e,
str = digitsToString(x.d),
len = str.length;
if (isExp) {
if (sd && (k = sd - len) > 0) {
str = str.charAt(0) + '.' + str.slice(1) + getZeroString(k);
} else if (len > 1) {
str = str.charAt(0) + '.' + str.slice(1);
}
str = str + (x.e < 0 ? 'e' : 'e+') + x.e;
} else if (e < 0) {
str = '0.' + getZeroString(-e - 1) + str;
if (sd && (k = sd - len) > 0) str += getZeroString(k);
} else if (e >= len) {
str += getZeroString(e + 1 - len);
if (sd && (k = sd - e - 1) > 0) str = str + '.' + getZeroString(k);
} else {
if ((k = e + 1) < len) str = str.slice(0, k) + '.' + str.slice(k);
if (sd && (k = sd - len) > 0) {
if (e + 1 === len) str += '.';
str += getZeroString(k);
}
}
return str;
}
// Calculate the base 10 exponent from the base 1e7 exponent.
function getBase10Exponent(digits, e) {
// First get the number of digits of the first word of the digits array.
for (var i = 1, w = digits[0]; w >= 10; w /= 10) i++;
return i + e * LOG_BASE - 1;
}
function getLn10(Ctor, sd, pr) {
if (sd > LN10_PRECISION) {
// Reset global state in case the exception is caught.
external = true;
if (pr) Ctor.precision = pr;
throw Error(precisionLimitExceeded);
}
return finalise(new Ctor(LN10), sd, 1, true);
}
function getPi(Ctor, sd, rm) {
if (sd > PI_PRECISION) throw Error(precisionLimitExceeded);
return finalise(new Ctor(PI), sd, rm, true);
}
function getPrecision(digits) {
var w = digits.length - 1,
len = w * LOG_BASE + 1;
w = digits[w];
// If non-zero...
if (w) {
// Subtract the number of trailing zeros of the last word.
for (; w % 10 == 0; w /= 10) len--;
// Add the number of digits of the first word.
for (w = digits[0]; w >= 10; w /= 10) len++;
}
return len;
}
function getZeroString(k) {
var zs = '';
for (; k--;) zs += '0';
return zs;
}
/*
* Return a new Decimal whose value is the value of Decimal `x` to the power `n`, where `n` is an
* integer of type number.
*
* Implements 'exponentiation by squaring'. Called by `pow` and `parseOther`.
*
*/
function intPow(Ctor, x, n, pr) {
var isTruncated,
r = new Ctor(1),
// Max n of 9007199254740991 takes 53 loop iterations.
// Maximum digits array length; leaves [28, 34] guard digits.
k = Math.ceil(pr / LOG_BASE + 4);
external = false;
for (;;) {
if (n % 2) {
r = r.times(x);
if (truncate(r.d, k)) isTruncated = true;
}
n = mathfloor(n / 2);
if (n === 0) {
// To ensure correct rounding when r.d is truncated, increment the last word if it is zero.
n = r.d.length - 1;
if (isTruncated && r.d[n] === 0) ++r.d[n];
break;
}
x = x.times(x);
truncate(x.d, k);
}
external = true;
return r;
}
function isOdd(n) {
return n.d[n.d.length - 1] & 1;
}
/*
* Handle `max` and `min`. `ltgt` is 'lt' or 'gt'.
*/
function maxOrMin(Ctor, args, ltgt) {
var y,
x = new Ctor(args[0]),
i = 0;
for (; ++i < args.length;) {
y = new Ctor(args[i]);
if (!y.s) {
x = y;
break;
} else if (x[ltgt](y)) {
x = y;
}
}
return x;
}
/*
* Return a new Decimal whose value is the natural exponential of `x` rounded to `sd` significant
* digits.
*
* Taylor/Maclaurin series.
*
* exp(x) = x^0/0! + x^1/1! + x^2/2! + x^3/3! + ...
*
* Argument reduction:
* Repeat x = x / 32, k += 5, until |x| < 0.1
* exp(x) = exp(x / 2^k)^(2^k)
*
* Previously, the argument was initially reduced by
* exp(x) = exp(r) * 10^k where r = x - k * ln10, k = floor(x / ln10)
* to first put r in the range [0, ln10], before dividing by 32 until |x| < 0.1, but this was
* found to be slower than just dividing repeatedly by 32 as above.
*
* Max integer argument: exp('20723265836946413') = 6.3e+9000000000000000
* Min integer argument: exp('-20723265836946411') = 1.2e-9000000000000000
* (Math object integer min/max: Math.exp(709) = 8.2e+307, Math.exp(-745) = 5e-324)
*
* exp(Infinity) = Infinity
* exp(-Infinity) = 0
* exp(NaN) = NaN
* exp(±0) = 1
*
* exp(x) is non-terminating for any finite, non-zero x.
*
* The result will always be correctly rounded.
*
*/
function naturalExponential(x, sd) {
var denominator, guard, j, pow, sum, t, wpr,
rep = 0,
i = 0,
k = 0,
Ctor = x.constructor,
rm = Ctor.rounding,
pr = Ctor.precision;
// 0/NaN/Infinity?
if (!x.d || !x.d[0] || x.e > 17) {
return new Ctor(x.d
? !x.d[0] ? 1 : x.s < 0 ? 0 : 1 / 0
: x.s ? x.s < 0 ? 0 : x : 0 / 0);
}
if (sd == null) {
external = false;
wpr = pr;
} else {
wpr = sd;
}
t = new Ctor(0.03125);
// while abs(x) >= 0.1
while (x.e > -2) {
// x = x / 2^5
x = x.times(t);
k += 5;
}
// Use 2 * log10(2^k) + 5 (empirically derived) to estimate the increase in precision
// necessary to ensure the first 4 rounding digits are correct.
guard = Math.log(mathpow(2, k)) / Math.LN10 * 2 + 5 | 0;
wpr += guard;
denominator = pow = sum = new Ctor(1);
Ctor.precision = wpr;
for (;;) {
pow = finalise(pow.times(x), wpr, 1);
denominator = denominator.times(++i);
t = sum.plus(divide(pow, denominator, wpr, 1));
if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
j = k;
while (j--) sum = finalise(sum.times(sum), wpr, 1);
// Check to see if the first 4 rounding digits are [49]999.
// If so, repeat the summation with a higher precision, otherwise
// e.g. with precision: 18, rounding: 1
// exp(18.404272462595034083567793919843761) = 98372560.1229999999 (should be 98372560.123)
// `wpr - guard` is the index of first rounding digit.
if (sd == null) {
if (rep < 3 && checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
Ctor.precision = wpr += 10;
denominator = pow = t = new Ctor(1);
i = 0;
rep++;
} else {
return finalise(sum, Ctor.precision = pr, rm, external = true);
}
} else {
Ctor.precision = pr;
return sum;
}
}
sum = t;
}
}
/*
* Return a new Decimal whose value is the natural logarithm of `x` rounded to `sd` significant
* digits.
*
* ln(-n) = NaN
* ln(0) = -Infinity
* ln(-0) = -Infinity
* ln(1) = 0
* ln(Infinity) = Infinity
* ln(-Infinity) = NaN
* ln(NaN) = NaN
*
* ln(n) (n != 1) is non-terminating.
*
*/
function naturalLogarithm(y, sd) {
var c, c0, denominator, e, numerator, rep, sum, t, wpr, x1, x2,
n = 1,
guard = 10,
x = y,
xd = x.d,
Ctor = x.constructor,
rm = Ctor.rounding,
pr = Ctor.precision;
// Is x negative or Infinity, NaN, 0 or 1?
if (x.s < 0 || !xd || !xd[0] || !x.e && xd[0] == 1 && xd.length == 1) {
return new Ctor(xd && !xd[0] ? -1 / 0 : x.s != 1 ? NaN : xd ? 0 : x);
}
if (sd == null) {
external = false;
wpr = pr;
} else {
wpr = sd;
}
Ctor.precision = wpr += guard;
c = digitsToString(xd);
c0 = c.charAt(0);
if (Math.abs(e = x.e) < 1.5e15) {
// Argument reduction.
// The series converges faster the closer the argument is to 1, so using
// ln(a^b) = b * ln(a), ln(a) = ln(a^b) / b
// multiply the argument by itself until the leading digits of the significand are 7, 8, 9,
// 10, 11, 12 or 13, recording the number of multiplications so the sum of the series can
// later be divided by this number, then separate out the power of 10 using
// ln(a*10^b) = ln(a) + b*ln(10).
// max n is 21 (gives 0.9, 1.0 or 1.1) (9e15 / 21 = 4.2e14).
//while (c0 < 9 && c0 != 1 || c0 == 1 && c.charAt(1) > 1) {
// max n is 6 (gives 0.7 - 1.3)
while (c0 < 7 && c0 != 1 || c0 == 1 && c.charAt(1) > 3) {
x = x.times(y);
c = digitsToString(x.d);
c0 = c.charAt(0);
n++;
}
e = x.e;
if (c0 > 1) {
x = new Ctor('0.' + c);
e++;
} else {
x = new Ctor(c0 + '.' + c.slice(1));
}
} else {
// The argument reduction method above may result in overflow if the argument y is a massive
// number with exponent >= 1500000000000000 (9e15 / 6 = 1.5e15), so instead recall this
// function using ln(x*10^e) = ln(x) + e*ln(10).
t = getLn10(Ctor, wpr + 2, pr).times(e + '');
x = naturalLogarithm(new Ctor(c0 + '.' + c.slice(1)), wpr - guard).plus(t);
Ctor.precision = pr;
return sd == null ? finalise(x, pr, rm, external = true) : x;
}
// x1 is x reduced to a value near 1.
x1 = x;
// Taylor series.
// ln(y) = ln((1 + x)/(1 - x)) = 2(x + x^3/3 + x^5/5 + x^7/7 + ...)
// where x = (y - 1)/(y + 1) (|x| < 1)
sum = numerator = x = divide(x.minus(1), x.plus(1), wpr, 1);
x2 = finalise(x.times(x), wpr, 1);
denominator = 3;
for (;;) {
numerator = finalise(numerator.times(x2), wpr, 1);
t = sum.plus(divide(numerator, new Ctor(denominator), wpr, 1));
if (digitsToString(t.d).slice(0, wpr) === digitsToString(sum.d).slice(0, wpr)) {
sum = sum.times(2);
// Reverse the argument reduction. Check that e is not 0 because, besides preventing an
// unnecessary calculation, -0 + 0 = +0 and to ensure correct rounding -0 needs to stay -0.
if (e !== 0) sum = sum.plus(getLn10(Ctor, wpr + 2, pr).times(e + ''));
sum = divide(sum, new Ctor(n), wpr, 1);
// Is rm > 3 and the first 4 rounding digits 4999, or rm < 4 (or the summation has
// been repeated previously) and the first 4 rounding digits 9999?
// If so, restart the summation with a higher precision, otherwise
// e.g. with precision: 12, rounding: 1
// ln(135520028.6126091714265381533) = 18.7246299999 when it should be 18.72463.
// `wpr - guard` is the index of first rounding digit.
if (sd == null) {
if (checkRoundingDigits(sum.d, wpr - guard, rm, rep)) {
Ctor.precision = wpr += guard;
t = numerator = x = divide(x1.minus(1), x1.plus(1), wpr, 1);
x2 = finalise(x.times(x), wpr, 1);
denominator = rep = 1;
} else {
return finalise(sum, Ctor.precision = pr, rm, external = true);
}
} else {
Ctor.precision = pr;
return sum;
}
}
sum = t;
denominator += 2;
}
}
// ±Infinity, NaN.
function nonFiniteToString(x) {
// Unsigned.
return String(x.s * x.s / 0);
}
/*
* Parse the value of a new Decimal `x` from string `str`.
*/
function parseDecimal(x, str) {
var e, i, len;
// Decimal point?
if ((e = str.indexOf('.')) > -1) str = str.replace('.', '');
// Exponential form?
if ((i = str.search(/e/i)) > 0) {
// Determine exponent.
if (e < 0) e = i;
e += +str.slice(i + 1);
str = str.substring(0, i);
} else if (e < 0) {
// Integer.
e = str.length;
}
// Determine leading zeros.
for (i = 0; str.charCodeAt(i) === 48; i++);
// Determine trailing zeros.
for (len = str.length; str.charCodeAt(len - 1) === 48; --len);
str = str.slice(i, len);
if (str) {
len -= i;
x.e = e = e - i - 1;
x.d = [];
// Transform base
// e is the base 10 exponent.
// i is where to slice str to get the first word of the digits array.
i = (e + 1) % LOG_BASE;
if (e < 0) i += LOG_BASE;
if (i < len) {
if (i) x.d.push(+str.slice(0, i));
for (len -= LOG_BASE; i < len;) x.d.push(+str.slice(i, i += LOG_BASE));
str = str.slice(i);
i = LOG_BASE - str.length;
} else {
i -= len;
}
for (; i--;) str += '0';
x.d.push(+str);
if (external) {
// Overflow?
if (x.e > x.constructor.maxE) {
// Infinity.
x.d = null;
x.e = NaN;
// Underflow?
} else if (x.e < x.constructor.minE) {
// Zero.
x.e = 0;
x.d = [0];
// x.constructor.underflow = true;
} // else x.constructor.underflow = false;
}
} else {
// Zero.
x.e = 0;
x.d = [0];
}
return x;
}
/*
* Parse the value of a new Decimal `x` from a string `str`, which is not a decimal value.
*/
function parseOther(x, str) {
var base, Ctor, divisor, i, isFloat, len, p, xd, xe;
if (str === 'Infinity' || str === 'NaN') {
if (!+str) x.s = NaN;
x.e = NaN;
x.d = null;
return x;
}
if (isHex.test(str)) {
base = 16;
str = str.toLowerCase();
} else if (isBinary.test(str)) {
base = 2;
} else if (isOctal.test(str)) {
base = 8;
} else {
throw Error(invalidArgument + str);
}
// Is there a binary exponent part?
i = str.search(/p/i);
if (i > 0) {
p = +str.slice(i + 1);
str = str.substring(2, i);
} else {
str = str.slice(2);
}
// Convert `str` as an integer then divide the result by `base` raised to a power such that the
// fraction part will be restored.
i = str.indexOf('.');
isFloat = i >= 0;
Ctor = x.constructor;
if (isFloat) {
str = str.replace('.', '');
len = str.length;
i = len - i;
// log[10](16) = 1.2041... , log[10](88) = 1.9444....
divisor = intPow(Ctor, new Ctor(base), i, i * 2);
}
xd = convertBase(str, base, BASE);
xe = xd.length - 1;
// Remove trailing zeros.
for (i = xe; xd[i] === 0; --i) xd.pop();
if (i < 0) return new Ctor(x.s * 0);
x.e = getBase10Exponent(xd, xe);
x.d = xd;
external = false;
// At what precision to perform the division to ensure exact conversion?
// maxDecimalIntegerPartDigitCount = ceil(log[10](b) * otherBaseIntegerPartDigitCount)
// log[10](2) = 0.30103, log[10](8) = 0.90309, log[10](16) = 1.20412
// E.g. ceil(1.2 * 3) = 4, so up to 4 decimal digits are needed to represent 3 hex int digits.
// maxDecimalFractionPartDigitCount = {Hex:4|Oct:3|Bin:1} * otherBaseFractionPartDigitCount
// Therefore using 4 * the number of digits of str will always be enough.
if (isFloat) x = divide(x, divisor, len * 4);
// Multiply by the binary exponent part if present.
if (p) x = x.times(Math.abs(p) < 54 ? Math.pow(2, p) : Decimal.pow(2, p));
external = true;
return x;
}
/*
* sin(x) = x - x^3/3! + x^5/5! - ...
* |x| < pi/2
*
*/
function sine(Ctor, x) {
var k,
len = x.d.length;
if (len < 3) return taylorSeries(Ctor, 2, x, x);
// Argument reduction: sin(5x) = 16*sin^5(x) - 20*sin^3(x) + 5*sin(x)
// i.e. sin(x) = 16*sin^5(x/5) - 20*sin^3(x/5) + 5*sin(x/5)
// and sin(x) = sin(x/5)(5 + sin^2(x/5)(16sin^2(x/5) - 20))
// Estimate the optimum number of times to use the argument reduction.
k = 1.4 * Math.sqrt(len);
k = k > 16 ? 16 : k | 0;
// Max k before Math.pow precision loss is 22
x = x.times(Math.pow(5, -k));
x = taylorSeries(Ctor, 2, x, x);
// Reverse argument reduction
var sin2_x,
d5 = new Ctor(5),
d16 = new Ctor(16),
d20 = new Ctor(20);
for (; k--;) {
sin2_x = x.times(x);
x = x.times(d5.plus(sin2_x.times(d16.times(sin2_x).minus(d20))));
}
return x;
}
// Calculate Taylor series for `cos`, `cosh`, `sin` and `sinh`.
function taylorSeries(Ctor, n, x, y, isHyperbolic) {
var j, t, u, x2,
i = 1,
pr = Ctor.precision,
k = Math.ceil(pr / LOG_BASE);
external = false;
x2 = x.times(x);
u = new Ctor(y);
for (;;) {
t = divide(u.times(x2), new Ctor(n++ * n++), pr, 1);
u = isHyperbolic ? y.plus(t) : y.minus(t);
y = divide(t.times(x2), new Ctor(n++ * n++), pr, 1);
t = u.plus(y);
if (t.d[k] !== void 0) {
for (j = k; t.d[j] === u.d[j] && j--;);
if (j == -1) break;
}
j = u;
u = y;
y = t;
t = j;
i++;
}
external = true;
t.d.length = k + 1;
return t;
}
// Return the absolute value of `x` reduced to less than or equal to half pi.
function toLessThanHalfPi(Ctor, x) {
var t,
isNeg = x.s < 0,
pi = getPi(Ctor, Ctor.precision, 1),
halfPi = pi.times(0.5);
x = x.abs();
if (x.lte(halfPi)) {
quadrant = isNeg ? 4 : 1;
return x;
}
t = x.divToInt(pi);
if (t.isZero()) {
quadrant = isNeg ? 3 : 2;
} else {
x = x.minus(t.times(pi));
// 0 <= x < pi
if (x.lte(halfPi)) {
quadrant = isOdd(t) ? (isNeg ? 2 : 3) : (isNeg ? 4 : 1);
return x;
}
quadrant = isOdd(t) ? (isNeg ? 1 : 4) : (isNeg ? 3 : 2);
}
return x.minus(pi).abs();
}
/*
* Return the value of Decimal `x` as a string in base `baseOut`.
*
* If the optional `sd` argument is present include a binary exponent suffix.
*/
function toStringBinary(x, baseOut, sd, rm) {
var base, e, i, k, len, roundUp, str, xd, y,
Ctor = x.constructor,
isExp = sd !== void 0;
if (isExp) {
checkInt32(sd, 1, MAX_DIGITS);
if (rm === void 0) rm = Ctor.rounding;
else checkInt32(rm, 0, 8);
} else {
sd = Ctor.precision;
rm = Ctor.rounding;
}
if (!x.isFinite()) {
str = nonFiniteToString(x);
} else {
str = finiteToString(x);
i = str.indexOf('.');
// Use exponential notation according to `toExpPos` and `toExpNeg`? No, but if required:
// maxBinaryExponent = floor((decimalExponent + 1) * log[2](10))
// minBinaryExponent = floor(decimalExponent * log[2](10))
// log[2](10) = 3.321928094887362347870319429489390175864
if (isExp) {
base = 2;
if (baseOut == 16) {
sd = sd * 4 - 3;
} else if (baseOut == 8) {
sd = sd * 3 - 2;
}
} else {
base = baseOut;
}
// Convert the number as an integer then divide the result by its base raised to a power such
// that the fraction part will be restored.
// Non-integer.
if (i >= 0) {
str = str.replace('.', '');
y = new Ctor(1);
y.e = str.length - i;
y.d = convertBase(finiteToString(y), 10, base);
y.e = y.d.length;
}
xd = convertBase(str, 10, base);
e = len = xd.length;
// Remove trailing zeros.
for (; xd[--len] == 0;) xd.pop();
if (!xd[0]) {
str = isExp ? '0p+0' : '0';
} else {
if (i < 0) {
e--;
} else {
x = new Ctor(x);
x.d = xd;
x.e = e;
x = divide(x, y, sd, rm, 0, base);
xd = x.d;
e = x.e;
roundUp = inexact;
}
// The rounding digit, i.e. the digit after the digit that may be rounded up.
i = xd[sd];
k = base / 2;
roundUp = roundUp || xd[sd + 1] !== void 0;
roundUp = rm < 4
? (i !== void 0 || roundUp) && (rm === 0 || rm === (x.s < 0 ? 3 : 2))
: i > k || i === k && (rm === 4 || roundUp || rm === 6 && xd[sd - 1] & 1 ||
rm === (x.s < 0 ? 8 : 7));
xd.length = sd;
if (roundUp) {
// Rounding up may mean the previous digit has to be rounded up and so on.
for (; ++xd[--sd] > base - 1;) {
xd[sd] = 0;
if (!sd) {
++e;
xd.unshift(1);
}
}
}
// Determine trailing zeros.
for (len = xd.length; !xd[len - 1]; --len);
// E.g. [4, 11, 15] becomes 4bf.
for (i = 0, str = ''; i < len; i++) str += NUMERALS.charAt(xd[i]);
// Add binary exponent suffix?
if (isExp) {
if (len > 1) {
if (baseOut == 16 || baseOut == 8) {
i = baseOut == 16 ? 4 : 3;
for (--len; len % i; len++) str += '0';
xd = convertBase(str, base, baseOut);
for (len = xd.length; !xd[len - 1]; --len);
// xd[0] will always be be 1
for (i = 1, str = '1.'; i < len; i++) str += NUMERALS.charAt(xd[i]);
} else {
str = str.charAt(0) + '.' + str.slice(1);
}
}
str = str + (e < 0 ? 'p' : 'p+') + e;
} else if (e < 0) {
for (; ++e;) str = '0' + str;
str = '0.' + str;
} else {
if (++e > len) for (e -= len; e-- ;) str += '0';
else if (e < len) str = str.slice(0, e) + '.' + str.slice(e);
}
}
str = (baseOut == 16 ? '0x' : baseOut == 2 ? '0b' : baseOut == 8 ? '0o' : '') + str;
}
return x.s < 0 ? '-' + str : str;
}
// Does not strip trailing zeros.
function truncate(arr, len) {
if (arr.length > len) {
arr.length = len;
return true;
}
}
// Decimal methods
/*
* abs
* acos
* acosh
* add
* asin
* asinh
* atan
* atanh
* atan2
* cbrt
* ceil
* clone
* config
* cos
* cosh
* div
* exp
* floor
* fromJSON
* hypot
* ln
* log
* log2
* log10
* max
* min
* mod
* mul
* pow
* random
* round
* sign
* sin
* sinh
* sqrt
* sub
* tan
* tanh
* trunc
*/
/*
* Return a new Decimal whose value is the absolute value of `x`.
*
* x {number|string|Decimal}
*
*/
function abs(x) {
return new this(x).abs();
}
/*
* Return a new Decimal whose value is the arccosine in radians of `x`.
*
* x {number|string|Decimal}
*
*/
function acos(x) {
return new this(x).acos();
}
/*
* Return a new Decimal whose value is the inverse of the hyperbolic cosine of `x`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function acosh(x) {
return new this(x).acosh();
}
/*
* Return a new Decimal whose value is the sum of `x` and `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function add(x, y) {
return new this(x).plus(y);
}
/*
* Return a new Decimal whose value is the arcsine in radians of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function asin(x) {
return new this(x).asin();
}
/*
* Return a new Decimal whose value is the inverse of the hyperbolic sine of `x`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function asinh(x) {
return new this(x).asinh();
}
/*
* Return a new Decimal whose value is the arctangent in radians of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function atan(x) {
return new this(x).atan();
}
/*
* Return a new Decimal whose value is the inverse of the hyperbolic tangent of `x`, rounded to
* `precision` significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function atanh(x) {
return new this(x).atanh();
}
/*
* Return a new Decimal whose value is the arctangent in radians of `y/x` in the range -pi to pi
* (inclusive), rounded to `precision` significant digits using rounding mode `rounding`.
*
* Domain: [-Infinity, Infinity]
* Range: [-pi, pi]
*
* y {number|string|Decimal} The y-coordinate.
* x {number|string|Decimal} The x-coordinate.
*
* atan2(±0, -0) = ±pi
* atan2(±0, +0) = ±0
* atan2(±0, -x) = ±pi for x > 0
* atan2(±0, x) = ±0 for x > 0
* atan2(-y, ±0) = -pi/2 for y > 0
* atan2(y, ±0) = pi/2 for y > 0
* atan2(±y, -Infinity) = ±pi for finite y > 0
* atan2(±y, +Infinity) = ±0 for finite y > 0
* atan2(±Infinity, x) = ±pi/2 for finite x
* atan2(±Infinity, -Infinity) = ±3*pi/4
* atan2(±Infinity, +Infinity) = ±pi/4
* atan2(NaN, x) = NaN
* atan2(y, NaN) = NaN
*
*/
function atan2(y, x) {
y = new this(y);
x = new this(x);
var r,
pr = this.precision,
rm = this.rounding,
wpr = pr + 4;
// Either NaN
if (!y.s || !x.s) {
r = new this(NaN);
// Both ±Infinity
} else if (!y.d && !x.d) {
r = getPi(this, wpr, 1).times(x.s > 0 ? 0.25 : 0.75);
r.s = y.s;
// x is ±Infinity or y is ±0
} else if (!x.d || y.isZero()) {
r = x.s < 0 ? getPi(this, pr, rm) : new this(0);
r.s = y.s;
// y is ±Infinity or x is ±0
} else if (!y.d || x.isZero()) {
r = getPi(this, wpr, 1).times(0.5);
r.s = y.s;
// Both non-zero and finite
} else if (x.s < 0) {
this.precision = wpr;
this.rounding = 1;
r = this.atan(divide(y, x, wpr, 1));
x = getPi(this, wpr, 1);
this.precision = pr;
this.rounding = rm;
r = y.s < 0 ? r.minus(x) : r.plus(x);
} else {
r = this.atan(divide(y, x, wpr, 1));
}
return r;
}
/*
* Return a new Decimal whose value is the cube root of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function cbrt(x) {
return new this(x).cbrt();
}
/*
* Return a new Decimal whose value is `x` rounded to an integer using `ROUND_CEIL`.
*
* x {number|string|Decimal}
*
*/
function ceil(x) {
return finalise(x = new this(x), x.e + 1, 2);
}
/*
* Configure global settings for a Decimal constructor.
*
* `obj` is an object with one or more of the following properties,
*
* precision {number}
* rounding {number}
* toExpNeg {number}
* toExpPos {number}
* maxE {number}
* minE {number}
* modulo {number}
* crypto {boolean|number|undefined}
*
* E.g. Decimal.config({ precision: 20, rounding: 4 })
*
*/
function config(obj) {
if (!obj || typeof obj !== 'object') throw Error(decimalError + 'Object expected');
var i, p, v,
ps = [
'precision', 1, MAX_DIGITS,
'rounding', 0, 8,
'toExpNeg', -EXP_LIMIT, 0,
'toExpPos', 0, EXP_LIMIT,
'maxE', 0, EXP_LIMIT,
'minE', -EXP_LIMIT, 0,
'modulo', 0, 9
];
for (i = 0; i < ps.length; i += 3) {
if ((v = obj[p = ps[i]]) !== void 0) {
if (mathfloor(v) === v && v >= ps[i + 1] && v <= ps[i + 2]) this[p] = v;
else throw Error(invalidArgument + p + ': ' + v);
}
}
if (obj.hasOwnProperty(p = 'crypto')) {
if ((v = obj[p]) === void 0) {
this[p] = v;
} else if (v === true || v === false || v === 0 || v === 1) {
this[p] = !!(v && cryptoObject &&
(cryptoObject.getRandomValues || cryptoObject.randomBytes));
} else {
throw Error(invalidArgument + p + ': ' + v);
}
}
return this;
}
/*
* Return a new Decimal whose value is the cosine of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function cos(x) {
return new this(x).cos();
}
/*
* Return a new Decimal whose value is the hyperbolic cosine of `x`, rounded to precision
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function cosh(x) {
return new this(x).cosh();
}
/*
* Create and return a Decimal constructor with the same configuration properties as this Decimal
* constructor.
*
*/
function clone(obj) {
var i, p, ps;
/*
* The Decimal constructor and exported function.
* Return a new Decimal instance.
*
* v {number|string|Decimal} A numeric value.
*
*/
function Decimal(v) {
var e, i, t,
x = this;
// Decimal called without new.
if (!(x instanceof Decimal)) return new Decimal(v);
// Retain a reference to this Decimal constructor, and shadow Decimal.prototype.constructor
// which points to Object.
x.constructor = Decimal;
// Duplicate.
if (v instanceof Decimal) {
x.s = v.s;
x.e = v.e;
x.d = (v = v.d) ? v.slice() : v;
return;
}
t = typeof v;
if (t === 'number') {
if (v === 0) {
x.s = 1 / v < 0 ? -1 : 1;
x.e = 0;
x.d = [0];
return;
}
if (v < 0) {
v = -v;
x.s = -1;
} else {
x.s = 1;
}
// Fast path for small integers.
if (v === ~~v && v < 1e7) {
for (e = 0, i = v; i >= 10; i /= 10) e++;
x.e = e;
x.d = [v];
return;
// Infinity, NaN.
} else if (v * 0 !== 0) {
if (!v) x.s = NaN;
x.e = NaN;
x.d = null;
return;
}
return parseDecimal(x, v.toString());
} else if (t !== 'string') {
throw Error(invalidArgument + v);
}
// Minus sign?
if (v.charCodeAt(0) === 45) {
v = v.slice(1);
x.s = -1;
} else {
x.s = 1;
}
return isDecimal.test(v) ? parseDecimal(x, v) : parseOther(x, v);
}
Decimal.prototype = P;
Decimal.ROUND_UP = 0;
Decimal.ROUND_DOWN = 1;
Decimal.ROUND_CEIL = 2;
Decimal.ROUND_FLOOR = 3;
Decimal.ROUND_HALF_UP = 4;
Decimal.ROUND_HALF_DOWN = 5;
Decimal.ROUND_HALF_EVEN = 6;
Decimal.ROUND_HALF_CEIL = 7;
Decimal.ROUND_HALF_FLOOR = 8;
Decimal.EUCLID = 9;
Decimal.config = config;
Decimal.clone = clone;
Decimal.abs = abs;
Decimal.acos = acos;
Decimal.acosh = acosh; // ES6
Decimal.add = add;
Decimal.asin = asin;
Decimal.asinh = asinh; // ES6
Decimal.atan = atan;
Decimal.atanh = atanh; // ES6
Decimal.atan2 = atan2;
Decimal.cbrt = cbrt; // ES6
Decimal.ceil = ceil;
Decimal.cos = cos;
Decimal.cosh = cosh; // ES6
Decimal.div = div;
Decimal.exp = exp;
Decimal.floor = floor;
Decimal.fromJSON = fromJSON;
Decimal.hypot = hypot; // ES6
Decimal.ln = ln;
Decimal.log = log;
Decimal.log10 = log10; // ES6
Decimal.log2 = log2; // ES6
Decimal.max = max;
Decimal.min = min;
Decimal.mod = mod;
Decimal.mul = mul;
Decimal.pow = pow;
Decimal.random = random;
Decimal.round = round;
Decimal.sign = sign; // ES6
Decimal.sin = sin;
Decimal.sinh = sinh; // ES6
Decimal.sqrt = sqrt;
Decimal.sub = sub;
Decimal.tan = tan;
Decimal.tanh = tanh; // ES6
Decimal.trunc = trunc; // ES6
if (obj === void 0) obj = {};
if (obj) {
ps = ['precision', 'rounding', 'toExpNeg', 'toExpPos', 'maxE', 'minE', 'modulo', 'crypto'];
for (i = 0; i < ps.length;) if (!obj.hasOwnProperty(p = ps[i++])) obj[p] = this[p];
}
Decimal.config(obj);
return Decimal;
}
/*
* Return a new Decimal whose value is `x` divided by `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function div(x, y) {
return new this(x).div(y);
}
/*
* Return a new Decimal whose value is the natural exponential of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} The power to which to raise the base of the natural log.
*
*/
function exp(x) {
return new this(x).exp();
}
/*
* Return a new Decimal whose value is `x` round to an integer using `ROUND_FLOOR`.
*
* x {number|string|Decimal}
*
*/
function floor(x) {
return finalise(x = new this(x), x.e + 1, 3);
}
/*
* Return a new Decimal from `str`, a string value created by `toJSON`.
*
* Base 88 alphabet:
* 0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!#$%()*+,-./:;=?@[]^_`{|}~
*
* If `str` is just one character:
* 0-81 [[0, 40][-0, -40]]
* 82 -Infinity
* 83 +Infinity
* 84 NaN
*
* 64 32 16 8 4 2 1
* 1 0 1 0 1 1 1 = 87
*
*/
function fromJSON(str) {
var e, isNeg, k, n;
if (typeof str !== 'string' || !str) throw Error(invalidArgument + str);
k = str.length;
n = NUMERALS.indexOf(str.charAt(0));
// [0, 81] -> [[0, 40][-0, -40]]
if (k === 1) {
return new this(n > 81 ? [-1 / 0, 1 / 0, 0 / 0][n - 82] : n > 40 ? -(n - 41) : n);
} else if (n & 64) {
isNeg = n & 16;
// e = isNeg ? [-3, 4] : [-7, 8]
e = isNeg ? (n & 7) - 3 : (n & 15) - 7;
k = 1;
} else if (k === 2) {
n = n * 88 + NUMERALS.indexOf(str.charAt(1));
// [0, 5631] -> [[0, 2815][-0, -2815]] -> [[41, 2856][-41, -2856]]
return new this(n >= 2816 ? -(n - 2816) - 41 : n + 41);
} else {
// 0XXXXXX
// 0 {is negative} {is exponent negative} {exponent digit count [0, 15]}
isNeg = n & 32;
// Has an exponent been specified?
if (n & 31) {
e = n & 15; // Exponent character count [1, 15]
k = e + 1; // Index of first character of the significand.
if (e === 1) {
e = NUMERALS.indexOf(str.charAt(1));
} else if (e === 2) {
e = NUMERALS.indexOf(str.charAt(1)) * 88 +
NUMERALS.indexOf(str.charAt(2));
} else {
e = +convertBase(str.slice(1, k), 88, 10).join('');
}
// Negative exponent?
if (n & 16) e = -e;
} else {
// Integer without trailing zeros.
// 0X00000
// 0 {is negative} 0 0 0 0 0
str = convertBase(str.slice(1), 88, 10).join('');
return new this(isNeg ? '-' + str : str);
}
}
str = convertBase(str.slice(k), 88, 10).join('');
e = e - str.length + 1;
str = str + 'e' + e;
return new this(isNeg ? '-' + str : str);
}
/*
* Return a new Decimal whose value is the square root of the sum of the squares of the arguments,
* rounded to `precision` significant digits using rounding mode `rounding`.
*
* hypot(a, b, ...) = sqrt(a^2 + b^2 + ...)
*
*/
function hypot() {
var i, n,
t = new this(0);
external = false;
for (i = 0; i < arguments.length;) {
n = new this(arguments[i++]);
if (!n.d) {
if (n.s) {
external = true;
return new this(1 / 0);
}
t = n;
} else if (t.d) {
t = t.plus(n.times(n));
}
}
external = true;
return t.sqrt();
}
/*
* Return a new Decimal whose value is the natural logarithm of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function ln(x) {
return new this(x).ln();
}
/*
* Return a new Decimal whose value is the log of `x` to the base `y`, or to base 10 if no base
* is specified, rounded to `precision` significant digits using rounding mode `rounding`.
*
* log[y](x)
*
* x {number|string|Decimal} The argument of the logarithm.
* y {number|string|Decimal} The base of the logarithm.
*
*/
function log(x, y) {
return new this(x).log(y);
}
/*
* Return a new Decimal whose value is the base 2 logarithm of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function log2(x) {
return new this(x).log(2);
}
/*
* Return a new Decimal whose value is the base 10 logarithm of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function log10(x) {
return new this(x).log(10);
}
/*
* Return a new Decimal whose value is the maximum of the arguments.
*
* arguments {number|string|Decimal}
*
*/
function max() {
return maxOrMin(this, arguments, 'lt');
}
/*
* Return a new Decimal whose value is the minimum of the arguments.
*
* arguments {number|string|Decimal}
*
*/
function min() {
return maxOrMin(this, arguments, 'gt');
}
/*
* Return a new Decimal whose value is `x` modulo `y`, rounded to `precision` significant digits
* using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function mod(x, y) {
return new this(x).mod(y);
}
/*
* Return a new Decimal whose value is `x` multiplied by `y`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function mul(x, y) {
return new this(x).mul(y);
}
/*
* Return a new Decimal whose value is `x` raised to the power `y`, rounded to precision
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} The base.
* y {number|string|Decimal} The exponent.
*
*/
function pow(x, y) {
return new this(x).pow(y);
}
/*
* Returns a new Decimal with a random value equal to or greater than 0 and less than 1, and with
* `sd`, or `Decimal.precision` if `sd` is omitted, significant digits (or less if trailing zeros
* are produced).
*
* [sd] {number} Significant digits. Integer, 0 to MAX_DIGITS inclusive.
*
*/
function random(sd) {
var d, e, k, n,
i = 0,
r = new this(1),
rd = [];
if (sd === void 0) sd = this.precision;
else checkInt32(sd, 1, MAX_DIGITS);
k = Math.ceil(sd / LOG_BASE);
if (this.crypto === false) {
for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
// Browsers supporting crypto.getRandomValues.
} else if (cryptoObject && cryptoObject.getRandomValues) {
d = cryptoObject.getRandomValues(new Uint32Array(k));
for (; i < k;) {
n = d[i];
// 0 <= n < 4294967296
// Probability n >= 4.29e9, is 4967296 / 4294967296 = 0.00116 (1 in 865).
if (n >= 4.29e9) {
d[i] = cryptoObject.getRandomValues(new Uint32Array(1))[0];
} else {
// 0 <= n <= 4289999999
// 0 <= (n % 1e7) <= 9999999
rd[i++] = n % 1e7;
}
}
// Node.js supporting crypto.randomBytes.
} else if (cryptoObject && cryptoObject.randomBytes) {
// buffer
d = cryptoObject.randomBytes(k *= 4);
for (; i < k;) {
// 0 <= n < 2147483648
n = d[i] + (d[i + 1] << 8) + (d[i + 2] << 16) + ((d[i + 3] & 0x7f) << 24);
// Probability n >= 2.14e9, is 7483648 / 2147483648 = 0.0035 (1 in 286).
if (n >= 2.14e9) {
cryptoObject.randomBytes(4).copy(d, i);
} else {
// 0 <= n <= 2139999999
// 0 <= (n % 1e7) <= 9999999
rd.push(n % 1e7);
i += 4;
}
}
i = k / 4;
} else if (this.crypto) {
throw Error(decimalError + 'crypto unavailable');
} else {
for (; i < k;) rd[i++] = Math.random() * 1e7 | 0;
}
k = rd[--i];
sd %= LOG_BASE;
// Convert trailing digits to zeros according to sd.
if (k && sd) {
n = mathpow(10, LOG_BASE - sd);
rd[i] = (k / n | 0) * n;
}
// Remove trailing words which are zero.
for (; rd[i] === 0; i--) rd.pop();
// Zero?
if (i < 0) {
e = 0;
rd = [0];
} else {
e = -1;
// Remove leading words which are zero and adjust exponent accordingly.
for (; rd[0] === 0; e -= LOG_BASE) rd.shift();
// Count the digits of the first word of rd to determine leading zeros.
for (k = 1, n = rd[0]; n >= 10; n /= 10) k++;
// Adjust the exponent for leading zeros of the first word of rd.
if (k < LOG_BASE) e -= LOG_BASE - k;
}
r.e = e;
r.d = rd;
return r;
}
/*
* Return a new Decimal whose value is `x` rounded to an integer using rounding mode `rounding`.
*
* To emulate `Math.round`, set rounding to 7 (ROUND_HALF_CEIL).
*
* x {number|string|Decimal}
*
*/
function round(x) {
return finalise(x = new this(x), x.e + 1, this.rounding);
}
/*
* Return
* 1 if x > 0,
* -1 if x < 0,
* 0 if x is 0,
* -0 if x is -0,
* NaN otherwise
*
*/
function sign(x) {
x = new this(x);
return x.d ? (x.d[0] ? x.s : 0 * x.s) : x.s || NaN;
}
/*
* Return a new Decimal whose value is the sine of `x`, rounded to `precision` significant digits
* using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function sin(x) {
return new this(x).sin();
}
/*
* Return a new Decimal whose value is the hyperbolic sine of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function sinh(x) {
return new this(x).sinh();
}
/*
* Return a new Decimal whose value is the square root of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal}
*
*/
function sqrt(x) {
return new this(x).sqrt();
}
/*
* Return a new Decimal whose value is `x` minus `y`, rounded to `precision` significant digits
* using rounding mode `rounding`.
*
* x {number|string|Decimal}
* y {number|string|Decimal}
*
*/
function sub(x, y) {
return new this(x).sub(y);
}
/*
* Return a new Decimal whose value is the tangent of `x`, rounded to `precision` significant
* digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function tan(x) {
return new this(x).tan();
}
/*
* Return a new Decimal whose value is the hyperbolic tangent of `x`, rounded to `precision`
* significant digits using rounding mode `rounding`.
*
* x {number|string|Decimal} A value in radians.
*
*/
function tanh(x) {
return new this(x).tanh();
}
/*
* Return a new Decimal whose value is `x` truncated to an integer.
*
* x {number|string|Decimal}
*
*/
function trunc(x) {
return finalise(x = new this(x), x.e + 1, 1);
}
// Create and configure initial Decimal constructor.
Decimal = clone(Decimal);
// Create the internal constants from their string values.
LN10 = new Decimal(LN10);
PI = new Decimal(PI);
// Export.
// AMD.
if (true) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function () {
return Decimal;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
// Node and other environments that support module.exports.
} else if (typeof module != 'undefined' && module.exports) {
module.exports = Decimal;
if (!cryptoObject) {
try {
cryptoObject = require('cry' + 'pto');
} catch (e) {
// Ignore.
}
}
// Browser.
} else {
if (!globalScope) {
globalScope = typeof self != 'undefined' && self && self.self == self
? self : Function('return this')();
}
noConflict = globalScope.Decimal;
Decimal.noConflict = function () {
globalScope.Decimal = noConflict;
return Decimal;
};
globalScope.Decimal = Decimal;
}
})(this);
/***/ }),
/* 82 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {return typeof obj;} : function (obj) {return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;};var assert = __webpack_require__(2);
var BN = __webpack_require__(30);
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(10);var bytesToHex = _require.bytesToHex;var parseBytes = _require.parseBytes;var serializeUIntN = _require.serializeUIntN;var _require2 =
__webpack_require__(43);var UInt = _require2.UInt;
var HEX_REGEX = /^[A-F0-9]{16}$/;
var UInt64 = makeClass({
inherits: UInt,
statics: { width: 8 },
UInt64: function UInt64() {var arg = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
var argType = typeof arg === 'undefined' ? 'undefined' : _typeof(arg);
if (argType === 'number') {
assert(arg >= 0);
this._bytes = new Uint8Array(8);
this._bytes.set(serializeUIntN(arg, 4), 4);} else
if (arg instanceof BN) {
this._bytes = parseBytes(arg.toArray('be', 8), Uint8Array);
this._toBN = arg;} else
{
if (argType === 'string') {
if (!HEX_REGEX.test(arg)) {
throw new Error(arg + ' is not a valid UInt64 hex string');}}
this._bytes = parseBytes(arg, Uint8Array);}
assert(this._bytes.length === 8);},
toJSON: function toJSON() {
return bytesToHex(this._bytes);},
valueOf: function valueOf() {
return this.toBN();},
cached: {
toBN: function toBN() {
return new BN(this._bytes);} },
toBytes: function toBytes() {
return this._bytes;} });
module.exports = {
UInt64: UInt64 };
/***/ }),
/* 83 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(50);var Hash = _require.Hash;
var Hash256 = makeClass({
inherits: Hash,
statics: {
width: 32,
init: function init() {
this.ZERO_256 = new this(new Uint8Array(this.width));} } });
module.exports = {
Hash256: Hash256 };
/***/ }),
/* 84 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {return typeof obj;} : function (obj) {return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj;};var _ = __webpack_require__(1);
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(29);var Field = _require.Field;var _require2 =
__webpack_require__(51);var BinarySerializer = _require2.BinarySerializer;var
ObjectEndMarker = Field.ObjectEndMarker;var _require3 =
__webpack_require__(21);var SerializedType = _require3.SerializedType;
var STObject = makeClass({
mixins: SerializedType,
statics: {
fromParser: function fromParser(parser, hint) {
var end = typeof hint === 'number' ? parser.pos() + hint : null;
var so = new this();
while (!parser.end(end)) {
var field = parser.readField();
if (field === ObjectEndMarker) {
break;}
so[field] = parser.readFieldValue(field);}
return so;},
from: function from(value) {
if (value instanceof this) {
return value;}
if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object') {
return _.transform(value, function (so, val, key) {
var field = Field[key];
if (field) {
so[field] = field.associatedType.from(val);} else
{
so[key] = val;}},
new this());}
throw new Error(value + ' is unsupported');} },
fieldKeys: function fieldKeys() {
return Object.keys(this).map(function (k) {return Field[k];}).filter(Boolean);},
toJSON: function toJSON() {
// Otherwise seemingly result will have same prototype as `this`
var accumulator = {}; // of only `own` properties
return _.transform(this, function (result, value, key) {
result[key] = value && value.toJSON ? value.toJSON() : value;},
accumulator);},
toBytesSink: function toBytesSink(sink) {var _this = this;var filter = arguments.length <= 1 || arguments[1] === undefined ? function () {return true;} : arguments[1];
var serializer = new BinarySerializer(sink);
var fields = this.fieldKeys();
var sorted = _.sortBy(fields, 'ordinal');
sorted.filter(filter).forEach(function (field) {
var value = _this[field];
if (!field.isSerialized) {
return;}
serializer.writeFieldAndValue(field, value);});} });
module.exports = {
STObject: STObject };
/***/ }),
/* 85 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var inherits = __webpack_require__(3)
var md5 = __webpack_require__(298)
var RIPEMD160 = __webpack_require__(300)
var sha = __webpack_require__(310)
var Base = __webpack_require__(315)
function HashNoConstructor (hash) {
Base.call(this, 'digest')
this._hash = hash
this.buffers = []
}
inherits(HashNoConstructor, Base)
HashNoConstructor.prototype._update = function (data) {
this.buffers.push(data)
}
HashNoConstructor.prototype._final = function () {
var buf = Buffer.concat(this.buffers)
var r = this._hash(buf)
this.buffers = null
return r
}
function Hash (hash) {
Base.call(this, 'digest')
this._hash = hash
}
inherits(Hash, Base)
Hash.prototype._update = function (data) {
this._hash.update(data)
}
Hash.prototype._final = function () {
return this._hash.digest()
}
module.exports = function createHash (alg) {
alg = alg.toLowerCase()
if (alg === 'md5') return new HashNoConstructor(md5)
if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
return new Hash(sha(alg))
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 86 */
/***/ (function(module, exports, __webpack_require__) {
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
module.exports = Stream;
var EE = __webpack_require__(17).EventEmitter;
var inherits = __webpack_require__(3);
inherits(Stream, EE);
Stream.Readable = __webpack_require__(54);
Stream.Writable = __webpack_require__(306);
Stream.Duplex = __webpack_require__(307);
Stream.Transform = __webpack_require__(308);
Stream.PassThrough = __webpack_require__(309);
// Backwards-compat with node 0.4.x
Stream.Stream = Stream;
// old-style streams. Note that the pipe method (the only relevant
// part of this class) is overridden in the Readable class.
function Stream() {
EE.call(this);
}
Stream.prototype.pipe = function(dest, options) {
var source = this;
function ondata(chunk) {
if (dest.writable) {
if (false === dest.write(chunk) && source.pause) {
source.pause();
}
}
}
source.on('data', ondata);
function ondrain() {
if (source.readable && source.resume) {
source.resume();
}
}
dest.on('drain', ondrain);
// If the 'end' option is not supplied, dest.end() will be called when
// source gets the 'end' or 'close' events. Only dest.end() once.
if (!dest._isStdio && (!options || options.end !== false)) {
source.on('end', onend);
source.on('close', onclose);
}
var didOnEnd = false;
function onend() {
if (didOnEnd) return;
didOnEnd = true;
dest.end();
}
function onclose() {
if (didOnEnd) return;
didOnEnd = true;
if (typeof dest.destroy === 'function') dest.destroy();
}
// don't leave dangling pipes when there are errors.
function onerror(er) {
cleanup();
if (EE.listenerCount(this, 'error') === 0) {
throw er; // Unhandled stream error in pipe.
}
}
source.on('error', onerror);
dest.on('error', onerror);
// remove all the event listeners that were added.
function cleanup() {
source.removeListener('data', ondata);
dest.removeListener('drain', ondrain);
source.removeListener('end', onend);
source.removeListener('close', onclose);
source.removeListener('error', onerror);
dest.removeListener('error', onerror);
source.removeListener('end', cleanup);
source.removeListener('close', cleanup);
dest.removeListener('close', cleanup);
}
source.on('end', cleanup);
source.on('close', cleanup);
dest.on('close', cleanup);
dest.emit('pipe', source);
// Allow for unix-like usage: A.pipe(B).pipe(C)
return dest;
};
/***/ }),
/* 87 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
module.exports = Readable;
/*<replacement>*/
var isArray = __webpack_require__(302);
/*</replacement>*/
/*<replacement>*/
var Duplex;
/*</replacement>*/
Readable.ReadableState = ReadableState;
/*<replacement>*/
var EE = __webpack_require__(17).EventEmitter;
var EElistenerCount = function (emitter, type) {
return emitter.listeners(type).length;
};
/*</replacement>*/
/*<replacement>*/
var Stream = __webpack_require__(88);
/*</replacement>*/
// TODO(bmeurer): Change this back to const once hole checks are
// properly optimized away early in Ignition+TurboFan.
/*<replacement>*/
var Buffer = __webpack_require__(8).Buffer;
var OurUint8Array = global.Uint8Array || function () {};
function _uint8ArrayToBuffer(chunk) {
return Buffer.from(chunk);
}
function _isUint8Array(obj) {
return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
}
/*</replacement>*/
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
/*<replacement>*/
var debugUtil = __webpack_require__(303);
var debug = void 0;
if (debugUtil && debugUtil.debuglog) {
debug = debugUtil.debuglog('stream');
} else {
debug = function () {};
}
/*</replacement>*/
var BufferList = __webpack_require__(304);
var destroyImpl = __webpack_require__(89);
var StringDecoder;
util.inherits(Readable, Stream);
var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
function prependListener(emitter, event, fn) {
// Sadly this is not cacheable as some libraries bundle their own
// event emitter implementation with them.
if (typeof emitter.prependListener === 'function') {
return emitter.prependListener(event, fn);
} else {
// This is a hack to make sure that our error handler is attached before any
// userland ones. NEVER DO THIS. This is here only because this code needs
// to continue to work with older versions of Node.js that do not include
// the prependListener() method. The goal is to eventually remove this hack.
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]];
}
}
function ReadableState(options, stream) {
Duplex = Duplex || __webpack_require__(25);
options = options || {};
// object stream flag. Used to make read(n) ignore n and to
// make all the buffer merging and length checks go away
this.objectMode = !!options.objectMode;
if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
// the point at which it stops calling _read() to fill the buffer
// Note: 0 is a valid value, means "don't call _read preemptively ever"
var hwm = options.highWaterMark;
var defaultHwm = this.objectMode ? 16 : 16 * 1024;
this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
// cast to ints.
this.highWaterMark = Math.floor(this.highWaterMark);
// A linked list is used to store data chunks instead of an array because the
// linked list can remove elements from the beginning faster than
// array.shift()
this.buffer = new BufferList();
this.length = 0;
this.pipes = null;
this.pipesCount = 0;
this.flowing = null;
this.ended = false;
this.endEmitted = false;
this.reading = false;
// a flag to be able to tell if the event 'readable'/'data' is emitted
// immediately, or on a later tick. We set this to true at first, because
// any actions that shouldn't happen until "later" should generally also
// not happen before the first read call.
this.sync = true;
// whenever we return null, then we set a flag to say
// that we're awaiting a 'readable' event emission.
this.needReadable = false;
this.emittedReadable = false;
this.readableListening = false;
this.resumeScheduled = false;
// has it been destroyed
this.destroyed = false;
// Crypto is kind of old and crusty. Historically, its default string
// encoding is 'binary' so we have to make this configurable.
// Everything else in the universe uses 'utf8', though.
this.defaultEncoding = options.defaultEncoding || 'utf8';
// the number of writers that are awaiting a drain event in .pipe()s
this.awaitDrain = 0;
// if true, a maybeReadMore has been scheduled
this.readingMore = false;
this.decoder = null;
this.encoding = null;
if (options.encoding) {
if (!StringDecoder) StringDecoder = __webpack_require__(37).StringDecoder;
this.decoder = new StringDecoder(options.encoding);
this.encoding = options.encoding;
}
}
function Readable(options) {
Duplex = Duplex || __webpack_require__(25);
if (!(this instanceof Readable)) return new Readable(options);
this._readableState = new ReadableState(options, this);
// legacy
this.readable = true;
if (options) {
if (typeof options.read === 'function') this._read = options.read;
if (typeof options.destroy === 'function') this._destroy = options.destroy;
}
Stream.call(this);
}
Object.defineProperty(Readable.prototype, 'destroyed', {
get: function () {
if (this._readableState === undefined) {
return false;
}
return this._readableState.destroyed;
},
set: function (value) {
// we ignore the value if the stream
// has not been initialized yet
if (!this._readableState) {
return;
}
// backward compatibility, the user is explicitly
// managing destroyed
this._readableState.destroyed = value;
}
});
Readable.prototype.destroy = destroyImpl.destroy;
Readable.prototype._undestroy = destroyImpl.undestroy;
Readable.prototype._destroy = function (err, cb) {
this.push(null);
cb(err);
};
// Manually shove something into the read() buffer.
// This returns true if the highWaterMark has not been hit yet,
// similar to how Writable.write() returns true if you should
// write() some more.
Readable.prototype.push = function (chunk, encoding) {
var state = this._readableState;
var skipChunkCheck;
if (!state.objectMode) {
if (typeof chunk === 'string') {
encoding = encoding || state.defaultEncoding;
if (encoding !== state.encoding) {
chunk = Buffer.from(chunk, encoding);
encoding = '';
}
skipChunkCheck = true;
}
} else {
skipChunkCheck = true;
}
return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
};
// Unshift should *always* be something directly out of read()
Readable.prototype.unshift = function (chunk) {
return readableAddChunk(this, chunk, null, true, false);
};
function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
var state = stream._readableState;
if (chunk === null) {
state.reading = false;
onEofChunk(stream, state);
} else {
var er;
if (!skipChunkCheck) er = chunkInvalid(state, chunk);
if (er) {
stream.emit('error', er);
} else if (state.objectMode || chunk && chunk.length > 0) {
if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
chunk = _uint8ArrayToBuffer(chunk);
}
if (addToFront) {
if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
} else if (state.ended) {
stream.emit('error', new Error('stream.push() after EOF'));
} else {
state.reading = false;
if (state.decoder && !encoding) {
chunk = state.decoder.write(chunk);
if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
} else {
addChunk(stream, state, chunk, false);
}
}
} else if (!addToFront) {
state.reading = false;
}
}
return needMoreData(state);
}
function addChunk(stream, state, chunk, addToFront) {
if (state.flowing && state.length === 0 && !state.sync) {
stream.emit('data', chunk);
stream.read(0);
} else {
// update the buffer info.
state.length += state.objectMode ? 1 : chunk.length;
if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
if (state.needReadable) emitReadable(stream);
}
maybeReadMore(stream, state);
}
function chunkInvalid(state, chunk) {
var er;
if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
er = new TypeError('Invalid non-string/buffer chunk');
}
return er;
}
// if it's past the high water mark, we can push in some more.
// Also, if we have no data yet, we can stand some
// more bytes. This is to work around cases where hwm=0,
// such as the repl. Also, if the push() triggered a
// readable event, and the user called read(largeNumber) such that
// needReadable was set, then we ought to push more, so that another
// 'readable' event will be triggered.
function needMoreData(state) {
return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
}
Readable.prototype.isPaused = function () {
return this._readableState.flowing === false;
};
// backwards compatibility.
Readable.prototype.setEncoding = function (enc) {
if (!StringDecoder) StringDecoder = __webpack_require__(37).StringDecoder;
this._readableState.decoder = new StringDecoder(enc);
this._readableState.encoding = enc;
return this;
};
// Don't raise the hwm > 8MB
var MAX_HWM = 0x800000;
function computeNewHighWaterMark(n) {
if (n >= MAX_HWM) {
n = MAX_HWM;
} else {
// Get the next highest power of 2 to prevent increasing hwm excessively in
// tiny amounts
n--;
n |= n >>> 1;
n |= n >>> 2;
n |= n >>> 4;
n |= n >>> 8;
n |= n >>> 16;
n++;
}
return n;
}
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function howMuchToRead(n, state) {
if (n <= 0 || state.length === 0 && state.ended) return 0;
if (state.objectMode) return 1;
if (n !== n) {
// Only flow one buffer at a time
if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
}
// If we're asking for more than the current hwm, then raise the hwm.
if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
if (n <= state.length) return n;
// Don't have enough
if (!state.ended) {
state.needReadable = true;
return 0;
}
return state.length;
}
// you can override either this method, or the async _read(n) below.
Readable.prototype.read = function (n) {
debug('read', n);
n = parseInt(n, 10);
var state = this._readableState;
var nOrig = n;
if (n !== 0) state.emittedReadable = false;
// if we're doing read(0) to trigger a readable event, but we
// already have a bunch of data in the buffer, then just trigger
// the 'readable' event and move on.
if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
debug('read: emitReadable', state.length, state.ended);
if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
return null;
}
n = howMuchToRead(n, state);
// if we've ended, and we're now clear, then finish it up.
if (n === 0 && state.ended) {
if (state.length === 0) endReadable(this);
return null;
}
// All the actual chunk generation logic needs to be
// *below* the call to _read. The reason is that in certain
// synthetic stream cases, such as passthrough streams, _read
// may be a completely synchronous operation which may change
// the state of the read buffer, providing enough data when
// before there was *not* enough.
//
// So, the steps are:
// 1. Figure out what the state of things will be after we do
// a read from the buffer.
//
// 2. If that resulting state will trigger a _read, then call _read.
// Note that this may be asynchronous, or synchronous. Yes, it is
// deeply ugly to write APIs this way, but that still doesn't mean
// that the Readable class should behave improperly, as streams are
// designed to be sync/async agnostic.
// Take note if the _read call is sync or async (ie, if the read call
// has returned yet), so that we know whether or not it's safe to emit
// 'readable' etc.
//
// 3. Actually pull the requested chunks out of the buffer and return.
// if we need a readable event, then we need to do some reading.
var doRead = state.needReadable;
debug('need readable', doRead);
// if we currently have less than the highWaterMark, then also read some
if (state.length === 0 || state.length - n < state.highWaterMark) {
doRead = true;
debug('length less than watermark', doRead);
}
// however, if we've ended, then there's no point, and if we're already
// reading, then it's unnecessary.
if (state.ended || state.reading) {
doRead = false;
debug('reading or ended', doRead);
} else if (doRead) {
debug('do read');
state.reading = true;
state.sync = true;
// if the length is currently zero, then we *need* a readable event.
if (state.length === 0) state.needReadable = true;
// call internal read method
this._read(state.highWaterMark);
state.sync = false;
// If _read pushed data synchronously, then `reading` will be false,
// and we need to re-evaluate how much data we can return to the user.
if (!state.reading) n = howMuchToRead(nOrig, state);
}
var ret;
if (n > 0) ret = fromList(n, state);else ret = null;
if (ret === null) {
state.needReadable = true;
n = 0;
} else {
state.length -= n;
}
if (state.length === 0) {
// If we have nothing in the buffer, then we want to know
// as soon as we *do* get something into the buffer.
if (!state.ended) state.needReadable = true;
// If we tried to read() past the EOF, then emit end on the next tick.
if (nOrig !== n && state.ended) endReadable(this);
}
if (ret !== null) this.emit('data', ret);
return ret;
};
function onEofChunk(stream, state) {
if (state.ended) return;
if (state.decoder) {
var chunk = state.decoder.end();
if (chunk && chunk.length) {
state.buffer.push(chunk);
state.length += state.objectMode ? 1 : chunk.length;
}
}
state.ended = true;
// emit 'readable' now to make sure it gets picked up.
emitReadable(stream);
}
// Don't emit readable right away in sync mode, because this can trigger
// another read() call => stack overflow. This way, it might trigger
// a nextTick recursion warning, but that's not so bad.
function emitReadable(stream) {
var state = stream._readableState;
state.needReadable = false;
if (!state.emittedReadable) {
debug('emitReadable', state.flowing);
state.emittedReadable = true;
if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
}
}
function emitReadable_(stream) {
debug('emit readable');
stream.emit('readable');
flow(stream);
}
// at this point, the user has presumably seen the 'readable' event,
// and called read() to consume some data. that may have triggered
// in turn another _read(n) call, in which case reading = true if
// it's in progress.
// However, if we're not ended, or reading, and the length < hwm,
// then go ahead and try to read some more preemptively.
function maybeReadMore(stream, state) {
if (!state.readingMore) {
state.readingMore = true;
processNextTick(maybeReadMore_, stream, state);
}
}
function maybeReadMore_(stream, state) {
var len = state.length;
while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
debug('maybeReadMore read 0');
stream.read(0);
if (len === state.length)
// didn't get any data, stop spinning.
break;else len = state.length;
}
state.readingMore = false;
}
// abstract method. to be overridden in specific implementation classes.
// call cb(er, data) where data is <= n in length.
// for virtual (non-string, non-buffer) streams, "length" is somewhat
// arbitrary, and perhaps not very meaningful.
Readable.prototype._read = function (n) {
this.emit('error', new Error('_read() is not implemented'));
};
Readable.prototype.pipe = function (dest, pipeOpts) {
var src = this;
var state = this._readableState;
switch (state.pipesCount) {
case 0:
state.pipes = dest;
break;
case 1:
state.pipes = [state.pipes, dest];
break;
default:
state.pipes.push(dest);
break;
}
state.pipesCount += 1;
debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
var endFn = doEnd ? onend : unpipe;
if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
dest.on('unpipe', onunpipe);
function onunpipe(readable, unpipeInfo) {
debug('onunpipe');
if (readable === src) {
if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
unpipeInfo.hasUnpiped = true;
cleanup();
}
}
}
function onend() {
debug('onend');
dest.end();
}
// when the dest drains, it reduces the awaitDrain counter
// on the source. This would be more elegant with a .once()
// handler in flow(), but adding and removing repeatedly is
// too slow.
var ondrain = pipeOnDrain(src);
dest.on('drain', ondrain);
var cleanedUp = false;
function cleanup() {
debug('cleanup');
// cleanup event handlers once the pipe is broken
dest.removeListener('close', onclose);
dest.removeListener('finish', onfinish);
dest.removeListener('drain', ondrain);
dest.removeListener('error', onerror);
dest.removeListener('unpipe', onunpipe);
src.removeListener('end', onend);
src.removeListener('end', unpipe);
src.removeListener('data', ondata);
cleanedUp = true;
// if the reader is waiting for a drain event from this
// specific writer, then it would cause it to never start
// flowing again.
// So, if this is awaiting a drain, then we just call it now.
// If we don't know, then assume that we are waiting for one.
if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
}
// If the user pushes more data while we're writing to dest then we'll end up
// in ondata again. However, we only want to increase awaitDrain once because
// dest will only emit one 'drain' event for the multiple writes.
// => Introduce a guard on increasing awaitDrain.
var increasedAwaitDrain = false;
src.on('data', ondata);
function ondata(chunk) {
debug('ondata');
increasedAwaitDrain = false;
var ret = dest.write(chunk);
if (false === ret && !increasedAwaitDrain) {
// If the user unpiped during `dest.write()`, it is possible
// to get stuck in a permanently paused state if that write
// also returned false.
// => Check whether `dest` is still a piping destination.
if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
debug('false write response, pause', src._readableState.awaitDrain);
src._readableState.awaitDrain++;
increasedAwaitDrain = true;
}
src.pause();
}
}
// if the dest has an error, then stop piping into it.
// however, don't suppress the throwing behavior for this.
function onerror(er) {
debug('onerror', er);
unpipe();
dest.removeListener('error', onerror);
if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
}
// Make sure our error handler is attached before userland ones.
prependListener(dest, 'error', onerror);
// Both close and finish should trigger unpipe, but only once.
function onclose() {
dest.removeListener('finish', onfinish);
unpipe();
}
dest.once('close', onclose);
function onfinish() {
debug('onfinish');
dest.removeListener('close', onclose);
unpipe();
}
dest.once('finish', onfinish);
function unpipe() {
debug('unpipe');
src.unpipe(dest);
}
// tell the dest that it's being piped to
dest.emit('pipe', src);
// start the flow if it hasn't been started already.
if (!state.flowing) {
debug('pipe resume');
src.resume();
}
return dest;
};
function pipeOnDrain(src) {
return function () {
var state = src._readableState;
debug('pipeOnDrain', state.awaitDrain);
if (state.awaitDrain) state.awaitDrain--;
if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
state.flowing = true;
flow(src);
}
};
}
Readable.prototype.unpipe = function (dest) {
var state = this._readableState;
var unpipeInfo = { hasUnpiped: false };
// if we're not piping anywhere, then do nothing.
if (state.pipesCount === 0) return this;
// just one destination. most common case.
if (state.pipesCount === 1) {
// passed in one, but it's not the right one.
if (dest && dest !== state.pipes) return this;
if (!dest) dest = state.pipes;
// got a match.
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
if (dest) dest.emit('unpipe', this, unpipeInfo);
return this;
}
// slow case. multiple pipe destinations.
if (!dest) {
// remove all.
var dests = state.pipes;
var len = state.pipesCount;
state.pipes = null;
state.pipesCount = 0;
state.flowing = false;
for (var i = 0; i < len; i++) {
dests[i].emit('unpipe', this, unpipeInfo);
}return this;
}
// try to find the right one.
var index = indexOf(state.pipes, dest);
if (index === -1) return this;
state.pipes.splice(index, 1);
state.pipesCount -= 1;
if (state.pipesCount === 1) state.pipes = state.pipes[0];
dest.emit('unpipe', this, unpipeInfo);
return this;
};
// set up data events if they are asked for
// Ensure readable listeners eventually get something
Readable.prototype.on = function (ev, fn) {
var res = Stream.prototype.on.call(this, ev, fn);
if (ev === 'data') {
// Start flowing on next tick if stream isn't explicitly paused
if (this._readableState.flowing !== false) this.resume();
} else if (ev === 'readable') {
var state = this._readableState;
if (!state.endEmitted && !state.readableListening) {
state.readableListening = state.needReadable = true;
state.emittedReadable = false;
if (!state.reading) {
processNextTick(nReadingNextTick, this);
} else if (state.length) {
emitReadable(this);
}
}
}
return res;
};
Readable.prototype.addListener = Readable.prototype.on;
function nReadingNextTick(self) {
debug('readable nexttick read 0');
self.read(0);
}
// pause() and resume() are remnants of the legacy readable stream API
// If the user uses them, then switch into old mode.
Readable.prototype.resume = function () {
var state = this._readableState;
if (!state.flowing) {
debug('resume');
state.flowing = true;
resume(this, state);
}
return this;
};
function resume(stream, state) {
if (!state.resumeScheduled) {
state.resumeScheduled = true;
processNextTick(resume_, stream, state);
}
}
function resume_(stream, state) {
if (!state.reading) {
debug('resume read 0');
stream.read(0);
}
state.resumeScheduled = false;
state.awaitDrain = 0;
stream.emit('resume');
flow(stream);
if (state.flowing && !state.reading) stream.read(0);
}
Readable.prototype.pause = function () {
debug('call pause flowing=%j', this._readableState.flowing);
if (false !== this._readableState.flowing) {
debug('pause');
this._readableState.flowing = false;
this.emit('pause');
}
return this;
};
function flow(stream) {
var state = stream._readableState;
debug('flow', state.flowing);
while (state.flowing && stream.read() !== null) {}
}
// wrap an old-style stream as the async data source.
// This is *not* part of the readable stream interface.
// It is an ugly unfortunate mess of history.
Readable.prototype.wrap = function (stream) {
var state = this._readableState;
var paused = false;
var self = this;
stream.on('end', function () {
debug('wrapped end');
if (state.decoder && !state.ended) {
var chunk = state.decoder.end();
if (chunk && chunk.length) self.push(chunk);
}
self.push(null);
});
stream.on('data', function (chunk) {
debug('wrapped data');
if (state.decoder) chunk = state.decoder.write(chunk);
// don't skip over falsy values in objectMode
if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
var ret = self.push(chunk);
if (!ret) {
paused = true;
stream.pause();
}
});
// proxy all the other methods.
// important when wrapping filters and duplexes.
for (var i in stream) {
if (this[i] === undefined && typeof stream[i] === 'function') {
this[i] = function (method) {
return function () {
return stream[method].apply(stream, arguments);
};
}(i);
}
}
// proxy certain important events.
for (var n = 0; n < kProxyEvents.length; n++) {
stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
}
// when we try to consume some more bytes, simply unpause the
// underlying stream.
self._read = function (n) {
debug('wrapped _read', n);
if (paused) {
paused = false;
stream.resume();
}
};
return self;
};
// exposed for testing purposes only.
Readable._fromList = fromList;
// Pluck off n bytes from an array of buffers.
// Length is the combined lengths of all the buffers in the list.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromList(n, state) {
// nothing buffered
if (state.length === 0) return null;
var ret;
if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
// read it all, truncate the list
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);
state.buffer.clear();
} else {
// read part of list
ret = fromListPartial(n, state.buffer, state.decoder);
}
return ret;
}
// Extracts only enough buffered data to satisfy the amount requested.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function fromListPartial(n, list, hasStrings) {
var ret;
if (n < list.head.data.length) {
// slice is the same for buffers and strings
ret = list.head.data.slice(0, n);
list.head.data = list.head.data.slice(n);
} else if (n === list.head.data.length) {
// first chunk is a perfect match
ret = list.shift();
} else {
// result spans more than one buffer
ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
}
return ret;
}
// Copies a specified amount of characters from the list of buffered data
// chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBufferString(n, list) {
var p = list.head;
var c = 1;
var ret = p.data;
n -= ret.length;
while (p = p.next) {
var str = p.data;
var nb = n > str.length ? str.length : n;
if (nb === str.length) ret += str;else ret += str.slice(0, n);
n -= nb;
if (n === 0) {
if (nb === str.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = str.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
// Copies a specified amount of bytes from the list of buffered data chunks.
// This function is designed to be inlinable, so please take care when making
// changes to the function body.
function copyFromBuffer(n, list) {
var ret = Buffer.allocUnsafe(n);
var p = list.head;
var c = 1;
p.data.copy(ret);
n -= p.data.length;
while (p = p.next) {
var buf = p.data;
var nb = n > buf.length ? buf.length : n;
buf.copy(ret, ret.length - n, 0, nb);
n -= nb;
if (n === 0) {
if (nb === buf.length) {
++c;
if (p.next) list.head = p.next;else list.head = list.tail = null;
} else {
list.head = p;
p.data = buf.slice(nb);
}
break;
}
++c;
}
list.length -= c;
return ret;
}
function endReadable(stream) {
var state = stream._readableState;
// If we get here before consuming all the bytes, then that is a
// bug in node. Should never happen.
if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
if (!state.endEmitted) {
state.ended = true;
processNextTick(endReadableNT, state, stream);
}
}
function endReadableNT(state, stream) {
// Check that we didn't get one last unshift.
if (!state.endEmitted && state.length === 0) {
state.endEmitted = true;
stream.readable = false;
stream.emit('end');
}
}
function forEach(xs, f) {
for (var i = 0, l = xs.length; i < l; i++) {
f(xs[i], i);
}
}
function indexOf(xs, x) {
for (var i = 0, l = xs.length; i < l; i++) {
if (xs[i] === x) return i;
}
return -1;
}
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(7), __webpack_require__(9)))
/***/ }),
/* 88 */
/***/ (function(module, exports, __webpack_require__) {
module.exports = __webpack_require__(17).EventEmitter;
/***/ }),
/* 89 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/*<replacement>*/
var processNextTick = __webpack_require__(20);
/*</replacement>*/
// undocumented cb() API, needed for core, not for public API
function destroy(err, cb) {
var _this = this;
var readableDestroyed = this._readableState && this._readableState.destroyed;
var writableDestroyed = this._writableState && this._writableState.destroyed;
if (readableDestroyed || writableDestroyed) {
if (cb) {
cb(err);
} else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
processNextTick(emitErrorNT, this, err);
}
return;
}
// we set destroyed to true before firing error callbacks in order
// to make it re-entrance safe in case destroy() is called within callbacks
if (this._readableState) {
this._readableState.destroyed = true;
}
// if this is a duplex stream mark the writable part as destroyed as well
if (this._writableState) {
this._writableState.destroyed = true;
}
this._destroy(err || null, function (err) {
if (!cb && err) {
processNextTick(emitErrorNT, _this, err);
if (_this._writableState) {
_this._writableState.errorEmitted = true;
}
} else if (cb) {
cb(err);
}
});
}
function undestroy() {
if (this._readableState) {
this._readableState.destroyed = false;
this._readableState.reading = false;
this._readableState.ended = false;
this._readableState.endEmitted = false;
}
if (this._writableState) {
this._writableState.destroyed = false;
this._writableState.ended = false;
this._writableState.ending = false;
this._writableState.finished = false;
this._writableState.errorEmitted = false;
}
}
function emitErrorNT(self, err) {
self.emit('error', err);
}
module.exports = {
destroy: destroy,
undestroy: undestroy
};
/***/ }),
/* 90 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// a transform stream is a readable/writable stream where you do
// something with the data. Sometimes it's called a "filter",
// but that's not a great name for it, since that implies a thing where
// some bits pass through, and others are simply ignored. (That would
// be a valid example of a transform, of course.)
//
// While the output is causally related to the input, it's not a
// necessarily symmetric or synchronous transformation. For example,
// a zlib stream might take multiple plain-text writes(), and then
// emit a single compressed chunk some time in the future.
//
// Here's how this works:
//
// The Transform stream has all the aspects of the readable and writable
// stream classes. When you write(chunk), that calls _write(chunk,cb)
// internally, and returns false if there's a lot of pending writes
// buffered up. When you call read(), that calls _read(n) until
// there's enough pending readable data buffered up.
//
// In a transform stream, the written data is placed in a buffer. When
// _read(n) is called, it transforms the queued up data, calling the
// buffered _write cb's as it consumes chunks. If consuming a single
// written chunk would result in multiple output chunks, then the first
// outputted bit calls the readcb, and subsequent chunks just go into
// the read buffer, and will cause it to emit 'readable' if necessary.
//
// This way, back-pressure is actually determined by the reading side,
// since _read has to be called to start processing a new chunk. However,
// a pathological inflate type of transform can cause excessive buffering
// here. For example, imagine a stream where every byte of input is
// interpreted as an integer from 0-255, and then results in that many
// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
// 1kb of data being output. In this case, you could write a very small
// amount of input, and end up with a very large amount of output. In
// such a pathological inflating mechanism, there'd be no way to tell
// the system to stop doing the transform. A single 4MB write could
// cause the system to run out of memory.
//
// However, even in such a pathological case, only a single written chunk
// would be consumed, and then the rest would wait (un-transformed) until
// the results of the previous transformed chunk were consumed.
module.exports = Transform;
var Duplex = __webpack_require__(25);
/*<replacement>*/
var util = __webpack_require__(15);
util.inherits = __webpack_require__(3);
/*</replacement>*/
util.inherits(Transform, Duplex);
function TransformState(stream) {
this.afterTransform = function (er, data) {
return afterTransform(stream, er, data);
};
this.needTransform = false;
this.transforming = false;
this.writecb = null;
this.writechunk = null;
this.writeencoding = null;
}
function afterTransform(stream, er, data) {
var ts = stream._transformState;
ts.transforming = false;
var cb = ts.writecb;
if (!cb) {
return stream.emit('error', new Error('write callback called multiple times'));
}
ts.writechunk = null;
ts.writecb = null;
if (data !== null && data !== undefined) stream.push(data);
cb(er);
var rs = stream._readableState;
rs.reading = false;
if (rs.needReadable || rs.length < rs.highWaterMark) {
stream._read(rs.highWaterMark);
}
}
function Transform(options) {
if (!(this instanceof Transform)) return new Transform(options);
Duplex.call(this, options);
this._transformState = new TransformState(this);
var stream = this;
// start out asking for a readable event once data is transformed.
this._readableState.needReadable = true;
// we have implemented the _read method, and done the other things
// that Readable wants before the first _read call, so unset the
// sync guard flag.
this._readableState.sync = false;
if (options) {
if (typeof options.transform === 'function') this._transform = options.transform;
if (typeof options.flush === 'function') this._flush = options.flush;
}
// When the writable side finishes, then flush out anything remaining.
this.once('prefinish', function () {
if (typeof this._flush === 'function') this._flush(function (er, data) {
done(stream, er, data);
});else done(stream);
});
}
Transform.prototype.push = function (chunk, encoding) {
this._transformState.needTransform = false;
return Duplex.prototype.push.call(this, chunk, encoding);
};
// This is the part where you do stuff!
// override this function in implementation classes.
// 'chunk' is an input chunk.
//
// Call `push(newChunk)` to pass along transformed output
// to the readable side. You may call 'push' zero or more times.
//
// Call `cb(err)` when you are done with this chunk. If you pass
// an error, then that'll put the hurt on the whole operation. If you
// never call cb(), then you'll never get another chunk.
Transform.prototype._transform = function (chunk, encoding, cb) {
throw new Error('_transform() is not implemented');
};
Transform.prototype._write = function (chunk, encoding, cb) {
var ts = this._transformState;
ts.writecb = cb;
ts.writechunk = chunk;
ts.writeencoding = encoding;
if (!ts.transforming) {
var rs = this._readableState;
if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
}
};
// Doesn't matter what the args are here.
// _transform does all the work.
// That we got here means that the readable side wants more data.
Transform.prototype._read = function (n) {
var ts = this._transformState;
if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
ts.transforming = true;
this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
} else {
// mark that we need a transform, so that any data that comes in
// will get processed, now that we've asked for it.
ts.needTransform = true;
}
};
Transform.prototype._destroy = function (err, cb) {
var _this = this;
Duplex.prototype._destroy.call(this, err, function (err2) {
cb(err2);
_this.emit('close');
});
};
function done(stream, er, data) {
if (er) return stream.emit('error', er);
if (data !== null && data !== undefined) stream.push(data);
// if there's nothing in the write buffer, then that means
// that nothing more will ever be provided
var ws = stream._writableState;
var ts = stream._transformState;
if (ws.length) throw new Error('Calling transform done when ws.length != 0');
if (ts.transforming) throw new Error('Calling transform done when still transforming');
return stream.push(null);
}
/***/ }),
/* 91 */
/***/ (function(module, exports, __webpack_require__) {
/**
* A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
* in FIPS 180-2
* Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
*
*/
var inherits = __webpack_require__(3)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(8).Buffer
var K = [
0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
]
var W = new Array(64)
function Sha256 () {
this.init()
this._w = W // new Array(64)
Hash.call(this, 64, 56)
}
inherits(Sha256, Hash)
Sha256.prototype.init = function () {
this._a = 0x6a09e667
this._b = 0xbb67ae85
this._c = 0x3c6ef372
this._d = 0xa54ff53a
this._e = 0x510e527f
this._f = 0x9b05688c
this._g = 0x1f83d9ab
this._h = 0x5be0cd19
return this
}
function ch (x, y, z) {
return z ^ (x & (y ^ z))
}
function maj (x, y, z) {
return (x & y) | (z & (x | y))
}
function sigma0 (x) {
return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
}
function sigma1 (x) {
return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
}
function gamma0 (x) {
return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
}
function gamma1 (x) {
return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
}
Sha256.prototype._update = function (M) {
var W = this._w
var a = this._a | 0
var b = this._b | 0
var c = this._c | 0
var d = this._d | 0
var e = this._e | 0
var f = this._f | 0
var g = this._g | 0
var h = this._h | 0
for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
for (var j = 0; j < 64; ++j) {
var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
var T2 = (sigma0(a) + maj(a, b, c)) | 0
h = g
g = f
f = e
e = (d + T1) | 0
d = c
c = b
b = a
a = (T1 + T2) | 0
}
this._a = (a + this._a) | 0
this._b = (b + this._b) | 0
this._c = (c + this._c) | 0
this._d = (d + this._d) | 0
this._e = (e + this._e) | 0
this._f = (f + this._f) | 0
this._g = (g + this._g) | 0
this._h = (h + this._h) | 0
}
Sha256.prototype._hash = function () {
var H = Buffer.allocUnsafe(32)
H.writeInt32BE(this._a, 0)
H.writeInt32BE(this._b, 4)
H.writeInt32BE(this._c, 8)
H.writeInt32BE(this._d, 12)
H.writeInt32BE(this._e, 16)
H.writeInt32BE(this._f, 20)
H.writeInt32BE(this._g, 24)
H.writeInt32BE(this._h, 28)
return H
}
module.exports = Sha256
/***/ }),
/* 92 */
/***/ (function(module, exports, __webpack_require__) {
var inherits = __webpack_require__(3)
var Hash = __webpack_require__(31)
var Buffer = __webpack_require__(8).Buffer
var K = [
0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
]
var W = new Array(160)
function Sha512 () {
this.init()
this._w = W
Hash.call(this, 128, 112)
}
inherits(Sha512, Hash)
Sha512.prototype.init = function () {
this._ah = 0x6a09e667
this._bh = 0xbb67ae85
this._ch = 0x3c6ef372
this._dh = 0xa54ff53a
this._eh = 0x510e527f
this._fh = 0x9b05688c
this._gh = 0x1f83d9ab
this._hh = 0x5be0cd19
this._al = 0xf3bcc908
this._bl = 0x84caa73b
this._cl = 0xfe94f82b
this._dl = 0x5f1d36f1
this._el = 0xade682d1
this._fl = 0x2b3e6c1f
this._gl = 0xfb41bd6b
this._hl = 0x137e2179
return this
}
function Ch (x, y, z) {
return z ^ (x & (y ^ z))
}
function maj (x, y, z) {
return (x & y) | (z & (x | y))
}
function sigma0 (x, xl) {
return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
}
function sigma1 (x, xl) {
return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
}
function Gamma0 (x, xl) {
return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
}
function Gamma0l (x, xl) {
return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
}
function Gamma1 (x, xl) {
return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
}
function Gamma1l (x, xl) {
return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
}
function getCarry (a, b) {
return (a >>> 0) < (b >>> 0) ? 1 : 0
}
Sha512.prototype._update = function (M) {
var W = this._w
var ah = this._ah | 0
var bh = this._bh | 0
var ch = this._ch | 0
var dh = this._dh | 0
var eh = this._eh | 0
var fh = this._fh | 0
var gh = this._gh | 0
var hh = this._hh | 0
var al = this._al | 0
var bl = this._bl | 0
var cl = this._cl | 0
var dl = this._dl | 0
var el = this._el | 0
var fl = this._fl | 0
var gl = this._gl | 0
var hl = this._hl | 0
for (var i = 0; i < 32; i += 2) {
W[i] = M.readInt32BE(i * 4)
W[i + 1] = M.readInt32BE(i * 4 + 4)
}
for (; i < 160; i += 2) {
var xh = W[i - 15 * 2]
var xl = W[i - 15 * 2 + 1]
var gamma0 = Gamma0(xh, xl)
var gamma0l = Gamma0l(xl, xh)
xh = W[i - 2 * 2]
xl = W[i - 2 * 2 + 1]
var gamma1 = Gamma1(xh, xl)
var gamma1l = Gamma1l(xl, xh)
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7h = W[i - 7 * 2]
var Wi7l = W[i - 7 * 2 + 1]
var Wi16h = W[i - 16 * 2]
var Wi16l = W[i - 16 * 2 + 1]
var Wil = (gamma0l + Wi7l) | 0
var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
Wil = (Wil + gamma1l) | 0
Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
Wil = (Wil + Wi16l) | 0
Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
W[i] = Wih
W[i + 1] = Wil
}
for (var j = 0; j < 160; j += 2) {
Wih = W[j]
Wil = W[j + 1]
var majh = maj(ah, bh, ch)
var majl = maj(al, bl, cl)
var sigma0h = sigma0(ah, al)
var sigma0l = sigma0(al, ah)
var sigma1h = sigma1(eh, el)
var sigma1l = sigma1(el, eh)
// t1 = h + sigma1 + ch + K[j] + W[j]
var Kih = K[j]
var Kil = K[j + 1]
var chh = Ch(eh, fh, gh)
var chl = Ch(el, fl, gl)
var t1l = (hl + sigma1l) | 0
var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
t1l = (t1l + chl) | 0
t1h = (t1h + chh + getCarry(t1l, chl)) | 0
t1l = (t1l + Kil) | 0
t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
t1l = (t1l + Wil) | 0
t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
// t2 = sigma0 + maj
var t2l = (sigma0l + majl) | 0
var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
hh = gh
hl = gl
gh = fh
gl = fl
fh = eh
fl = el
el = (dl + t1l) | 0
eh = (dh + t1h + getCarry(el, dl)) | 0
dh = ch
dl = cl
ch = bh
cl = bl
bh = ah
bl = al
al = (t1l + t2l) | 0
ah = (t1h + t2h + getCarry(al, t1l)) | 0
}
this._al = (this._al + al) | 0
this._bl = (this._bl + bl) | 0
this._cl = (this._cl + cl) | 0
this._dl = (this._dl + dl) | 0
this._el = (this._el + el) | 0
this._fl = (this._fl + fl) | 0
this._gl = (this._gl + gl) | 0
this._hl = (this._hl + hl) | 0
this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
}
Sha512.prototype._hash = function () {
var H = Buffer.allocUnsafe(64)
function writeInt64BE (h, l, offset) {
H.writeInt32BE(h, offset)
H.writeInt32BE(l, offset + 4)
}
writeInt64BE(this._ah, this._al, 0)
writeInt64BE(this._bh, this._bl, 8)
writeInt64BE(this._ch, this._cl, 16)
writeInt64BE(this._dh, this._dl, 24)
writeInt64BE(this._eh, this._el, 32)
writeInt64BE(this._fh, this._fl, 40)
writeInt64BE(this._gh, this._gl, 48)
writeInt64BE(this._hh, this._hl, 56)
return H
}
module.exports = Sha512
/***/ }),
/* 93 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var assert = __webpack_require__(2);
var makeClass = __webpack_require__(4);var _require =
__webpack_require__(24);var Hash256 = _require.Hash256;var _require2 =
__webpack_require__(38);var HashPrefix = _require2.HashPrefix;var _require3 =
__webpack_require__(44);var Hasher = _require3.Sha512Half;
var ShaMapNode = makeClass({
virtuals: {
hashPrefix: function hashPrefix() {},
isLeaf: function isLeaf() {},
isInner: function isInner() {} },
cached: {
hash: function hash() {
var hasher = Hasher.put(this.hashPrefix());
this.toBytesSink(hasher);
return hasher.finish();} } });
var ShaMapLeaf = makeClass({
inherits: ShaMapNode,
ShaMapLeaf: function ShaMapLeaf(index, item) {
ShaMapNode.call(this);
this.index = index;
this.item = item;},
isLeaf: function isLeaf() {
return true;},
isInner: function isInner() {
return false;},
hashPrefix: function hashPrefix() {
return this.item.hashPrefix();},
toBytesSink: function toBytesSink(sink) {
this.item.toBytesSink(sink);
this.index.toBytesSink(sink);} });
var $uper = ShaMapNode.prototype;
var ShaMapInner = makeClass({
inherits: ShaMapNode,
ShaMapInner: function ShaMapInner() {var depth = arguments.length <= 0 || arguments[0] === undefined ? 0 : arguments[0];
ShaMapNode.call(this);
this.depth = depth;
this.slotBits = 0;
this.branches = Array(16);},
isInner: function isInner() {
return true;},
isLeaf: function isLeaf() {
return false;},
hashPrefix: function hashPrefix() {
return HashPrefix.innerNode;},
setBranch: function setBranch(slot, branch) {
this.slotBits = this.slotBits | 1 << slot;
this.branches[slot] = branch;},
empty: function empty() {
return this.slotBits === 0;},
hash: function hash() {
if (this.empty()) {
return Hash256.ZERO_256;}
return $uper.hash.call(this);},
toBytesSink: function toBytesSink(sink) {
for (var i = 0; i < this.branches.length; i++) {
var branch = this.branches[i];
var hash = branch ? branch.hash() : Hash256.ZERO_256;
hash.toBytesSink(sink);}},
addItem: function addItem(index, item, leaf) {
assert(index instanceof Hash256);
var nibble = index.nibblet(this.depth);
var existing = this.branches[nibble];
if (!existing) {
this.setBranch(nibble, leaf || new ShaMapLeaf(index, item));} else
if (existing.isLeaf()) {
var newInner = new ShaMapInner(this.depth + 1);
newInner.addItem(existing.index, null, existing);
newInner.addItem(index, item, leaf);
this.setBranch(nibble, newInner);} else
if (existing.isInner()) {
existing.addItem(index, item, leaf);} else
{
assert(false);}} });
var ShaMap = makeClass({
inherits: ShaMapInner });
module.exports = {
ShaMap: ShaMap };
/***/ }),
/* 94 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/**
* Prefix for hashing functions.
*
* These prefixes are inserted before the source material used to
* generate various hashes. This is done to put each hash in its own
* "space." This way, two different types of objects with the
* same binary data will produce different hashes.
*
* Each prefix is a 4-byte value with the last byte set to zero
* and the first three bytes formed from the ASCII equivalent of
* some arbitrary string. For example "TXN".
*/
// transaction plus signature to give transaction ID
exports.HASH_TX_ID = 0x54584E00; // 'TXN'
// transaction plus metadata
exports.HASH_TX_NODE = 0x534E4400; // 'TND'
// inner node in tree
exports.HASH_INNER_NODE = 0x4D494E00; // 'MIN'
// inner node version 2
exports.HASH_INNER_NODE_V2 = 0x494E5200; // 'INR'
// leaf node in tree
exports.HASH_LEAF_NODE = 0x4D4C4E00; // 'MLN'
// inner transaction to sign
exports.HASH_TX_SIGN = 0x53545800; // 'STX'
// inner transaction to sign (TESTNET)
exports.HASH_TX_SIGN_TESTNET = 0x73747800; // 'stx'
// inner transaction to multisign
exports.HASH_TX_MULTISIGN = 0x534D5400; // 'SMT'
exports.HASH_LEDGER = 0x4C575200;
/***/ }),
/* 95 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
/* WEBPACK VAR INJECTION */(function(Buffer) {
var util = __webpack_require__(26);
var hashprefixes = __webpack_require__(94);
var sha512half = __webpack_require__(96);
var HEX_ZERO = '00000000000000000000000000000000' +
'00000000000000000000000000000000';
/**
* Abstract class representing a node in a SHAMap tree.
*
* Can be either SHAMapTreeNodeInner, SHAMapTreeNodeInnerV2
* or SHAMapTreeNodeLeaf.
*
* @class
*/
function SHAMapTreeNode() { }
SHAMapTreeNode.TYPE_INNER = 1;
SHAMapTreeNode.TYPE_TRANSACTION_NM = 2;
SHAMapTreeNode.TYPE_TRANSACTION_MD = 3;
SHAMapTreeNode.TYPE_ACCOUNT_STATE = 4;
function hash(hex) {
return sha512half(new Buffer(hex, 'hex'));
}
/**
* @param {String} tag (64 hexadecimal characters)
* @param {SHAMapTreeNode} node
* @return {void}
* @virtual
*/
/* eslint-disable no-unused-vars*/
SHAMapTreeNode.prototype.add_item = function(tag, node) {
throw new Error(
'Called unimplemented virtual method SHAMapTreeNode#add_item.');
};
/* eslint-enable no-unused-vars*/
SHAMapTreeNode.prototype.hash = function() {
throw new Error('Called unimplemented virtual method SHAMapTreeNode#hash.');
};
/**
* Inner (non-leaf) node in a SHAMap tree.
* @param {Number} depth (i.e. how many parent inner nodes)
* @class
*/
function SHAMapTreeNodeInner(depth) {
SHAMapTreeNode.call(this);
this.leaves = {};
this.type = SHAMapTreeNode.INNER;
this.depth = depth === undefined ? 0 : depth;
this.empty = true;
}
util.inherits(SHAMapTreeNodeInner, SHAMapTreeNode);
/**
* @param {String} tag (equates to a ledger entry `index`)
* @param {SHAMapTreeNode} node (to add)
* @return {void}
*/
SHAMapTreeNodeInner.prototype.add_item = function(tag, node) {
var depth = this.depth;
var existing_node = this.get_node(tag[depth]);
if (existing_node) {
// A node already exists in this slot
if (existing_node instanceof SHAMapTreeNodeInner) {
// There is an inner node, so we need to go deeper
existing_node.add_item(tag, node);
} else if (existing_node.tag === tag) {
// Collision
throw new Error(
'Tried to add a node to a SHAMap that was already in there.');
} else {
// Turn it into an inner node
var new_inner_node = new SHAMapTreeNodeInner(depth + 1);
// Parent new and existing node
new_inner_node.add_item(existing_node.tag, existing_node);
new_inner_node.add_item(tag, node);
// And place the newly created inner node in the slot
this.set_node(tag[depth], new_inner_node);
}
} else {
// Neat, we have a nice open spot for the new node
this.set_node(tag[depth], node);
}
};
/**
* Overwrite the node that is currently in a given slot.
* @param {String} slot (a character 0-F)
* @param {SHAMapTreeNode} node (to place)
* @return {void}
*/
SHAMapTreeNodeInner.prototype.set_node = function(slot, node) {
this.leaves[slot] = node;
this.empty = false;
};
SHAMapTreeNodeInner.prototype.get_node = function(slot) {
return this.leaves[slot];
};
SHAMapTreeNodeInner.prototype.hash = function() {
if (this.empty) {
return HEX_ZERO;
}
var hex = '';
for (var i = 0; i < 16; i++) {
var slot = i.toString(16).toUpperCase();
hex += this.leaves[slot] ? this.leaves[slot].hash() : HEX_ZERO;
}
var prefix = hashprefixes.HASH_INNER_NODE.toString(16);
return hash(prefix + hex);
};
/**
* V2 inner (non-leaf) node in a SHAMap tree.
* @param {Number} depth ()
* @class
*/
function SHAMapTreeNodeInnerV2(depth) {
SHAMapTreeNodeInner.call(this, depth);
this.common = '';
}
util.inherits(SHAMapTreeNodeInnerV2, SHAMapTreeNodeInner);
/**
* @param {String} key (equates to a ledger entry `index`)
* @return {Number} (common prefix depth)
*/
SHAMapTreeNodeInnerV2.prototype.get_common_prefix = function(key) {
var depth = 0;
for (var i = 0; i < this.depth; i++) {
if (this.common[i] === key[i]) {
depth++
}
}
return depth;
};
/**
* @param {String} key (equates to a ledger entry `index`)
* @return {bool} (returns true if common prefix exists)
*/
SHAMapTreeNodeInnerV2.prototype.has_common_prefix = function(key) {
for (var i = 0; i < this.depth; i++) {
if (this.common[i] !== key[i]) {
return false;
}
}
return true;
};
/**
* @param {String} tag (equates to a ledger entry `index`)
* @param {SHAMapTreeNode} node (to add)
* @return {void}
*/
SHAMapTreeNodeInnerV2.prototype.add_item = function(tag, node) {
var depth = this.depth;
var existing_node = this.get_node(tag[depth]);
if (existing_node) {
// A node already exists in this slot
if (existing_node instanceof SHAMapTreeNodeInnerV2) {
if (existing_node.has_common_prefix(tag)) {
// There is an inner node, so we need to go deeper
existing_node.add_item(tag, node);
} else {
// Create new inner node and move existing node under it
var new_depth = existing_node.get_common_prefix(tag);
var new_inner_node = new SHAMapTreeNodeInnerV2(new_depth);
new_inner_node.common = tag.slice(0, new_depth - 64);
// Parent new and existing node
new_inner_node.set_node(existing_node.common[new_depth], existing_node);
new_inner_node.add_item(tag, node);
// And place the newly created inner node in the slot
this.set_node(tag[depth], new_inner_node);
}
} else if (existing_node.tag === tag) {
// Collision
throw new Error(
'Tried to add a node to a SHAMap that was already in there.');
} else {
// Turn it into an inner node
var new_inner_node = new SHAMapTreeNodeInnerV2(0);
for (var i = 0; tag[i] === existing_node.tag[i]; i++) {
new_inner_node.common += tag[i];
new_inner_node.depth++;
}
// Parent new and existing node
new_inner_node.add_item(existing_node.tag, existing_node);
new_inner_node.add_item(tag, node);
// And place the newly created inner node in the slot
this.set_node(tag[depth], new_inner_node);
}
} else {
// Neat, we have a nice open spot for the new node
this.set_node(tag[depth], node);
}
};
SHAMapTreeNodeInnerV2.prototype.hash = function() {
if (this.empty) {
return HEX_ZERO;
}
var hex = '';
for (var i = 0; i < 16; i++) {
var slot = i.toString(16).toUpperCase();
hex += this.leaves[slot] ? this.leaves[slot].hash() : HEX_ZERO;
}
if (this.depth < 16) {
hex += '0';
}
hex += this.depth.toString(16).toUpperCase();
hex += this.common;
if (this.common.length % 2) {
hex += '0';
}
var prefix = hashprefixes.HASH_INNER_NODE_V2.toString(16);
return hash(prefix + hex);
};
/**
* Leaf node in a SHAMap tree.
* @param {String} tag (equates to a ledger entry `index`)
* @param {String} data (hex of account state, transaction etc)
* @param {Number} type (one of TYPE_ACCOUNT_STATE, TYPE_TRANSACTION_MD etc)
* @class
*/
function SHAMapTreeNodeLeaf(tag, data, type) {
SHAMapTreeNode.call(this);
if (typeof tag !== 'string') {
throw new Error('Tag is unexpected type.');
}
this.tag = tag;
this.type = type;
this.data = data;
}
util.inherits(SHAMapTreeNodeLeaf, SHAMapTreeNode);
SHAMapTreeNodeLeaf.prototype.hash = function() {
switch (this.type) {
case SHAMapTreeNode.TYPE_ACCOUNT_STATE:
var leafPrefix = hashprefixes.HASH_LEAF_NODE.toString(16);
return hash(leafPrefix + this.data + this.tag);
case SHAMapTreeNode.TYPE_TRANSACTION_NM:
var txPrefix = hashprefixes.HASH_TX_ID.toString(16);
return hash(txPrefix + this.data);
case SHAMapTreeNode.TYPE_TRANSACTION_MD:
var txPrefix = hashprefixes.HASH_TX_NODE.toString(16);
return hash(txPrefix + this.data + this.tag);
default:
throw new Error('Tried to hash a SHAMap node of unknown type.');
}
};
/**
* SHAMap tree.
* @param {Number} version (inner node version number)
* @class
*/
function SHAMap(version) {
this.version = version === undefined ? 1 : version;
this.root = this.version === 1 ? new SHAMapTreeNodeInner(0) :
new SHAMapTreeNodeInnerV2(0);
}
SHAMap.prototype.add_item = function(tag, data, type) {
this.root.add_item(tag, new SHAMapTreeNodeLeaf(tag, data, type));
};
SHAMap.prototype.hash = function() {
return this.root.hash();
};
exports.SHAMap = SHAMap;
exports.SHAMapTreeNode = SHAMapTreeNode;
exports.SHAMapTreeNodeInner = SHAMapTreeNodeInner;
exports.SHAMapTreeNodeInnerV2 = SHAMapTreeNodeInnerV2;
exports.SHAMapTreeNodeLeaf = SHAMapTreeNodeLeaf;
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(5).Buffer))
/***/ }),
/* 96 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var createHash = __webpack_require__(85);
// For a hash function, rippled uses SHA-512 and then truncates the result
// to the first 256 bytes. This algorithm, informally called SHA-512Half,
// provides an output that has comparable security to SHA-256, but runs
// faster on 64-bit processors.
function sha512half(buffer) {
var sha512 = createHash('sha512');
return sha512.update(buffer).digest('hex').toUpperCase().slice(0, 64);
}
module.exports = sha512half;
/***/ }),
/* 97 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const orderFlags = {
Passive: 0x00010000,
Sell: 0x00020000 // offer was placed as a sell
};
exports.orderFlags = orderFlags;
const trustlineFlags = {
LowReserve: 0x00010000,
HighReserve: 0x00020000,
LowAuth: 0x00040000,
HighAuth: 0x00080000,
LowNoRipple: 0x00100000,
HighNoRipple: 0x00200000,
LowFreeze: 0x00400000,
HighFreeze: 0x00800000
};
exports.trustlineFlags = trustlineFlags;
/***/ }),
/* 98 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
var api_1 = __webpack_require__(56);
exports.RippleAPI = api_1.RippleAPI;
// Broadcast api is experimental
var broadcast_1 = __webpack_require__(354);
exports.RippleAPIBroadcast = broadcast_1.RippleAPIBroadcast;
/***/ }),
/* 99 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const txflags_1 = __webpack_require__(57);
const accountRootFlags = {
PasswordSpent: 0x00010000,
RequireDestTag: 0x00020000,
RequireAuth: 0x00040000,
DisallowXRP: 0x00080000,
DisableMaster: 0x00100000,
NoFreeze: 0x00200000,
GlobalFreeze: 0x00400000,
DefaultRipple: 0x00800000
};
const AccountFlags = {
passwordSpent: accountRootFlags.PasswordSpent,
requireDestinationTag: accountRootFlags.RequireDestTag,
requireAuthorization: accountRootFlags.RequireAuth,
disallowIncomingXRP: accountRootFlags.DisallowXRP,
disableMasterKey: accountRootFlags.DisableMaster,
noFreeze: accountRootFlags.NoFreeze,
globalFreeze: accountRootFlags.GlobalFreeze,
defaultRipple: accountRootFlags.DefaultRipple
};
exports.AccountFlags = AccountFlags;
const AccountFlagIndices = {
requireDestinationTag: txflags_1.txFlagIndices.AccountSet.asfRequireDest,
requireAuthorization: txflags_1.txFlagIndices.AccountSet.asfRequireAuth,
disallowIncomingXRP: txflags_1.txFlagIndices.AccountSet.asfDisallowXRP,
disableMasterKey: txflags_1.txFlagIndices.AccountSet.asfDisableMaster,
enableTransactionIDTracking: txflags_1.txFlagIndices.AccountSet.asfAccountTxnID,
noFreeze: txflags_1.txFlagIndices.AccountSet.asfNoFreeze,
globalFreeze: txflags_1.txFlagIndices.AccountSet.asfGlobalFreeze,
defaultRipple: txflags_1.txFlagIndices.AccountSet.asfDefaultRipple
};
exports.AccountFlagIndices = AccountFlagIndices;
const AccountFields = {
EmailHash: { name: 'emailHash', encoding: 'hex',
length: 32, defaults: '0' },
MessageKey: { name: 'messageKey' },
Domain: { name: 'domain', encoding: 'hex' },
TransferRate: { name: 'transferRate', defaults: 0, shift: 9 }
};
exports.AccountFields = AccountFields;
/***/ }),
/* 100 */
/***/ (function(module, exports) {
module.exports = function isBuffer(arg) {
return arg && typeof arg === 'object'
&& typeof arg.copy === 'function'
&& typeof arg.fill === 'function'
&& typeof arg.readUInt8 === 'function';
}
/***/ }),
/* 101 */
/***/ (function(module, exports) {
if (typeof Object.create === 'function') {
// implementation from standard node.js 'util' module
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
ctor.prototype = Object.create(superCtor.prototype, {
constructor: {
value: ctor,
enumerable: false,
writable: true,
configurable: true
}
});
};
} else {
// old school shim for old browsers
module.exports = function inherits(ctor, superCtor) {
ctor.super_ = superCtor
var TempCtor = function () {}
TempCtor.prototype = superCtor.prototype
ctor.prototype = new TempCtor()
ctor.prototype.constructor = ctor
}
}
/***/ }),
/* 102 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
function setPrototypeOf(object, prototype) {
// Object.setPrototypeOf not supported on Internet Explorer 9
Object.setPrototypeOf ? Object.setPrototypeOf(object, prototype) :
// @ts-ignore: Specifically a fallback for IE9
object.__proto__ = prototype;
}
exports.setPrototypeOf = setPrototypeOf;
function getConstructorName(object) {
// hack for internet explorer
if (!object.constructor.name) {
return object.constructor.toString().match(/^function\s+([^(]*)/)[1];
}
return object.constructor.name;
}
exports.getConstructorName = getConstructorName;
/***/ }),
/* 103 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _ = __webpack_require__(1);
const errors_1 = __webpack_require__(39);
const schema_validator_1 = __webpack_require__(58);
function error(text) {
return new errors_1.ValidationError(text);
}
function validateLedgerRange(options) {
if (!_.isUndefined(options) && !_.isUndefined(options.minLedgerVersion)
&& !_.isUndefined(options.maxLedgerVersion)) {
if (Number(options.minLedgerVersion) > Number(options.maxLedgerVersion)) {
throw error('minLedgerVersion must not be greater than maxLedgerVersion');
}
}
}
function validateOptions(schema, instance) {
schema_validator_1.schemaValidate(schema, instance);
validateLedgerRange(instance.options);
}
exports.getPaths = _.partial(schema_validator_1.schemaValidate, 'getPathsParameters');
exports.getTransactions = _.partial(validateOptions, 'getTransactionsParameters');
exports.getSettings = _.partial(validateOptions, 'getSettingsParameters');
exports.getAccountInfo = _.partial(validateOptions, 'getAccountInfoParameters');
exports.getTrustlines = _.partial(validateOptions, 'getTrustlinesParameters');
exports.getBalances = _.partial(validateOptions, 'getBalancesParameters');
exports.getBalanceSheet = _.partial(validateOptions, 'getBalanceSheetParameters');
exports.getOrders = _.partial(validateOptions, 'getOrdersParameters');
exports.getOrderbook = _.partial(validateOptions, 'getOrderbookParameters');
exports.getTransaction = _.partial(validateOptions, 'getTransactionParameters');
exports.getPaymentChannel = _.partial(validateOptions, 'getPaymentChannelParameters');
exports.getLedger = _.partial(validateOptions, 'getLedgerParameters');
exports.preparePayment = _.partial(schema_validator_1.schemaValidate, 'preparePaymentParameters');
exports.prepareOrder = _.partial(schema_validator_1.schemaValidate, 'prepareOrderParameters');
exports.prepareOrderCancellation = _.partial(schema_validator_1.schemaValidate, 'prepareOrderCancellationParameters');
exports.prepareTrustline = _.partial(schema_validator_1.schemaValidate, 'prepareTrustlineParameters');
exports.prepareSettings = _.partial(schema_validator_1.schemaValidate, 'prepareSettingsParameters');
exports.prepareEscrowCreation = _.partial(schema_validator_1.schemaValidate, 'prepareEscrowCreationParameters');
exports.prepareEscrowCancellation = _.partial(schema_validator_1.schemaValidate, 'prepareEscrowCancellationParameters');
exports.prepareEscrowExecution = _.partial(schema_validator_1.schemaValidate, 'prepareEscrowExecutionParameters');
exports.preparePaymentChannelCreate = _.partial(schema_validator_1.schemaValidate, 'preparePaymentChannelCreateParameters');
exports.preparePaymentChannelFund = _.partial(schema_validator_1.schemaValidate, 'preparePaymentChannelFundParameters');
exports.preparePaymentChannelClaim = _.partial(schema_validator_1.schemaValidate, 'preparePaymentChannelClaimParameters');
exports.sign = _.partial(schema_validator_1.schemaValidate, 'signParameters');
exports.combine = _.partial(schema_validator_1.schemaValidate, 'combineParameters');
exports.submit = _.partial(schema_validator_1.schemaValidate, 'submitParameters');
exports.computeLedgerHash = _.partial(schema_validator_1.schemaValidate, 'computeLedgerHashParameters');
exports.generateAddress = _.partial(schema_validator_1.schemaValidate, 'generateAddressParameters');
exports.signPaymentChannelClaim = _.partial(schema_validator_1.schemaValidate, 'signPaymentChannelClaimParameters');
exports.verifyPaymentChannelClaim = _.partial(schema_validator_1.schemaValidate, 'verifyPaymentChannelClaimParameters');
exports.apiOptions = _.partial(schema_validator_1.schemaValidate, 'api-options');
exports.instructions = _.partial(schema_validator_1.schemaValidate, 'instructions');
/***/ }),
/* 104 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var Validator = module.exports.Validator = __webpack_require__(105);
module.exports.ValidatorResult = __webpack_require__(32).ValidatorResult;
module.exports.ValidationError = __webpack_require__(32).ValidationError;
module.exports.SchemaError = __webpack_require__(32).SchemaError;
module.exports.validate = function (instance, schema, options) {
var v = new Validator();
return v.validate(instance, schema, options);
};
/***/ }),
/* 105 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var urilib = __webpack_require__(22);
var attribute = __webpack_require__(111);
var helpers = __webpack_require__(32);
var ValidatorResult = helpers.ValidatorResult;
var SchemaError = helpers.SchemaError;
var SchemaContext = helpers.SchemaContext;
/**
* Creates a new Validator object
* @name Validator
* @constructor
*/
var Validator = function Validator () {
// Allow a validator instance to override global custom formats or to have their
// own custom formats.
this.customFormats = Object.create(Validator.prototype.customFormats);
this.schemas = {};
this.unresolvedRefs = [];
// Use Object.create to make this extensible without Validator instances stepping on each other's toes.
this.types = Object.create(types);
this.attributes = Object.create(attribute.validators);
};
// Allow formats to be registered globally.
Validator.prototype.customFormats = {};
// Hint at the presence of a property
Validator.prototype.schemas = null;
Validator.prototype.types = null;
Validator.prototype.attributes = null;
Validator.prototype.unresolvedRefs = null;
/**
* Adds a schema with a certain urn to the Validator instance.
* @param schema
* @param urn
* @return {Object}
*/
Validator.prototype.addSchema = function addSchema (schema, uri) {
if (!schema) {
return null;
}
var ourUri = uri || schema.id;
this.addSubSchema(ourUri, schema);
if (ourUri) {
this.schemas[ourUri] = schema;
}
return this.schemas[ourUri];
};
Validator.prototype.addSubSchema = function addSubSchema(baseuri, schema) {
if(!schema || typeof schema!='object') return;
// Mark all referenced schemas so we can tell later which schemas are referred to, but never defined
if(schema.$ref){
var resolvedUri = urilib.resolve(baseuri, schema.$ref);
// Only mark unknown schemas as unresolved
if (this.schemas[resolvedUri] === undefined) {
this.schemas[resolvedUri] = null;
this.unresolvedRefs.push(resolvedUri);
}
return;
}
var ourUri = schema.id && urilib.resolve(baseuri, schema.id);
var ourBase = ourUri || baseuri;
if (ourUri) {
if(this.schemas[ourUri]){
if(!helpers.deepCompareStrict(this.schemas[ourUri], schema)){
throw new Error('Schema <'+schema+'> already exists with different definition');
}
return this.schemas[ourUri];
}
this.schemas[ourUri] = schema;
var documentUri = ourUri.replace(/^([^#]*)#$/, '$1');
this.schemas[documentUri] = schema;
}
this.addSubSchemaArray(ourBase, ((schema.items instanceof Array)?schema.items:[schema.items]));
this.addSubSchemaArray(ourBase, ((schema.extends instanceof Array)?schema.extends:[schema.extends]));
this.addSubSchema(ourBase, schema.additionalItems);
this.addSubSchemaObject(ourBase, schema.properties);
this.addSubSchema(ourBase, schema.additionalProperties);
this.addSubSchemaObject(ourBase, schema.definitions);
this.addSubSchemaObject(ourBase, schema.patternProperties);
this.addSubSchemaObject(ourBase, schema.dependencies);
this.addSubSchemaArray(ourBase, schema.disallow);
this.addSubSchemaArray(ourBase, schema.allOf);
this.addSubSchemaArray(ourBase, schema.anyOf);
this.addSubSchemaArray(ourBase, schema.oneOf);
this.addSubSchema(ourBase, schema.not);
return this.schemas[ourUri];
};
Validator.prototype.addSubSchemaArray = function addSubSchemaArray(baseuri, schemas) {
if(!(schemas instanceof Array)) return;
for(var i=0; i<schemas.length; i++){
this.addSubSchema(baseuri, schemas[i]);
}
};
Validator.prototype.addSubSchemaObject = function addSubSchemaArray(baseuri, schemas) {
if(!schemas || typeof schemas!='object') return;
for(var p in schemas){
this.addSubSchema(baseuri, schemas[p]);
}
};
/**
* Sets all the schemas of the Validator instance.
* @param schemas
*/
Validator.prototype.setSchemas = function setSchemas (schemas) {
this.schemas = schemas;
};
/**
* Returns the schema of a certain urn
* @param urn
*/
Validator.prototype.getSchema = function getSchema (urn) {
return this.schemas[urn];
};
/**
* Validates instance against the provided schema
* @param instance
* @param schema
* @param [options]
* @param [ctx]
* @return {Array}
*/
Validator.prototype.validate = function validate (instance, schema, options, ctx) {
if (!options) {
options = {};
}
var propertyName = options.propertyName || 'instance';
// This will work so long as the function at uri.resolve() will resolve a relative URI to a relative URI
var base = urilib.resolve(options.base||'/', schema.id||'');
if(!ctx){
ctx = new SchemaContext(schema, options, propertyName, base, Object.create(this.schemas));
if (!ctx.schemas[base]) {
ctx.schemas[base] = schema;
}
}
if (schema) {
var result = this.validateSchema(instance, schema, options, ctx);
if (!result) {
throw new Error('Result undefined');
}
return result;
}
throw new SchemaError('no schema specified', schema);
};
/**
* @param Object schema
* @return mixed schema uri or false
*/
function shouldResolve(schema) {
var ref = (typeof schema === 'string') ? schema : schema.$ref;
if (typeof ref=='string') return ref;
return false;
}
/**
* Validates an instance against the schema (the actual work horse)
* @param instance
* @param schema
* @param options
* @param ctx
* @private
* @return {ValidatorResult}
*/
Validator.prototype.validateSchema = function validateSchema (instance, schema, options, ctx) {
var result = new ValidatorResult(instance, schema, options, ctx);
if (!schema) {
throw new Error("schema is undefined");
}
if (schema['extends']) {
if (schema['extends'] instanceof Array) {
var schemaobj = {schema: schema, ctx: ctx};
schema['extends'].forEach(this.schemaTraverser.bind(this, schemaobj));
schema = schemaobj.schema;
schemaobj.schema = null;
schemaobj.ctx = null;
schemaobj = null;
} else {
schema = helpers.deepMerge(schema, this.superResolve(schema['extends'], ctx));
}
}
var switchSchema;
if (switchSchema = shouldResolve(schema)) {
var resolved = this.resolve(schema, switchSchema, ctx);
var subctx = new SchemaContext(resolved.subschema, options, ctx.propertyPath, resolved.switchSchema, ctx.schemas);
return this.validateSchema(instance, resolved.subschema, options, subctx);
}
var skipAttributes = options && options.skipAttributes || [];
// Validate each schema attribute against the instance
for (var key in schema) {
if (!attribute.ignoreProperties[key] && skipAttributes.indexOf(key) < 0) {
var validatorErr = null;
var validator = this.attributes[key];
if (validator) {
validatorErr = validator.call(this, instance, schema, options, ctx);
} else if (options.allowUnknownAttributes === false) {
// This represents an error with the schema itself, not an invalid instance
throw new SchemaError("Unsupported attribute: " + key, schema);
}
if (validatorErr) {
result.importErrors(validatorErr);
}
}
}
if (typeof options.rewrite == 'function') {
var value = options.rewrite.call(this, instance, schema, options, ctx);
result.instance = value;
}
return result;
};
/**
* @private
* @param Object schema
* @param SchemaContext ctx
* @returns Object schema or resolved schema
*/
Validator.prototype.schemaTraverser = function schemaTraverser (schemaobj, s) {
schemaobj.schema = helpers.deepMerge(schemaobj.schema, this.superResolve(s, schemaobj.ctx));
}
/**
* @private
* @param Object schema
* @param SchemaContext ctx
* @returns Object schema or resolved schema
*/
Validator.prototype.superResolve = function superResolve (schema, ctx) {
var ref;
if(ref = shouldResolve(schema)) {
return this.resolve(schema, ref, ctx).subschema;
}
return schema;
}
/**
* @private
* @param Object schema
* @param Object switchSchema
* @param SchemaContext ctx
* @return Object resolved schemas {subschema:String, switchSchema: String}
* @throws SchemaError
*/
Validator.prototype.resolve = function resolve (schema, switchSchema, ctx) {
switchSchema = ctx.resolve(switchSchema);
// First see if the schema exists under the provided URI
if (ctx.schemas[switchSchema]) {
return {subschema: ctx.schemas[switchSchema], switchSchema: switchSchema};
}
// Else try walking the property pointer
var parsed = urilib.parse(switchSchema);
var fragment = parsed && parsed.hash;
var document = fragment && fragment.length && switchSchema.substr(0, switchSchema.length - fragment.length);
if (!document || !ctx.schemas[document]) {
throw new SchemaError("no such schema <" + switchSchema + ">", schema);
}
var subschema = helpers.objectGetPath(ctx.schemas[document], fragment.substr(1));
if(subschema===undefined){
throw new SchemaError("no such schema " + fragment + " located in <" + document + ">", schema);
}
return {subschema: subschema, switchSchema: switchSchema};
};
/**
* Tests whether the instance if of a certain type.
* @private
* @param instance
* @param schema
* @param options
* @param ctx
* @param type
* @return {boolean}
*/
Validator.prototype.testType = function validateType (instance, schema, options, ctx, type) {
if (typeof this.types[type] == 'function') {
return this.types[type].call(this, instance);
}
if (type && typeof type == 'object') {
var res = this.validateSchema(instance, type, options, ctx);
return res === undefined || !(res && res.errors.length);
}
// Undefined or properties not on the list are acceptable, same as not being defined
return true;
};
var types = Validator.prototype.types = {};
types.string = function testString (instance) {
return typeof instance == 'string';
};
types.number = function testNumber (instance) {
// isFinite returns false for NaN, Infinity, and -Infinity
return typeof instance == 'number' && isFinite(instance);
};
types.integer = function testInteger (instance) {
return (typeof instance == 'number') && instance % 1 === 0;
};
types.boolean = function testBoolean (instance) {
return typeof instance == 'boolean';
};
types.array = function testArray (instance) {
return Array.isArray(instance);
};
types['null'] = function testNull (instance) {
return instance === null;
};
types.date = function testDate (instance) {
return instance instanceof Date;
};
types.any = function testAny (instance) {
return true;
};
types.object = function testObject (instance) {
// TODO: fix this - see #15
return instance && (typeof instance) === 'object' && !(instance instanceof Array) && !(instance instanceof Date);
};
module.exports = Validator;
/***/ }),
/* 106 */
/***/ (function(module, exports, __webpack_require__) {
/* WEBPACK VAR INJECTION */(function(module, global) {var __WEBPACK_AMD_DEFINE_RESULT__;/*! https://mths.be/punycode v1.4.1 by @mathias */
;(function(root) {
/** Detect free variables */
var freeExports = typeof exports == 'object' && exports &&
!exports.nodeType && exports;
var freeModule = typeof module == 'object' && module &&
!module.nodeType && module;
var freeGlobal = typeof global == 'object' && global;
if (
freeGlobal.global === freeGlobal ||
freeGlobal.window === freeGlobal ||
freeGlobal.self === freeGlobal
) {
root = freeGlobal;
}
/**
* The `punycode` object.
* @name punycode
* @type Object
*/
var punycode,
/** Highest positive signed 32-bit float value */
maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
/** Bootstring parameters */
base = 36,
tMin = 1,
tMax = 26,
skew = 38,
damp = 700,
initialBias = 72,
initialN = 128, // 0x80
delimiter = '-', // '\x2D'
/** Regular expressions */
regexPunycode = /^xn--/,
regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
/** Error messages */
errors = {
'overflow': 'Overflow: input needs wider integers to process',
'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
'invalid-input': 'Invalid input'
},
/** Convenience shortcuts */
baseMinusTMin = base - tMin,
floor = Math.floor,
stringFromCharCode = String.fromCharCode,
/** Temporary variable */
key;
/*--------------------------------------------------------------------------*/
/**
* A generic error utility function.
* @private
* @param {String} type The error type.
* @returns {Error} Throws a `RangeError` with the applicable error message.
*/
function error(type) {
throw new RangeError(errors[type]);
}
/**
* A generic `Array#map` utility function.
* @private
* @param {Array} array The array to iterate over.
* @param {Function} callback The function that gets called for every array
* item.
* @returns {Array} A new array of values returned by the callback function.
*/
function map(array, fn) {
var length = array.length;
var result = [];
while (length--) {
result[length] = fn(array[length]);
}
return result;
}
/**
* A simple `Array#map`-like wrapper to work with domain name strings or email
* addresses.
* @private
* @param {String} domain The domain name or email address.
* @param {Function} callback The function that gets called for every
* character.
* @returns {Array} A new string of characters returned by the callback
* function.
*/
function mapDomain(string, fn) {
var parts = string.split('@');
var result = '';
if (parts.length > 1) {
// In email addresses, only the domain name should be punycoded. Leave
// the local part (i.e. everything up to `@`) intact.
result = parts[0] + '@';
string = parts[1];
}
// Avoid `split(regex)` for IE8 compatibility. See #17.
string = string.replace(regexSeparators, '\x2E');
var labels = string.split('.');
var encoded = map(labels, fn).join('.');
return result + encoded;
}
/**
* Creates an array containing the numeric code points of each Unicode
* character in the string. While JavaScript uses UCS-2 internally,
* this function will convert a pair of surrogate halves (each of which
* UCS-2 exposes as separate characters) into a single code point,
* matching UTF-16.
* @see `punycode.ucs2.encode`
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode.ucs2
* @name decode
* @param {String} string The Unicode input string (UCS-2).
* @returns {Array} The new array of code points.
*/
function ucs2decode(string) {
var output = [],
counter = 0,
length = string.length,
value,
extra;
while (counter < length) {
value = string.charCodeAt(counter++);
if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
// high surrogate, and there is a next character
extra = string.charCodeAt(counter++);
if ((extra & 0xFC00) == 0xDC00) { // low surrogate
output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
} else {
// unmatched surrogate; only append this code unit, in case the next
// code unit is the high surrogate of a surrogate pair
output.push(value);
counter--;
}
} else {
output.push(value);
}
}
return output;
}
/**
* Creates a string based on an array of numeric code points.
* @see `punycode.ucs2.decode`
* @memberOf punycode.ucs2
* @name encode
* @param {Array} codePoints The array of numeric code points.
* @returns {String} The new Unicode string (UCS-2).
*/
function ucs2encode(array) {
return map(array, function(value) {
var output = '';
if (value > 0xFFFF) {
value -= 0x10000;
output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
value = 0xDC00 | value & 0x3FF;
}
output += stringFromCharCode(value);
return output;
}).join('');
}
/**
* Converts a basic code point into a digit/integer.
* @see `digitToBasic()`
* @private
* @param {Number} codePoint The basic numeric code point value.
* @returns {Number} The numeric value of a basic code point (for use in
* representing integers) in the range `0` to `base - 1`, or `base` if
* the code point does not represent a value.
*/
function basicToDigit(codePoint) {
if (codePoint - 48 < 10) {
return codePoint - 22;
}
if (codePoint - 65 < 26) {
return codePoint - 65;
}
if (codePoint - 97 < 26) {
return codePoint - 97;
}
return base;
}
/**
* Converts a digit/integer into a basic code point.
* @see `basicToDigit()`
* @private
* @param {Number} digit The numeric value of a basic code point.
* @returns {Number} The basic code point whose value (when used for
* representing integers) is `digit`, which needs to be in the range
* `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
* used; else, the lowercase form is used. The behavior is undefined
* if `flag` is non-zero and `digit` has no uppercase form.
*/
function digitToBasic(digit, flag) {
// 0..25 map to ASCII a..z or A..Z
// 26..35 map to ASCII 0..9
return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
}
/**
* Bias adaptation function as per section 3.4 of RFC 3492.
* https://tools.ietf.org/html/rfc3492#section-3.4
* @private
*/
function adapt(delta, numPoints, firstTime) {
var k = 0;
delta = firstTime ? floor(delta / damp) : delta >> 1;
delta += floor(delta / numPoints);
for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
delta = floor(delta / baseMinusTMin);
}
return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
}
/**
* Converts a Punycode string of ASCII-only symbols to a string of Unicode
* symbols.
* @memberOf punycode
* @param {String} input The Punycode string of ASCII-only symbols.
* @returns {String} The resulting string of Unicode symbols.
*/
function decode(input) {
// Don't use UCS-2
var output = [],
inputLength = input.length,
out,
i = 0,
n = initialN,
bias = initialBias,
basic,
j,
index,
oldi,
w,
k,
digit,
t,
/** Cached calculation results */
baseMinusT;
// Handle the basic code points: let `basic` be the number of input code
// points before the last delimiter, or `0` if there is none, then copy
// the first basic code points to the output.
basic = input.lastIndexOf(delimiter);
if (basic < 0) {
basic = 0;
}
for (j = 0; j < basic; ++j) {
// if it's not a basic code point
if (input.charCodeAt(j) >= 0x80) {
error('not-basic');
}
output.push(input.charCodeAt(j));
}
// Main decoding loop: start just after the last delimiter if any basic code
// points were copied; start at the beginning otherwise.
for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
// `index` is the index of the next character to be consumed.
// Decode a generalized variable-length integer into `delta`,
// which gets added to `i`. The overflow checking is easier
// if we increase `i` as we go, then subtract off its starting
// value at the end to obtain `delta`.
for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
if (index >= inputLength) {
error('invalid-input');
}
digit = basicToDigit(input.charCodeAt(index++));
if (digit >= base || digit > floor((maxInt - i) / w)) {
error('overflow');
}
i += digit * w;
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (digit < t) {
break;
}
baseMinusT = base - t;
if (w > floor(maxInt / baseMinusT)) {
error('overflow');
}
w *= baseMinusT;
}
out = output.length + 1;
bias = adapt(i - oldi, out, oldi == 0);
// `i` was supposed to wrap around from `out` to `0`,
// incrementing `n` each time, so we'll fix that now:
if (floor(i / out) > maxInt - n) {
error('overflow');
}
n += floor(i / out);
i %= out;
// Insert `n` at position `i` of the output
output.splice(i++, 0, n);
}
return ucs2encode(output);
}
/**
* Converts a string of Unicode symbols (e.g. a domain name label) to a
* Punycode string of ASCII-only symbols.
* @memberOf punycode
* @param {String} input The string of Unicode symbols.
* @returns {String} The resulting Punycode string of ASCII-only symbols.
*/
function encode(input) {
var n,
delta,
handledCPCount,
basicLength,
bias,
j,
m,
q,
k,
t,
currentValue,
output = [],
/** `inputLength` will hold the number of code points in `input`. */
inputLength,
/** Cached calculation results */
handledCPCountPlusOne,
baseMinusT,
qMinusT;
// Convert the input in UCS-2 to Unicode
input = ucs2decode(input);
// Cache the length
inputLength = input.length;
// Initialize the state
n = initialN;
delta = 0;
bias = initialBias;
// Handle the basic code points
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < 0x80) {
output.push(stringFromCharCode(currentValue));
}
}
handledCPCount = basicLength = output.length;
// `handledCPCount` is the number of code points that have been handled;
// `basicLength` is the number of basic code points.
// Finish the basic string - if it is not empty - with a delimiter
if (basicLength) {
output.push(delimiter);
}
// Main encoding loop:
while (handledCPCount < inputLength) {
// All non-basic code points < n have been handled already. Find the next
// larger one:
for (m = maxInt, j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue >= n && currentValue < m) {
m = currentValue;
}
}
// Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
// but guard against overflow
handledCPCountPlusOne = handledCPCount + 1;
if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
error('overflow');
}
delta += (m - n) * handledCPCountPlusOne;
n = m;
for (j = 0; j < inputLength; ++j) {
currentValue = input[j];
if (currentValue < n && ++delta > maxInt) {
error('overflow');
}
if (currentValue == n) {
// Represent delta as a generalized variable-length integer
for (q = delta, k = base; /* no condition */; k += base) {
t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
if (q < t) {
break;
}
qMinusT = q - t;
baseMinusT = base - t;
output.push(
stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
);
q = floor(qMinusT / baseMinusT);
}
output.push(stringFromCharCode(digitToBasic(q, 0)));
bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
delta = 0;
++handledCPCount;
}
}
++delta;
++n;
}
return output.join('');
}
/**
* Converts a Punycode string representing a domain name or an email address
* to Unicode. Only the Punycoded parts of the input will be converted, i.e.
* it doesn't matter if you call it on a string that has already been
* converted to Unicode.
* @memberOf punycode
* @param {String} input The Punycoded domain name or email address to
* convert to Unicode.
* @returns {String} The Unicode representation of the given Punycode
* string.
*/
function toUnicode(input) {
return mapDomain(input, function(string) {
return regexPunycode.test(string)
? decode(string.slice(4).toLowerCase())
: string;
});
}
/**
* Converts a Unicode string representing a domain name or an email address to
* Punycode. Only the non-ASCII parts of the domain name will be converted,
* i.e. it doesn't matter if you call it with a domain that's already in
* ASCII.
* @memberOf punycode
* @param {String} input The domain name or email address to convert, as a
* Unicode string.
* @returns {String} The Punycode representation of the given domain name or
* email address.
*/
function toASCII(input) {
return mapDomain(input, function(string) {
return regexNonASCII.test(string)
? 'xn--' + encode(string)
: string;
});
}
/*--------------------------------------------------------------------------*/
/** Define the public API */
punycode = {
/**
* A string representing the current Punycode.js version number.
* @memberOf punycode
* @type String
*/
'version': '1.4.1',
/**
* An object of methods to convert from JavaScript's internal character
* representation (UCS-2) to Unicode code points, and back.
* @see <https://mathiasbynens.be/notes/javascript-encoding>
* @memberOf punycode
* @type Object
*/
'ucs2': {
'decode': ucs2decode,
'encode': ucs2encode
},
'decode': decode,
'encode': encode,
'toASCII': toASCII,
'toUnicode': toUnicode
};
/** Expose `punycode` */
// Some AMD build optimizers, like r.js, check for specific condition patterns
// like the following:
if (
true
) {
!(__WEBPACK_AMD_DEFINE_RESULT__ = (function() {
return punycode;
}).call(exports, __webpack_require__, exports, module),
__WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
} else if (freeExports && freeModule) {
if (module.exports == freeExports) {
// in Node.js, io.js, or RingoJS v0.8.0+
freeModule.exports = punycode;
} else {
// in Narwhal or RingoJS v0.7.0-
for (key in punycode) {
punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
}
}
} else {
// in Rhino or a web browser
root.punycode = punycode;
}
}(this));
/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(40)(module), __webpack_require__(7)))
/***/ }),
/* 107 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
module.exports = {
isString: function(arg) {
return typeof(arg) === 'string';
},
isObject: function(arg) {
return typeof(arg) === 'object' && arg !== null;
},
isNull: function(arg) {
return arg === null;
},
isNullOrUndefined: function(arg) {
return arg == null;
}
};
/***/ }),
/* 108 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
exports.decode = exports.parse = __webpack_require__(109);
exports.encode = exports.stringify = __webpack_require__(110);
/***/ }),
/* 109 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
// If obj.hasOwnProperty has been overridden, then calling
// obj.hasOwnProperty(prop) will break.
// See: https://github.com/joyent/node/issues/1707
function hasOwnProperty(obj, prop) {
return Object.prototype.hasOwnProperty.call(obj, prop);
}
module.exports = function(qs, sep, eq, options) {
sep = sep || '&';
eq = eq || '=';
var obj = {};
if (typeof qs !== 'string' || qs.length === 0) {
return obj;
}
var regexp = /\+/g;
qs = qs.split(sep);
var maxKeys = 1000;
if (options && typeof options.maxKeys === 'number') {
maxKeys = options.maxKeys;
}
var len = qs.length;
// maxKeys <= 0 means that we should not limit keys count
if (maxKeys > 0 && len > maxKeys) {
len = maxKeys;
}
for (var i = 0; i < len; ++i) {
var x = qs[i].replace(regexp, '%20'),
idx = x.indexOf(eq),
kstr, vstr, k, v;
if (idx >= 0) {
kstr = x.substr(0, idx);
vstr = x.substr(idx + 1);
} else {
kstr = x;
vstr = '';
}
k = decodeURIComponent(kstr);
v = decodeURIComponent(vstr);
if (!hasOwnProperty(obj, k)) {
obj[k] = v;
} else if (isArray(obj[k])) {
obj[k].push(v);
} else {
obj[k] = [obj[k], v];
}
}
return obj;
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
/***/ }),
/* 110 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
// Copyright Joyent, Inc. and other Node contributors.
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to permit
// persons to whom the Software is furnished to do so, subject to the
// following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
// USE OR OTHER DEALINGS IN THE SOFTWARE.
var stringifyPrimitive = function(v) {
switch (typeof v) {
case 'string':
return v;
case 'boolean':
return v ? 'true' : 'false';
case 'number':
return isFinite(v) ? v : '';
default:
return '';
}
};
module.exports = function(obj, sep, eq, name) {
sep = sep || '&';
eq = eq || '=';
if (obj === null) {
obj = undefined;
}
if (typeof obj === 'object') {
return map(objectKeys(obj), function(k) {
var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
if (isArray(obj[k])) {
return map(obj[k], function(v) {
return ks + encodeURIComponent(stringifyPrimitive(v));
}).join(sep);
} else {
return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
}
}).join(sep);
}
if (!name) return '';
return encodeURIComponent(stringifyPrimitive(name)) + eq +
encodeURIComponent(stringifyPrimitive(obj));
};
var isArray = Array.isArray || function (xs) {
return Object.prototype.toString.call(xs) === '[object Array]';
};
function map (xs, f) {
if (xs.map) return xs.map(f);
var res = [];
for (var i = 0; i < xs.length; i++) {
res.push(f(xs[i], i));
}
return res;
}
var objectKeys = Object.keys || function (obj) {
var res = [];
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
}
return res;
};
/***/ }),
/* 111 */
/***/ (function(module, exports, __webpack_require__) {
"use strict";
var helpers = __webpack_require__(32);
/** @type ValidatorResult */
var ValidatorResult = helpers.ValidatorResult;
/** @type SchemaError */
var SchemaError = helpers.SchemaError;
var attribute = {};
attribute.ignoreProperties = {
// informative properties
'id': true,
'default': true,
'description': true,
'title': true,
// arguments to other properties
'exclusiveMinimum': true,
'exclusiveMaximum': true,
'additionalItems': true,
// special-handled properties
'$schema': true,
'$ref': true,
'extends': true
};
/**
* @name validators
*/
var validators = attribute.validators = {};
/**
* Validates whether the instance if of a certain type
* @param instance
* @param schema
* @param options
* @param ctx
* @return {ValidatorResult|null}
*/
validators.type = function validateType (instance, schema, options, ctx) {
// Ignore undefined instances
if (instance === undefined) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
var types = Array.isArray(schema.type) ? schema.type : [schema.type];
if (!types.some(this.testType.bind(this, instance, schema, options, ctx))) {
var list = types.map(function (v) {
return v.id && ('<' + v.id + '>') || (v+'');
});
result.addError({
name: 'type',
argument: list,
message: "is not of a type(s) " + list,
});
}
return result;
};
function testSchema(instance, options, ctx, callback, schema){
var res = this.validateSchema(instance, schema, options, ctx);
if (! res.valid && callback instanceof Function) {
callback(res);
}
return res.valid;
}
/**
* Validates whether the instance matches some of the given schemas
* @param instance
* @param schema
* @param options
* @param ctx
* @return {ValidatorResult|null}
*/
validators.anyOf = function validateAnyOf (instance, schema, options, ctx) {
// Ignore undefined instances
if (instance === undefined) {
return null;
}
var result = new ValidatorResult(instance, schema, options, ctx);
var inner = new ValidatorResult(instance, schema, options, ctx);
if (!Array.isArray(schema.anyOf)){
throw new SchemaError("anyOf must be an array");
}
if (!schema.anyOf.some(
testSchema.bind(
this, instance, options, ctx, function(res){inner.importErrors(res);}
))) {
var list = schema.anyOf.map(function (v, i) {
return (v.id && ('<' + v.id + '>')) || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']';
});
if (options.nestedErrors) {
result.importErrors(inner);
}
result.addError({
name: 'anyOf',
argument: list,
message: "is not any of " + list.join(','),
});
}
return result;
};
/**
* Validates whether the instance matches every given schema
* @param instance
* @param schema
* @param options
* @param ctx
* @return {String|null}
*/
validators.allOf = function validateAllOf (instance, schema, options, ctx) {
// Ignore undefined instances
if (instance === undefined) {
return null;
}
if (!Array.isArray(schema.allOf)){
throw new SchemaError("allOf must be an array");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var self = this;
schema.allOf.forEach(function(v, i){
var valid = self.validateSchema(instance, v, options, ctx);
if(!valid.valid){
var msg = (v.id && ('<' + v.id + '>')) || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']';
result.addError({
name: 'allOf',
argument: { id: msg, length: valid.errors.length, valid: valid },
message: 'does not match allOf schema ' + msg + ' with ' + valid.errors.length + ' error[s]:',
});
result.importErrors(valid);
}
});
return result;
};
/**
* Validates whether the instance matches exactly one of the given schemas
* @param instance
* @param schema
* @param options
* @param ctx
* @return {String|null}
*/
validators.oneOf = function validateOneOf (instance, schema, options, ctx) {
// Ignore undefined instances
if (instance === undefined) {
return null;
}
if (!Array.isArray(schema.oneOf)){
throw new SchemaError("oneOf must be an array");
}
var result = new ValidatorResult(instance, schema, options, ctx);
var inner = new ValidatorResult(instance, schema, options, ctx);
var count = schema.oneOf.filter(
testSchema.bind(
this, instance, options, ctx, function(res) {inner.importErrors(res);}
) ).length;
var list = schema.oneOf.map(function (v, i) {
return (v.id && ('<' + v.id + '>')) || (v.title && JSON.stringify(v.title)) || (v['$ref'] && ('<' + v['$ref'] + '>')) || '[subschema '+i+']';
});
if (count!==1) {
if (options.nestedErrors) {
result.importErrors(inner);
}
result.addError({
name: 'oneOf',
argument: list,
message: "is not exactly one from " + list.join(','),
});
}
return result;
};
/**
* Validates properties
* @param instance
* @param schema
* @param options
* @param ctx
* @return {String|null|ValidatorResult}
*/
validators.properties = function validateProperties (instance, schema, options, ctx) {
if(instance === undefined || !(instance instanceof Object)) return;
var result = new ValidatorResult(instance, schema, options, ctx);
var properties = schema.properties || {};
for (var property in properties) {
if (typeof options.preValidateProperty == 'function') {
options.preValidateProperty(instance, property, properties[property], options, ctx);
}
var prop = (instance || undefined) && instance[property];
var res = this.validateSchema(prop, properties[property], options, ctx.makeChild(properties[property], property));
if(res.instance !== result.instance[property]) result.instance[property] = res.instance;
result.importErrors(res);
}
return result;
};
/**
* Test a specific property within in instance against the additionalProperties schema attribute
* This ignores properties with definitions in the properties schema attribute, but no other attributes.
* If too many more types of property-existance tests pop up they may need their own class of tests (like `type` has)
* @private
* @return {boolean}
*/
function testAdditionalProperty (instance, schema, options, ctx, property, result) {
if (schema.properties && schema.properties[property] !== undefined) {
return;
}
if (schema.additionalProperties === false) {
result.addError({
name: 'additionalProperties',
argument: property,
message: "additionalProperty " + JSON.stringify(property) + " exists in instance when not allowed",
});
} else {
var additionalProperties = schema.additionalProperties || {};
if (typeof options.preValidateProperty == 'function') {
options.preValidateProperty(instance, property, additionalProperties, options, ctx);
}
var res = this.validateSchema(instance[property], additionalProperties, options, ctx.makeChild(additionalProperties, property));
if(res.instance !== resul
View raw

(Sorry about that, but we can’t show files that are this big right now.)

View raw

(Sorry about that, but we can’t show files that are this big right now.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment