From 153ae217fa5362099b981f79bc1b056051c40288 Mon Sep 17 00:00:00 2001 From: David Dias Date: Wed, 28 Jun 2017 20:14:51 +0100 Subject: [PATCH 1/7] docs: update the readme to reflect the WebRTC config steps for Node.js --- README.md | 93 ++++++++++++++++++++++++------------------------------- 1 file changed, 40 insertions(+), 53 deletions(-) diff --git a/README.md b/README.md index 9817c736cd..e8953f17c0 100644 --- a/README.md +++ b/README.md @@ -7,59 +7,28 @@

The JavaScript implementation of the IPFS protocol.

- - - - - - - - - + + +
- - - - - - - - - + + +

- - - - - - - - - + + +
- - - - - - - - - - - - - - - + + + + +
+ -->

### Project status @@ -138,18 +107,17 @@ In order to use js-ipfs as a CLI, you must install it with the `global` flag. Ru $ npm install ipfs --global ``` -The CLI is available by using the command `jsipfs` in your terminal. This is aliased, instead of using `ipfs`, to make sure it does not conflict with the Go implementation. - -### Use in the browser with browserify, webpack or any bundler +The CLI is available by using the command `jsipfs` in your terminal. This is aliased, instead of using `ipfs`, to make sure it does not conflict with the [Go implementation](https://github.com/ipfs/go-ipfs). -You can find examples of how to do this bundling at: `https://github.com/ipfs/js-ipfs/tree/master/examples`. If you are using webpack, make sure to use version 2 or above, otherwise it won't work. +### Use in the browser -### Use in a browser using a script tag +##### With browserify, webpack or any bundler -Loading this module in a browser (using a ` + + diff --git a/examples/electron/main.js b/examples/electron/main.js new file mode 100755 index 0000000000..d2c3af6976 --- /dev/null +++ b/examples/electron/main.js @@ -0,0 +1,56 @@ +const electron = require('electron') +const app = electron.app +const BrowserWindow = electron.BrowserWindow + +const IPFS = require('ipfs') +const path = require('path') +const url = require('url') + +let mainWindow + +function createWindow () { + mainWindow = new BrowserWindow({width: 800, height: 600}) + + // and load the index.html of the app. + mainWindow.loadURL(url.format({ + pathname: path.join(__dirname, 'index.html'), + protocol: 'file:', + slashes: true + })) + + // Open the DevTools. + mainWindow.webContents.openDevTools() + + // Emitted when the window is closed. + mainWindow.on('closed', () => { + mainWindow = null + }) +} + +app.on('ready', () => { + createWindow() + + // Spawn your IPFS node \o/ + const node = new IPFS() + + node.on('ready', () => { + node.id((err, id) => { + if (err) { + return console.log(err) + } + console.log(id) + }) + }) +}) + +// Quit when all windows are closed. +app.on('window-all-closed', () => { + if (process.platform !== 'darwin') { app.quit() } +}) + +app.on('activate', () => { + if (mainWindow === null) { createWindow() } +}) + +// In this file you can include the rest of your app's specific main process +// code. You can also put them in separate files and require them here. diff --git a/examples/electron/package.json b/examples/electron/package.json new file mode 100755 index 0000000000..579cabbc15 --- /dev/null +++ b/examples/electron/package.json @@ -0,0 +1,22 @@ +{ + "name": "js-ipfs-in-electron", + "version": "0.0.0", + "description": "A minimal Electron application with js-ipfs", + "main": "main.js", + "scripts": { + "start": "electron .", + "postinstall": "electron-rebuild" + }, + "keywords": [ + "Electron", + "IPFS", + "Example" + ], + "author": "David Dias ", + "license": "MIT", + "devDependencies": { + "electron": "~1.6.11", + "electron-rebuild": "^1.5.11", + "ipfs": "ipfs/js-ipfs#feat\/no-wrtc-by-default" + } +} diff --git a/examples/electron/renderer.js b/examples/electron/renderer.js new file mode 100755 index 0000000000..e69de29bb2 From 83ead4bbf06a381c1767eefe9e64ee40e35b27cd Mon Sep 17 00:00:00 2001 From: David Dias Date: Thu, 29 Jun 2017 13:39:30 +0100 Subject: [PATCH 4/7] chore: update deps --- package.json | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/package.json b/package.json index 35d134e302..634237a757 100644 --- a/package.json +++ b/package.json @@ -72,7 +72,7 @@ "expose-loader": "^0.7.3", "form-data": "^2.2.0", "gulp": "^3.9.1", - "interface-ipfs-core": "~0.29.0", + "interface-ipfs-core": "~0.29.1", "ipfsd-ctl": "~0.21.0", "left-pad": "^1.1.3", "lodash": "^4.17.4", @@ -81,14 +81,14 @@ "nexpect": "^0.5.0", "pre-commit": "^1.2.2", "pretty-bytes": "^4.0.2", - "qs": "^6.4.0", + "qs": "^6.5.0", "random-fs": "^1.0.3", "rimraf": "^2.6.1", "stream-to-promise": "^2.2.0", "transform-loader": "^0.2.4" }, "dependencies": { - "async": "^2.4.1", + "async": "^2.5.0", "bl": "^1.2.1", "boom": "^5.1.0", "cids": "^0.5.0", @@ -98,7 +98,7 @@ "hapi": "^16.4.3", "hapi-set-header": "^1.0.2", "hoek": "^4.1.1", - "ipfs-api": "^14.0.3", + "ipfs-api": "^14.0.4", "ipfs-bitswap": "~0.13.1", "ipfs-block": "~0.6.0", "ipfs-block-service": "~0.9.1", @@ -111,8 +111,8 @@ "isstream": "^0.1.2", "joi": "^10.6.0", "libp2p-floodsub": "~0.9.4", - "libp2p-ipfs-browser": "~0.24.1", - "libp2p-ipfs-nodejs": "~0.25.2", + "libp2p-ipfs-browser": "~0.25.0", + "libp2p-ipfs-nodejs": "~0.26.0", "lodash.flatmap": "^4.5.0", "lodash.get": "^4.4.2", "lodash.has": "^4.5.2", @@ -132,13 +132,13 @@ "pull-file": "^1.0.0", "pull-paramap": "^1.2.2", "pull-pushable": "^2.1.1", - "pull-sort": "^1.0.0", + "pull-sort": "^1.0.1", "pull-stream": "^3.6.0", "pull-stream-to-stream": "^1.3.4", "pull-zip": "^2.0.1", "read-pkg-up": "^2.0.0", "readable-stream": "1.1.14", - "safe-buffer": "^5.1.0", + "safe-buffer": "^5.1.1", "stream-to-pull-stream": "^1.7.2", "tar-stream": "^1.5.4", "temp": "^0.8.3", From eb21165ec59f0620bedb39a989f0c89f1b48062d Mon Sep 17 00:00:00 2001 From: David Dias Date: Thu, 29 Jun 2017 15:06:03 +0100 Subject: [PATCH 5/7] chore: remove bundle --- .gitignore | 3 +- examples/electron/bundle.js | 133802 --------------------------------- 2 files changed, 2 insertions(+), 133803 deletions(-) delete mode 100644 examples/electron/bundle.js diff --git a/.gitignore b/.gitignore index 1f5aa33552..1f90ef6ecd 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,7 @@ **/node_modules/ **/*.log test/repo-tests* +**/bundle.js # Logs logs @@ -35,4 +36,4 @@ lib dist test/test-data/go-ipfs-repo/LOCK test/test-data/go-ipfs-repo/LOG -test/test-data/go-ipfs-repo/LOG.old \ No newline at end of file +test/test-data/go-ipfs-repo/LOG.old diff --git a/examples/electron/bundle.js b/examples/electron/bundle.js deleted file mode 100644 index 021daec8fb..0000000000 --- a/examples/electron/bundle.js +++ /dev/null @@ -1,133802 +0,0 @@ -(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 { - node.id((err, id) => { - if (err) { - el.innerText = 'An error as happened' + err - return - } - el.innerText = JSON.stringify(id, 2) - }) -}) - -},{"../..":757}],2:[function(require,module,exports){ -var asn1 = exports; - -asn1.bignum = require('bn.js'); - -asn1.define = require('./asn1/api').define; -asn1.base = require('./asn1/base'); -asn1.constants = require('./asn1/constants'); -asn1.decoders = require('./asn1/decoders'); -asn1.encoders = require('./asn1/encoders'); - -},{"./asn1/api":3,"./asn1/base":5,"./asn1/constants":9,"./asn1/decoders":11,"./asn1/encoders":14,"bn.js":66}],3:[function(require,module,exports){ -var asn1 = require('../asn1'); -var inherits = require('inherits'); - -var api = exports; - -api.define = function define(name, body) { - return new Entity(name, body); -}; - -function Entity(name, body) { - this.name = name; - this.body = body; - - this.decoders = {}; - this.encoders = {}; -}; - -Entity.prototype._createNamed = function createNamed(base) { - var named; - try { - named = require('vm').runInThisContext( - '(function ' + this.name + '(entity) {\n' + - ' this._initNamed(entity);\n' + - '})' - ); - } catch (e) { - named = function (entity) { - this._initNamed(entity); - }; - } - inherits(named, base); - named.prototype._initNamed = function initnamed(entity) { - base.call(this, entity); - }; - - return new named(this); -}; - -Entity.prototype._getDecoder = function _getDecoder(enc) { - enc = enc || 'der'; - // Lazily create decoder - if (!this.decoders.hasOwnProperty(enc)) - this.decoders[enc] = this._createNamed(asn1.decoders[enc]); - return this.decoders[enc]; -}; - -Entity.prototype.decode = function decode(data, enc, options) { - return this._getDecoder(enc).decode(data, options); -}; - -Entity.prototype._getEncoder = function _getEncoder(enc) { - enc = enc || 'der'; - // Lazily create encoder - if (!this.encoders.hasOwnProperty(enc)) - this.encoders[enc] = this._createNamed(asn1.encoders[enc]); - return this.encoders[enc]; -}; - -Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { - return this._getEncoder(enc).encode(data, reporter); -}; - -},{"../asn1":2,"inherits":216,"vm":1037}],4:[function(require,module,exports){ -var inherits = require('inherits'); -var Reporter = require('../base').Reporter; -var Buffer = require('buffer').Buffer; - -function DecoderBuffer(base, options) { - Reporter.call(this, options); - if (!Buffer.isBuffer(base)) { - this.error('Input not Buffer'); - return; - } - - this.base = base; - this.offset = 0; - this.length = base.length; -} -inherits(DecoderBuffer, Reporter); -exports.DecoderBuffer = DecoderBuffer; - -DecoderBuffer.prototype.save = function save() { - return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; -}; - -DecoderBuffer.prototype.restore = function restore(save) { - // Return skipped data - var res = new DecoderBuffer(this.base); - res.offset = save.offset; - res.length = this.offset; - - this.offset = save.offset; - Reporter.prototype.restore.call(this, save.reporter); - - return res; -}; - -DecoderBuffer.prototype.isEmpty = function isEmpty() { - return this.offset === this.length; -}; - -DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { - if (this.offset + 1 <= this.length) - return this.base.readUInt8(this.offset++, true); - else - return this.error(fail || 'DecoderBuffer overrun'); -} - -DecoderBuffer.prototype.skip = function skip(bytes, fail) { - if (!(this.offset + bytes <= this.length)) - return this.error(fail || 'DecoderBuffer overrun'); - - var res = new DecoderBuffer(this.base); - - // Share reporter state - res._reporterState = this._reporterState; - - res.offset = this.offset; - res.length = this.offset + bytes; - this.offset += bytes; - return res; -} - -DecoderBuffer.prototype.raw = function raw(save) { - return this.base.slice(save ? save.offset : this.offset, this.length); -} - -function EncoderBuffer(value, reporter) { - if (Array.isArray(value)) { - this.length = 0; - this.value = value.map(function(item) { - if (!(item instanceof EncoderBuffer)) - item = new EncoderBuffer(item, reporter); - this.length += item.length; - return item; - }, this); - } else if (typeof value === 'number') { - if (!(0 <= value && value <= 0xff)) - return reporter.error('non-byte EncoderBuffer value'); - this.value = value; - this.length = 1; - } else if (typeof value === 'string') { - this.value = value; - this.length = Buffer.byteLength(value); - } else if (Buffer.isBuffer(value)) { - this.value = value; - this.length = value.length; - } else { - return reporter.error('Unsupported type: ' + typeof value); - } -} -exports.EncoderBuffer = EncoderBuffer; - -EncoderBuffer.prototype.join = function join(out, offset) { - if (!out) - out = new Buffer(this.length); - if (!offset) - offset = 0; - - if (this.length === 0) - return out; - - if (Array.isArray(this.value)) { - this.value.forEach(function(item) { - item.join(out, offset); - offset += item.length; - }); - } else { - if (typeof this.value === 'number') - out[offset] = this.value; - else if (typeof this.value === 'string') - out.write(this.value, offset); - else if (Buffer.isBuffer(this.value)) - this.value.copy(out, offset); - offset += this.length; - } - - return out; -}; - -},{"../base":5,"buffer":987,"inherits":216}],5:[function(require,module,exports){ -var base = exports; - -base.Reporter = require('./reporter').Reporter; -base.DecoderBuffer = require('./buffer').DecoderBuffer; -base.EncoderBuffer = require('./buffer').EncoderBuffer; -base.Node = require('./node'); - -},{"./buffer":4,"./node":6,"./reporter":7}],6:[function(require,module,exports){ -var Reporter = require('../base').Reporter; -var EncoderBuffer = require('../base').EncoderBuffer; -var DecoderBuffer = require('../base').DecoderBuffer; -var assert = require('minimalistic-assert'); - -// Supported tags -var tags = [ - 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', - 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', - 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', - 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' -]; - -// Public methods list -var methods = [ - 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', - 'any', 'contains' -].concat(tags); - -// Overrided methods list -var overrided = [ - '_peekTag', '_decodeTag', '_use', - '_decodeStr', '_decodeObjid', '_decodeTime', - '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', - - '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', - '_encodeNull', '_encodeInt', '_encodeBool' -]; - -function Node(enc, parent) { - var state = {}; - this._baseState = state; - - state.enc = enc; - - state.parent = parent || null; - state.children = null; - - // State - state.tag = null; - state.args = null; - state.reverseArgs = null; - state.choice = null; - state.optional = false; - state.any = false; - state.obj = false; - state.use = null; - state.useDecoder = null; - state.key = null; - state['default'] = null; - state.explicit = null; - state.implicit = null; - state.contains = null; - - // Should create new instance on each method - if (!state.parent) { - state.children = []; - this._wrap(); - } -} -module.exports = Node; - -var stateProps = [ - 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', - 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', - 'implicit', 'contains' -]; - -Node.prototype.clone = function clone() { - var state = this._baseState; - var cstate = {}; - stateProps.forEach(function(prop) { - cstate[prop] = state[prop]; - }); - var res = new this.constructor(cstate.parent); - res._baseState = cstate; - return res; -}; - -Node.prototype._wrap = function wrap() { - var state = this._baseState; - methods.forEach(function(method) { - this[method] = function _wrappedMethod() { - var clone = new this.constructor(this); - state.children.push(clone); - return clone[method].apply(clone, arguments); - }; - }, this); -}; - -Node.prototype._init = function init(body) { - var state = this._baseState; - - assert(state.parent === null); - body.call(this); - - // Filter children - state.children = state.children.filter(function(child) { - return child._baseState.parent === this; - }, this); - assert.equal(state.children.length, 1, 'Root node can have only one child'); -}; - -Node.prototype._useArgs = function useArgs(args) { - var state = this._baseState; - - // Filter children and args - var children = args.filter(function(arg) { - return arg instanceof this.constructor; - }, this); - args = args.filter(function(arg) { - return !(arg instanceof this.constructor); - }, this); - - if (children.length !== 0) { - assert(state.children === null); - state.children = children; - - // Replace parent to maintain backward link - children.forEach(function(child) { - child._baseState.parent = this; - }, this); - } - if (args.length !== 0) { - assert(state.args === null); - state.args = args; - state.reverseArgs = args.map(function(arg) { - if (typeof arg !== 'object' || arg.constructor !== Object) - return arg; - - var res = {}; - Object.keys(arg).forEach(function(key) { - if (key == (key | 0)) - key |= 0; - var value = arg[key]; - res[value] = key; - }); - return res; - }); - } -}; - -// -// Overrided methods -// - -overrided.forEach(function(method) { - Node.prototype[method] = function _overrided() { - var state = this._baseState; - throw new Error(method + ' not implemented for encoding: ' + state.enc); - }; -}); - -// -// Public methods -// - -tags.forEach(function(tag) { - Node.prototype[tag] = function _tagMethod() { - var state = this._baseState; - var args = Array.prototype.slice.call(arguments); - - assert(state.tag === null); - state.tag = tag; - - this._useArgs(args); - - return this; - }; -}); - -Node.prototype.use = function use(item) { - assert(item); - var state = this._baseState; - - assert(state.use === null); - state.use = item; - - return this; -}; - -Node.prototype.optional = function optional() { - var state = this._baseState; - - state.optional = true; - - return this; -}; - -Node.prototype.def = function def(val) { - var state = this._baseState; - - assert(state['default'] === null); - state['default'] = val; - state.optional = true; - - return this; -}; - -Node.prototype.explicit = function explicit(num) { - var state = this._baseState; - - assert(state.explicit === null && state.implicit === null); - state.explicit = num; - - return this; -}; - -Node.prototype.implicit = function implicit(num) { - var state = this._baseState; - - assert(state.explicit === null && state.implicit === null); - state.implicit = num; - - return this; -}; - -Node.prototype.obj = function obj() { - var state = this._baseState; - var args = Array.prototype.slice.call(arguments); - - state.obj = true; - - if (args.length !== 0) - this._useArgs(args); - - return this; -}; - -Node.prototype.key = function key(newKey) { - var state = this._baseState; - - assert(state.key === null); - state.key = newKey; - - return this; -}; - -Node.prototype.any = function any() { - var state = this._baseState; - - state.any = true; - - return this; -}; - -Node.prototype.choice = function choice(obj) { - var state = this._baseState; - - assert(state.choice === null); - state.choice = obj; - this._useArgs(Object.keys(obj).map(function(key) { - return obj[key]; - })); - - return this; -}; - -Node.prototype.contains = function contains(item) { - var state = this._baseState; - - assert(state.use === null); - state.contains = item; - - return this; -}; - -// -// Decoding -// - -Node.prototype._decode = function decode(input, options) { - var state = this._baseState; - - // Decode root node - if (state.parent === null) - return input.wrapResult(state.children[0]._decode(input, options)); - - var result = state['default']; - var present = true; - - var prevKey = null; - if (state.key !== null) - prevKey = input.enterKey(state.key); - - // Check if tag is there - if (state.optional) { - var tag = null; - if (state.explicit !== null) - tag = state.explicit; - else if (state.implicit !== null) - tag = state.implicit; - else if (state.tag !== null) - tag = state.tag; - - if (tag === null && !state.any) { - // Trial and Error - var save = input.save(); - try { - if (state.choice === null) - this._decodeGeneric(state.tag, input, options); - else - this._decodeChoice(input, options); - present = true; - } catch (e) { - present = false; - } - input.restore(save); - } else { - present = this._peekTag(input, tag, state.any); - - if (input.isError(present)) - return present; - } - } - - // Push object on stack - var prevObj; - if (state.obj && present) - prevObj = input.enterObject(); - - if (present) { - // Unwrap explicit values - if (state.explicit !== null) { - var explicit = this._decodeTag(input, state.explicit); - if (input.isError(explicit)) - return explicit; - input = explicit; - } - - var start = input.offset; - - // Unwrap implicit and normal values - if (state.use === null && state.choice === null) { - if (state.any) - var save = input.save(); - var body = this._decodeTag( - input, - state.implicit !== null ? state.implicit : state.tag, - state.any - ); - if (input.isError(body)) - return body; - - if (state.any) - result = input.raw(save); - else - input = body; - } - - if (options && options.track && state.tag !== null) - options.track(input.path(), start, input.length, 'tagged'); - - if (options && options.track && state.tag !== null) - options.track(input.path(), input.offset, input.length, 'content'); - - // Select proper method for tag - if (state.any) - result = result; - else if (state.choice === null) - result = this._decodeGeneric(state.tag, input, options); - else - result = this._decodeChoice(input, options); - - if (input.isError(result)) - return result; - - // Decode children - if (!state.any && state.choice === null && state.children !== null) { - state.children.forEach(function decodeChildren(child) { - // NOTE: We are ignoring errors here, to let parser continue with other - // parts of encoded data - child._decode(input, options); - }); - } - - // Decode contained/encoded by schema, only in bit or octet strings - if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { - var data = new DecoderBuffer(result); - result = this._getUse(state.contains, input._reporterState.obj) - ._decode(data, options); - } - } - - // Pop object - if (state.obj && present) - result = input.leaveObject(prevObj); - - // Set key - if (state.key !== null && (result !== null || present === true)) - input.leaveKey(prevKey, state.key, result); - else if (prevKey !== null) - input.exitKey(prevKey); - - return result; -}; - -Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { - var state = this._baseState; - - if (tag === 'seq' || tag === 'set') - return null; - if (tag === 'seqof' || tag === 'setof') - return this._decodeList(input, tag, state.args[0], options); - else if (/str$/.test(tag)) - return this._decodeStr(input, tag, options); - else if (tag === 'objid' && state.args) - return this._decodeObjid(input, state.args[0], state.args[1], options); - else if (tag === 'objid') - return this._decodeObjid(input, null, null, options); - else if (tag === 'gentime' || tag === 'utctime') - return this._decodeTime(input, tag, options); - else if (tag === 'null_') - return this._decodeNull(input, options); - else if (tag === 'bool') - return this._decodeBool(input, options); - else if (tag === 'objDesc') - return this._decodeStr(input, tag, options); - else if (tag === 'int' || tag === 'enum') - return this._decodeInt(input, state.args && state.args[0], options); - - if (state.use !== null) { - return this._getUse(state.use, input._reporterState.obj) - ._decode(input, options); - } else { - return input.error('unknown tag: ' + tag); - } -}; - -Node.prototype._getUse = function _getUse(entity, obj) { - - var state = this._baseState; - // Create altered use decoder if implicit is set - state.useDecoder = this._use(entity, obj); - assert(state.useDecoder._baseState.parent === null); - state.useDecoder = state.useDecoder._baseState.children[0]; - if (state.implicit !== state.useDecoder._baseState.implicit) { - state.useDecoder = state.useDecoder.clone(); - state.useDecoder._baseState.implicit = state.implicit; - } - return state.useDecoder; -}; - -Node.prototype._decodeChoice = function decodeChoice(input, options) { - var state = this._baseState; - var result = null; - var match = false; - - Object.keys(state.choice).some(function(key) { - var save = input.save(); - var node = state.choice[key]; - try { - var value = node._decode(input, options); - if (input.isError(value)) - return false; - - result = { type: key, value: value }; - match = true; - } catch (e) { - input.restore(save); - return false; - } - return true; - }, this); - - if (!match) - return input.error('Choice not matched'); - - return result; -}; - -// -// Encoding -// - -Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { - return new EncoderBuffer(data, this.reporter); -}; - -Node.prototype._encode = function encode(data, reporter, parent) { - var state = this._baseState; - if (state['default'] !== null && state['default'] === data) - return; - - var result = this._encodeValue(data, reporter, parent); - if (result === undefined) - return; - - if (this._skipDefault(result, reporter, parent)) - return; - - return result; -}; - -Node.prototype._encodeValue = function encode(data, reporter, parent) { - var state = this._baseState; - - // Decode root node - if (state.parent === null) - return state.children[0]._encode(data, reporter || new Reporter()); - - var result = null; - - // Set reporter to share it with a child class - this.reporter = reporter; - - // Check if data is there - if (state.optional && data === undefined) { - if (state['default'] !== null) - data = state['default'] - else - return; - } - - // Encode children first - var content = null; - var primitive = false; - if (state.any) { - // Anything that was given is translated to buffer - result = this._createEncoderBuffer(data); - } else if (state.choice) { - result = this._encodeChoice(data, reporter); - } else if (state.contains) { - content = this._getUse(state.contains, parent)._encode(data, reporter); - primitive = true; - } else if (state.children) { - content = state.children.map(function(child) { - if (child._baseState.tag === 'null_') - return child._encode(null, reporter, data); - - if (child._baseState.key === null) - return reporter.error('Child should have a key'); - var prevKey = reporter.enterKey(child._baseState.key); - - if (typeof data !== 'object') - return reporter.error('Child expected, but input is not object'); - - var res = child._encode(data[child._baseState.key], reporter, data); - reporter.leaveKey(prevKey); - - return res; - }, this).filter(function(child) { - return child; - }); - content = this._createEncoderBuffer(content); - } else { - if (state.tag === 'seqof' || state.tag === 'setof') { - // TODO(indutny): this should be thrown on DSL level - if (!(state.args && state.args.length === 1)) - return reporter.error('Too many args for : ' + state.tag); - - if (!Array.isArray(data)) - return reporter.error('seqof/setof, but data is not Array'); - - var child = this.clone(); - child._baseState.implicit = null; - content = this._createEncoderBuffer(data.map(function(item) { - var state = this._baseState; - - return this._getUse(state.args[0], data)._encode(item, reporter); - }, child)); - } else if (state.use !== null) { - result = this._getUse(state.use, parent)._encode(data, reporter); - } else { - content = this._encodePrimitive(state.tag, data); - primitive = true; - } - } - - // Encode data itself - var result; - if (!state.any && state.choice === null) { - var tag = state.implicit !== null ? state.implicit : state.tag; - var cls = state.implicit === null ? 'universal' : 'context'; - - if (tag === null) { - if (state.use === null) - reporter.error('Tag could be ommited only for .use()'); - } else { - if (state.use === null) - result = this._encodeComposite(tag, primitive, cls, content); - } - } - - // Wrap in explicit - if (state.explicit !== null) - result = this._encodeComposite(state.explicit, false, 'context', result); - - return result; -}; - -Node.prototype._encodeChoice = function encodeChoice(data, reporter) { - var state = this._baseState; - - var node = state.choice[data.type]; - if (!node) { - assert( - false, - data.type + ' not found in ' + - JSON.stringify(Object.keys(state.choice))); - } - return node._encode(data.value, reporter); -}; - -Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { - var state = this._baseState; - - if (/str$/.test(tag)) - return this._encodeStr(data, tag); - else if (tag === 'objid' && state.args) - return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); - else if (tag === 'objid') - return this._encodeObjid(data, null, null); - else if (tag === 'gentime' || tag === 'utctime') - return this._encodeTime(data, tag); - else if (tag === 'null_') - return this._encodeNull(); - else if (tag === 'int' || tag === 'enum') - return this._encodeInt(data, state.args && state.reverseArgs[0]); - else if (tag === 'bool') - return this._encodeBool(data); - else if (tag === 'objDesc') - return this._encodeStr(data, tag); - else - throw new Error('Unsupported tag: ' + tag); -}; - -Node.prototype._isNumstr = function isNumstr(str) { - return /^[0-9 ]*$/.test(str); -}; - -Node.prototype._isPrintstr = function isPrintstr(str) { - return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); -}; - -},{"../base":5,"minimalistic-assert":509}],7:[function(require,module,exports){ -var inherits = require('inherits'); - -function Reporter(options) { - this._reporterState = { - obj: null, - path: [], - options: options || {}, - errors: [] - }; -} -exports.Reporter = Reporter; - -Reporter.prototype.isError = function isError(obj) { - return obj instanceof ReporterError; -}; - -Reporter.prototype.save = function save() { - var state = this._reporterState; - - return { obj: state.obj, pathLen: state.path.length }; -}; - -Reporter.prototype.restore = function restore(data) { - var state = this._reporterState; - - state.obj = data.obj; - state.path = state.path.slice(0, data.pathLen); -}; - -Reporter.prototype.enterKey = function enterKey(key) { - return this._reporterState.path.push(key); -}; - -Reporter.prototype.exitKey = function exitKey(index) { - var state = this._reporterState; - - state.path = state.path.slice(0, index - 1); -}; - -Reporter.prototype.leaveKey = function leaveKey(index, key, value) { - var state = this._reporterState; - - this.exitKey(index); - if (state.obj !== null) - state.obj[key] = value; -}; - -Reporter.prototype.path = function path() { - return this._reporterState.path.join('/'); -}; - -Reporter.prototype.enterObject = function enterObject() { - var state = this._reporterState; - - var prev = state.obj; - state.obj = {}; - return prev; -}; - -Reporter.prototype.leaveObject = function leaveObject(prev) { - var state = this._reporterState; - - var now = state.obj; - state.obj = prev; - return now; -}; - -Reporter.prototype.error = function error(msg) { - var err; - var state = this._reporterState; - - var inherited = msg instanceof ReporterError; - if (inherited) { - err = msg; - } else { - err = new ReporterError(state.path.map(function(elem) { - return '[' + JSON.stringify(elem) + ']'; - }).join(''), msg.message || msg, msg.stack); - } - - if (!state.options.partial) - throw err; - - if (!inherited) - state.errors.push(err); - - return err; -}; - -Reporter.prototype.wrapResult = function wrapResult(result) { - var state = this._reporterState; - if (!state.options.partial) - return result; - - return { - result: this.isError(result) ? null : result, - errors: state.errors - }; -}; - -function ReporterError(path, msg) { - this.path = path; - this.rethrow(msg); -}; -inherits(ReporterError, Error); - -ReporterError.prototype.rethrow = function rethrow(msg) { - this.message = msg + ' at: ' + (this.path || '(shallow)'); - if (Error.captureStackTrace) - Error.captureStackTrace(this, ReporterError); - - if (!this.stack) { - try { - // IE only adds stack when thrown - throw new Error(this.message); - } catch (e) { - this.stack = e.stack; - } - } - return this; -}; - -},{"inherits":216}],8:[function(require,module,exports){ -var constants = require('../constants'); - -exports.tagClass = { - 0: 'universal', - 1: 'application', - 2: 'context', - 3: 'private' -}; -exports.tagClassByName = constants._reverse(exports.tagClass); - -exports.tag = { - 0x00: 'end', - 0x01: 'bool', - 0x02: 'int', - 0x03: 'bitstr', - 0x04: 'octstr', - 0x05: 'null_', - 0x06: 'objid', - 0x07: 'objDesc', - 0x08: 'external', - 0x09: 'real', - 0x0a: 'enum', - 0x0b: 'embed', - 0x0c: 'utf8str', - 0x0d: 'relativeOid', - 0x10: 'seq', - 0x11: 'set', - 0x12: 'numstr', - 0x13: 'printstr', - 0x14: 't61str', - 0x15: 'videostr', - 0x16: 'ia5str', - 0x17: 'utctime', - 0x18: 'gentime', - 0x19: 'graphstr', - 0x1a: 'iso646str', - 0x1b: 'genstr', - 0x1c: 'unistr', - 0x1d: 'charstr', - 0x1e: 'bmpstr' -}; -exports.tagByName = constants._reverse(exports.tag); - -},{"../constants":9}],9:[function(require,module,exports){ -var constants = exports; - -// Helper -constants._reverse = function reverse(map) { - var res = {}; - - Object.keys(map).forEach(function(key) { - // Convert key to integer if it is stringified - if ((key | 0) == key) - key = key | 0; - - var value = map[key]; - res[value] = key; - }); - - return res; -}; - -constants.der = require('./der'); - -},{"./der":8}],10:[function(require,module,exports){ -var inherits = require('inherits'); - -var asn1 = require('../../asn1'); -var base = asn1.base; -var bignum = asn1.bignum; - -// Import DER constants -var der = asn1.constants.der; - -function DERDecoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -}; -module.exports = DERDecoder; - -DERDecoder.prototype.decode = function decode(data, options) { - if (!(data instanceof base.DecoderBuffer)) - data = new base.DecoderBuffer(data, options); - - return this.tree._decode(data, options); -}; - -// Tree methods - -function DERNode(parent) { - base.Node.call(this, 'der', parent); -} -inherits(DERNode, base.Node); - -DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { - if (buffer.isEmpty()) - return false; - - var state = buffer.save(); - var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - buffer.restore(state); - - return decodedTag.tag === tag || decodedTag.tagStr === tag || - (decodedTag.tagStr + 'of') === tag || any; -}; - -DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { - var decodedTag = derDecodeTag(buffer, - 'Failed to decode tag of "' + tag + '"'); - if (buffer.isError(decodedTag)) - return decodedTag; - - var len = derDecodeLen(buffer, - decodedTag.primitive, - 'Failed to get length of "' + tag + '"'); - - // Failure - if (buffer.isError(len)) - return len; - - if (!any && - decodedTag.tag !== tag && - decodedTag.tagStr !== tag && - decodedTag.tagStr + 'of' !== tag) { - return buffer.error('Failed to match tag: "' + tag + '"'); - } - - if (decodedTag.primitive || len !== null) - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); - - // Indefinite length... find END tag - var state = buffer.save(); - var res = this._skipUntilEnd( - buffer, - 'Failed to skip indefinite length body: "' + this.tag + '"'); - if (buffer.isError(res)) - return res; - - len = buffer.offset - state.offset; - buffer.restore(state); - return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); -}; - -DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { - while (true) { - var tag = derDecodeTag(buffer, fail); - if (buffer.isError(tag)) - return tag; - var len = derDecodeLen(buffer, tag.primitive, fail); - if (buffer.isError(len)) - return len; - - var res; - if (tag.primitive || len !== null) - res = buffer.skip(len) - else - res = this._skipUntilEnd(buffer, fail); - - // Failure - if (buffer.isError(res)) - return res; - - if (tag.tagStr === 'end') - break; - } -}; - -DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, - options) { - var result = []; - while (!buffer.isEmpty()) { - var possibleEnd = this._peekTag(buffer, 'end'); - if (buffer.isError(possibleEnd)) - return possibleEnd; - - var res = decoder.decode(buffer, 'der', options); - if (buffer.isError(res) && possibleEnd) - break; - result.push(res); - } - return result; -}; - -DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { - if (tag === 'bitstr') { - var unused = buffer.readUInt8(); - if (buffer.isError(unused)) - return unused; - return { unused: unused, data: buffer.raw() }; - } else if (tag === 'bmpstr') { - var raw = buffer.raw(); - if (raw.length % 2 === 1) - return buffer.error('Decoding of string type: bmpstr length mismatch'); - - var str = ''; - for (var i = 0; i < raw.length / 2; i++) { - str += String.fromCharCode(raw.readUInt16BE(i * 2)); - } - return str; - } else if (tag === 'numstr') { - var numstr = buffer.raw().toString('ascii'); - if (!this._isNumstr(numstr)) { - return buffer.error('Decoding of string type: ' + - 'numstr unsupported characters'); - } - return numstr; - } else if (tag === 'octstr') { - return buffer.raw(); - } else if (tag === 'objDesc') { - return buffer.raw(); - } else if (tag === 'printstr') { - var printstr = buffer.raw().toString('ascii'); - if (!this._isPrintstr(printstr)) { - return buffer.error('Decoding of string type: ' + - 'printstr unsupported characters'); - } - return printstr; - } else if (/str$/.test(tag)) { - return buffer.raw().toString(); - } else { - return buffer.error('Decoding of string type: ' + tag + ' unsupported'); - } -}; - -DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { - var result; - var identifiers = []; - var ident = 0; - while (!buffer.isEmpty()) { - var subident = buffer.readUInt8(); - ident <<= 7; - ident |= subident & 0x7f; - if ((subident & 0x80) === 0) { - identifiers.push(ident); - ident = 0; - } - } - if (subident & 0x80) - identifiers.push(ident); - - var first = (identifiers[0] / 40) | 0; - var second = identifiers[0] % 40; - - if (relative) - result = identifiers; - else - result = [first, second].concat(identifiers.slice(1)); - - if (values) { - var tmp = values[result.join(' ')]; - if (tmp === undefined) - tmp = values[result.join('.')]; - if (tmp !== undefined) - result = tmp; - } - - return result; -}; - -DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { - var str = buffer.raw().toString(); - if (tag === 'gentime') { - var year = str.slice(0, 4) | 0; - var mon = str.slice(4, 6) | 0; - var day = str.slice(6, 8) | 0; - var hour = str.slice(8, 10) | 0; - var min = str.slice(10, 12) | 0; - var sec = str.slice(12, 14) | 0; - } else if (tag === 'utctime') { - var year = str.slice(0, 2) | 0; - var mon = str.slice(2, 4) | 0; - var day = str.slice(4, 6) | 0; - var hour = str.slice(6, 8) | 0; - var min = str.slice(8, 10) | 0; - var sec = str.slice(10, 12) | 0; - if (year < 70) - year = 2000 + year; - else - year = 1900 + year; - } else { - return buffer.error('Decoding ' + tag + ' time is not supported yet'); - } - - return Date.UTC(year, mon - 1, day, hour, min, sec, 0); -}; - -DERNode.prototype._decodeNull = function decodeNull(buffer) { - return null; -}; - -DERNode.prototype._decodeBool = function decodeBool(buffer) { - var res = buffer.readUInt8(); - if (buffer.isError(res)) - return res; - else - return res !== 0; -}; - -DERNode.prototype._decodeInt = function decodeInt(buffer, values) { - // Bigint, return as it is (assume big endian) - var raw = buffer.raw(); - var res = new bignum(raw); - - if (values) - res = values[res.toString(10)] || res; - - return res; -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getDecoder('der').tree; -}; - -// Utility methods - -function derDecodeTag(buf, fail) { - var tag = buf.readUInt8(fail); - if (buf.isError(tag)) - return tag; - - var cls = der.tagClass[tag >> 6]; - var primitive = (tag & 0x20) === 0; - - // Multi-octet tag - load - if ((tag & 0x1f) === 0x1f) { - var oct = tag; - tag = 0; - while ((oct & 0x80) === 0x80) { - oct = buf.readUInt8(fail); - if (buf.isError(oct)) - return oct; - - tag <<= 7; - tag |= oct & 0x7f; - } - } else { - tag &= 0x1f; - } - var tagStr = der.tag[tag]; - - return { - cls: cls, - primitive: primitive, - tag: tag, - tagStr: tagStr - }; -} - -function derDecodeLen(buf, primitive, fail) { - var len = buf.readUInt8(fail); - if (buf.isError(len)) - return len; - - // Indefinite form - if (!primitive && len === 0x80) - return null; - - // Definite form - if ((len & 0x80) === 0) { - // Short form - return len; - } - - // Long form - var num = len & 0x7f; - if (num > 4) - return buf.error('length octect is too long'); - - len = 0; - for (var i = 0; i < num; i++) { - len <<= 8; - var j = buf.readUInt8(fail); - if (buf.isError(j)) - return j; - len |= j; - } - - return len; -} - -},{"../../asn1":2,"inherits":216}],11:[function(require,module,exports){ -var decoders = exports; - -decoders.der = require('./der'); -decoders.pem = require('./pem'); - -},{"./der":10,"./pem":12}],12:[function(require,module,exports){ -var inherits = require('inherits'); -var Buffer = require('buffer').Buffer; - -var DERDecoder = require('./der'); - -function PEMDecoder(entity) { - DERDecoder.call(this, entity); - this.enc = 'pem'; -}; -inherits(PEMDecoder, DERDecoder); -module.exports = PEMDecoder; - -PEMDecoder.prototype.decode = function decode(data, options) { - var lines = data.toString().split(/[\r\n]+/g); - - var label = options.label.toUpperCase(); - - var re = /^-----(BEGIN|END) ([^-]+)-----$/; - var start = -1; - var end = -1; - for (var i = 0; i < lines.length; i++) { - var match = lines[i].match(re); - if (match === null) - continue; - - if (match[2] !== label) - continue; - - if (start === -1) { - if (match[1] !== 'BEGIN') - break; - start = i; - } else { - if (match[1] !== 'END') - break; - end = i; - break; - } - } - if (start === -1 || end === -1) - throw new Error('PEM section not found for: ' + label); - - var base64 = lines.slice(start + 1, end).join(''); - // Remove excessive symbols - base64.replace(/[^a-z0-9\+\/=]+/gi, ''); - - var input = new Buffer(base64, 'base64'); - return DERDecoder.prototype.decode.call(this, input, options); -}; - -},{"./der":10,"buffer":987,"inherits":216}],13:[function(require,module,exports){ -var inherits = require('inherits'); -var Buffer = require('buffer').Buffer; - -var asn1 = require('../../asn1'); -var base = asn1.base; - -// Import DER constants -var der = asn1.constants.der; - -function DEREncoder(entity) { - this.enc = 'der'; - this.name = entity.name; - this.entity = entity; - - // Construct base tree - this.tree = new DERNode(); - this.tree._init(entity.body); -}; -module.exports = DEREncoder; - -DEREncoder.prototype.encode = function encode(data, reporter) { - return this.tree._encode(data, reporter).join(); -}; - -// Tree methods - -function DERNode(parent) { - base.Node.call(this, 'der', parent); -} -inherits(DERNode, base.Node); - -DERNode.prototype._encodeComposite = function encodeComposite(tag, - primitive, - cls, - content) { - var encodedTag = encodeTag(tag, primitive, cls, this.reporter); - - // Short form - if (content.length < 0x80) { - var header = new Buffer(2); - header[0] = encodedTag; - header[1] = content.length; - return this._createEncoderBuffer([ header, content ]); - } - - // Long form - // Count octets required to store length - var lenOctets = 1; - for (var i = content.length; i >= 0x100; i >>= 8) - lenOctets++; - - var header = new Buffer(1 + 1 + lenOctets); - header[0] = encodedTag; - header[1] = 0x80 | lenOctets; - - for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) - header[i] = j & 0xff; - - return this._createEncoderBuffer([ header, content ]); -}; - -DERNode.prototype._encodeStr = function encodeStr(str, tag) { - if (tag === 'bitstr') { - return this._createEncoderBuffer([ str.unused | 0, str.data ]); - } else if (tag === 'bmpstr') { - var buf = new Buffer(str.length * 2); - for (var i = 0; i < str.length; i++) { - buf.writeUInt16BE(str.charCodeAt(i), i * 2); - } - return this._createEncoderBuffer(buf); - } else if (tag === 'numstr') { - if (!this._isNumstr(str)) { - return this.reporter.error('Encoding of string type: numstr supports ' + - 'only digits and space'); - } - return this._createEncoderBuffer(str); - } else if (tag === 'printstr') { - if (!this._isPrintstr(str)) { - return this.reporter.error('Encoding of string type: printstr supports ' + - 'only latin upper and lower case letters, ' + - 'digits, space, apostrophe, left and rigth ' + - 'parenthesis, plus sign, comma, hyphen, ' + - 'dot, slash, colon, equal sign, ' + - 'question mark'); - } - return this._createEncoderBuffer(str); - } else if (/str$/.test(tag)) { - return this._createEncoderBuffer(str); - } else if (tag === 'objDesc') { - return this._createEncoderBuffer(str); - } else { - return this.reporter.error('Encoding of string type: ' + tag + - ' unsupported'); - } -}; - -DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { - if (typeof id === 'string') { - if (!values) - return this.reporter.error('string objid given, but no values map found'); - if (!values.hasOwnProperty(id)) - return this.reporter.error('objid not found in values map'); - id = values[id].split(/[\s\.]+/g); - for (var i = 0; i < id.length; i++) - id[i] |= 0; - } else if (Array.isArray(id)) { - id = id.slice(); - for (var i = 0; i < id.length; i++) - id[i] |= 0; - } - - if (!Array.isArray(id)) { - return this.reporter.error('objid() should be either array or string, ' + - 'got: ' + JSON.stringify(id)); - } - - if (!relative) { - if (id[1] >= 40) - return this.reporter.error('Second objid identifier OOB'); - id.splice(0, 2, id[0] * 40 + id[1]); - } - - // Count number of octets - var size = 0; - for (var i = 0; i < id.length; i++) { - var ident = id[i]; - for (size++; ident >= 0x80; ident >>= 7) - size++; - } - - var objid = new Buffer(size); - var offset = objid.length - 1; - for (var i = id.length - 1; i >= 0; i--) { - var ident = id[i]; - objid[offset--] = ident & 0x7f; - while ((ident >>= 7) > 0) - objid[offset--] = 0x80 | (ident & 0x7f); - } - - return this._createEncoderBuffer(objid); -}; - -function two(num) { - if (num < 10) - return '0' + num; - else - return num; -} - -DERNode.prototype._encodeTime = function encodeTime(time, tag) { - var str; - var date = new Date(time); - - if (tag === 'gentime') { - str = [ - two(date.getFullYear()), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else if (tag === 'utctime') { - str = [ - two(date.getFullYear() % 100), - two(date.getUTCMonth() + 1), - two(date.getUTCDate()), - two(date.getUTCHours()), - two(date.getUTCMinutes()), - two(date.getUTCSeconds()), - 'Z' - ].join(''); - } else { - this.reporter.error('Encoding ' + tag + ' time is not supported yet'); - } - - return this._encodeStr(str, 'octstr'); -}; - -DERNode.prototype._encodeNull = function encodeNull() { - return this._createEncoderBuffer(''); -}; - -DERNode.prototype._encodeInt = function encodeInt(num, values) { - if (typeof num === 'string') { - if (!values) - return this.reporter.error('String int or enum given, but no values map'); - if (!values.hasOwnProperty(num)) { - return this.reporter.error('Values map doesn\'t contain: ' + - JSON.stringify(num)); - } - num = values[num]; - } - - // Bignum, assume big endian - if (typeof num !== 'number' && !Buffer.isBuffer(num)) { - var numArray = num.toArray(); - if (!num.sign && numArray[0] & 0x80) { - numArray.unshift(0); - } - num = new Buffer(numArray); - } - - if (Buffer.isBuffer(num)) { - var size = num.length; - if (num.length === 0) - size++; - - var out = new Buffer(size); - num.copy(out); - if (num.length === 0) - out[0] = 0 - return this._createEncoderBuffer(out); - } - - if (num < 0x80) - return this._createEncoderBuffer(num); - - if (num < 0x100) - return this._createEncoderBuffer([0, num]); - - var size = 1; - for (var i = num; i >= 0x100; i >>= 8) - size++; - - var out = new Array(size); - for (var i = out.length - 1; i >= 0; i--) { - out[i] = num & 0xff; - num >>= 8; - } - if(out[0] & 0x80) { - out.unshift(0); - } - - return this._createEncoderBuffer(new Buffer(out)); -}; - -DERNode.prototype._encodeBool = function encodeBool(value) { - return this._createEncoderBuffer(value ? 0xff : 0); -}; - -DERNode.prototype._use = function use(entity, obj) { - if (typeof entity === 'function') - entity = entity(obj); - return entity._getEncoder('der').tree; -}; - -DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { - var state = this._baseState; - var i; - if (state['default'] === null) - return false; - - var data = dataBuffer.join(); - if (state.defaultBuffer === undefined) - state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); - - if (data.length !== state.defaultBuffer.length) - return false; - - for (i=0; i < data.length; i++) - if (data[i] !== state.defaultBuffer[i]) - return false; - - return true; -}; - -// Utility methods - -function encodeTag(tag, primitive, cls, reporter) { - var res; - - if (tag === 'seqof') - tag = 'seq'; - else if (tag === 'setof') - tag = 'set'; - - if (der.tagByName.hasOwnProperty(tag)) - res = der.tagByName[tag]; - else if (typeof tag === 'number' && (tag | 0) === tag) - res = tag; - else - return reporter.error('Unknown tag: ' + tag); - - if (res >= 0x1f) - return reporter.error('Multi-octet tag encoding unsupported'); - - if (!primitive) - res |= 0x20; - - res |= (der.tagClassByName[cls || 'universal'] << 6); - - return res; -} - -},{"../../asn1":2,"buffer":987,"inherits":216}],14:[function(require,module,exports){ -var encoders = exports; - -encoders.der = require('./der'); -encoders.pem = require('./pem'); - -},{"./der":13,"./pem":15}],15:[function(require,module,exports){ -var inherits = require('inherits'); - -var DEREncoder = require('./der'); - -function PEMEncoder(entity) { - DEREncoder.call(this, entity); - this.enc = 'pem'; -}; -inherits(PEMEncoder, DEREncoder); -module.exports = PEMEncoder; - -PEMEncoder.prototype.encode = function encode(data, options) { - var buf = DEREncoder.prototype.encode.call(this, data); - - var p = buf.toString('base64'); - var out = [ '-----BEGIN ' + options.label + '-----' ]; - for (var i = 0; i < p.length; i += 64) - out.push(p.slice(i, i + 64)); - out.push('-----END ' + options.label + '-----'); - return out.join('\n'); -}; - -},{"./der":13,"inherits":216}],16:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = asyncify; - -var _isObject = require('lodash/isObject'); - -var _isObject2 = _interopRequireDefault(_isObject); - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return (0, _initialParams2.default)(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if ((0, _isObject2.default)(result) && typeof result.then === 'function') { - result.then(function (value) { - invokeCallback(callback, null, value); - }, function (err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - (0, _setImmediate2.default)(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} -module.exports = exports['default']; -},{"./internal/initialParams":35,"./internal/setImmediate":44,"lodash/isObject":484}],17:[function(require,module,exports){ -(function (process,global){ -(function (global, factory) { - typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : - typeof define === 'function' && define.amd ? define(['exports'], factory) : - (factory((global.async = global.async || {}))); -}(this, (function (exports) { 'use strict'; - -function slice(arrayLike, start) { - start = start|0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for(var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} - -var initialParams = function (fn) { - return function (/*...args, callback*/) { - var args = slice(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; - -/** - * Checks if `value` is the - * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) - * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(_.noop); - * // => true - * - * _.isObject(null); - * // => false - */ -function isObject(value) { - var type = typeof value; - return value != null && (type == 'object' || type == 'function'); -} - -var hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - -function fallback(fn) { - setTimeout(fn, 0); -} - -function wrap(defer) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} - -var _defer; - -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} - -var setImmediate$1 = wrap(_defer); - -/** - * Take a sync function and make it async, passing its return value to a - * callback. This is useful for plugging sync functions into a waterfall, - * series, or other async functions. Any arguments passed to the generated - * function will be passed to the wrapped function (except for the final - * callback argument). Errors thrown will be passed to the callback. - * - * If the function passed to `asyncify` returns a Promise, that promises's - * resolved/rejected state will be used to call the callback, rather than simply - * the synchronous return value. - * - * This also means you can asyncify ES2017 `async` functions. - * - * @name asyncify - * @static - * @memberOf module:Utils - * @method - * @alias wrapSync - * @category Util - * @param {Function} func - The synchronous function, or Promise-returning - * function to convert to an {@link AsyncFunction}. - * @returns {AsyncFunction} An asynchronous wrapper of the `func`. To be - * invoked with `(args..., callback)`. - * @example - * - * // passing a regular synchronous function - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(JSON.parse), - * function (data, next) { - * // data is the result of parsing the text. - * // If there was a parsing error, it would have been caught. - * } - * ], callback); - * - * // passing a function returning a promise - * async.waterfall([ - * async.apply(fs.readFile, filename, "utf8"), - * async.asyncify(function (contents) { - * return db.model.create(contents); - * }), - * function (model, next) { - * // `model` is the instantiated model object. - * // If there was an error, this function would be skipped. - * } - * ], callback); - * - * // es2017 example, though `asyncify` is not needed if your JS environment - * // supports async functions out of the box - * var q = async.queue(async.asyncify(async function(file) { - * var intermediateStep = await processFile(file); - * return await somePromise(intermediateStep) - * })); - * - * q.push(files); - */ -function asyncify(func) { - return initialParams(function (args, callback) { - var result; - try { - result = func.apply(this, args); - } catch (e) { - return callback(e); - } - // if result is Promise object - if (isObject(result) && typeof result.then === 'function') { - result.then(function(value) { - invokeCallback(callback, null, value); - }, function(err) { - invokeCallback(callback, err.message ? err : new Error(err)); - }); - } else { - callback(null, result); - } - }); -} - -function invokeCallback(callback, error, value) { - try { - callback(error, value); - } catch (e) { - setImmediate$1(rethrow, e); - } -} - -function rethrow(error) { - throw error; -} - -var supportsSymbol = typeof Symbol === 'function'; - -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} - -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? asyncify(asyncFn) : asyncFn; -} - -function applyEach$1(eachfn) { - return function(fns/*, ...args*/) { - var args = slice(arguments, 1); - var go = initialParams(function(args, callback) { - var that = this; - return eachfn(fns, function (fn, cb) { - wrapAsync(fn).apply(that, args.concat(cb)); - }, callback); - }); - if (args.length) { - return go.apply(this, args); - } - else { - return go; - } - }; -} - -/** Detect free variable `global` from Node.js. */ -var freeGlobal = typeof global == 'object' && global && global.Object === Object && global; - -/** Detect free variable `self`. */ -var freeSelf = typeof self == 'object' && self && self.Object === Object && self; - -/** Used as a reference to the global object. */ -var root = freeGlobal || freeSelf || Function('return this')(); - -/** Built-in value references. */ -var Symbol$1 = root.Symbol; - -/** Used for built-in method references. */ -var objectProto = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty = objectProto.hasOwnProperty; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString = objectProto.toString; - -/** Built-in value references. */ -var symToStringTag$1 = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the raw `toStringTag`. - */ -function getRawTag(value) { - var isOwn = hasOwnProperty.call(value, symToStringTag$1), - tag = value[symToStringTag$1]; - - try { - value[symToStringTag$1] = undefined; - var unmasked = true; - } catch (e) {} - - var result = nativeObjectToString.call(value); - if (unmasked) { - if (isOwn) { - value[symToStringTag$1] = tag; - } else { - delete value[symToStringTag$1]; - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$1 = Object.prototype; - -/** - * Used to resolve the - * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) - * of values. - */ -var nativeObjectToString$1 = objectProto$1.toString; - -/** - * Converts `value` to a string using `Object.prototype.toString`. - * - * @private - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - */ -function objectToString(value) { - return nativeObjectToString$1.call(value); -} - -/** `Object#toString` result references. */ -var nullTag = '[object Null]'; -var undefinedTag = '[object Undefined]'; - -/** Built-in value references. */ -var symToStringTag = Symbol$1 ? Symbol$1.toStringTag : undefined; - -/** - * The base implementation of `getTag` without fallbacks for buggy environments. - * - * @private - * @param {*} value The value to query. - * @returns {string} Returns the `toStringTag`. - */ -function baseGetTag(value) { - if (value == null) { - return value === undefined ? undefinedTag : nullTag; - } - value = Object(value); - return (symToStringTag && symToStringTag in value) - ? getRawTag(value) - : objectToString(value); -} - -/** `Object#toString` result references. */ -var asyncTag = '[object AsyncFunction]'; -var funcTag = '[object Function]'; -var genTag = '[object GeneratorFunction]'; -var proxyTag = '[object Proxy]'; - -/** - * Checks if `value` is classified as a `Function` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - * - * _.isFunction(/abc/); - * // => false - */ -function isFunction(value) { - if (!isObject(value)) { - return false; - } - // The use of `Object#toString` avoids issues with the `typeof` operator - // in Safari 9 which returns 'object' for typed arrays and other constructors. - var tag = baseGetTag(value); - return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag; -} - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER = 9007199254740991; - -/** - * Checks if `value` is a valid array-like length. - * - * **Note:** This method is loosely based on - * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. - * @example - * - * _.isLength(3); - * // => true - * - * _.isLength(Number.MIN_VALUE); - * // => false - * - * _.isLength(Infinity); - * // => false - * - * _.isLength('3'); - * // => false - */ -function isLength(value) { - return typeof value == 'number' && - value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER; -} - -/** - * Checks if `value` is array-like. A value is considered array-like if it's - * not a function and has a `value.length` that's an integer greater than or - * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is array-like, else `false`. - * @example - * - * _.isArrayLike([1, 2, 3]); - * // => true - * - * _.isArrayLike(document.body.children); - * // => true - * - * _.isArrayLike('abc'); - * // => true - * - * _.isArrayLike(_.noop); - * // => false - */ -function isArrayLike(value) { - return value != null && isLength(value.length) && !isFunction(value); -} - -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -var breakLoop = {}; - -/** - * This method returns `undefined`. - * - * @static - * @memberOf _ - * @since 2.3.0 - * @category Util - * @example - * - * _.times(2, _.noop); - * // => [undefined, undefined] - */ -function noop() { - // No operation performed. -} - -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} - -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -var getIterator = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; - -/** - * The base implementation of `_.times` without support for iteratee shorthands - * or max array length checks. - * - * @private - * @param {number} n The number of times to invoke `iteratee`. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the array of results. - */ -function baseTimes(n, iteratee) { - var index = -1, - result = Array(n); - - while (++index < n) { - result[index] = iteratee(index); - } - return result; -} - -/** - * Checks if `value` is object-like. A value is object-like if it's not `null` - * and has a `typeof` result of "object". - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is object-like, else `false`. - * @example - * - * _.isObjectLike({}); - * // => true - * - * _.isObjectLike([1, 2, 3]); - * // => true - * - * _.isObjectLike(_.noop); - * // => false - * - * _.isObjectLike(null); - * // => false - */ -function isObjectLike(value) { - return value != null && typeof value == 'object'; -} - -/** `Object#toString` result references. */ -var argsTag = '[object Arguments]'; - -/** - * The base implementation of `_.isArguments`. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - */ -function baseIsArguments(value) { - return isObjectLike(value) && baseGetTag(value) == argsTag; -} - -/** Used for built-in method references. */ -var objectProto$3 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$2 = objectProto$3.hasOwnProperty; - -/** Built-in value references. */ -var propertyIsEnumerable = objectProto$3.propertyIsEnumerable; - -/** - * Checks if `value` is likely an `arguments` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an `arguments` object, - * else `false`. - * @example - * - * _.isArguments(function() { return arguments; }()); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ -var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { - return isObjectLike(value) && hasOwnProperty$2.call(value, 'callee') && - !propertyIsEnumerable.call(value, 'callee'); -}; - -/** - * Checks if `value` is classified as an `Array` object. - * - * @static - * @memberOf _ - * @since 0.1.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is an array, else `false`. - * @example - * - * _.isArray([1, 2, 3]); - * // => true - * - * _.isArray(document.body.children); - * // => false - * - * _.isArray('abc'); - * // => false - * - * _.isArray(_.noop); - * // => false - */ -var isArray = Array.isArray; - -/** - * This method returns `false`. - * - * @static - * @memberOf _ - * @since 4.13.0 - * @category Util - * @returns {boolean} Returns `false`. - * @example - * - * _.times(2, _.stubFalse); - * // => [false, false] - */ -function stubFalse() { - return false; -} - -/** Detect free variable `exports`. */ -var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports = freeModule && freeModule.exports === freeExports; - -/** Built-in value references. */ -var Buffer = moduleExports ? root.Buffer : undefined; - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined; - -/** - * Checks if `value` is a buffer. - * - * @static - * @memberOf _ - * @since 4.3.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. - * @example - * - * _.isBuffer(new Buffer(2)); - * // => true - * - * _.isBuffer(new Uint8Array(2)); - * // => false - */ -var isBuffer = nativeIsBuffer || stubFalse; - -/** Used as references for various `Number` constants. */ -var MAX_SAFE_INTEGER$1 = 9007199254740991; - -/** Used to detect unsigned integer values. */ -var reIsUint = /^(?:0|[1-9]\d*)$/; - -/** - * Checks if `value` is a valid array-like index. - * - * @private - * @param {*} value The value to check. - * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. - * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. - */ -function isIndex(value, length) { - length = length == null ? MAX_SAFE_INTEGER$1 : length; - return !!length && - (typeof value == 'number' || reIsUint.test(value)) && - (value > -1 && value % 1 == 0 && value < length); -} - -/** `Object#toString` result references. */ -var argsTag$1 = '[object Arguments]'; -var arrayTag = '[object Array]'; -var boolTag = '[object Boolean]'; -var dateTag = '[object Date]'; -var errorTag = '[object Error]'; -var funcTag$1 = '[object Function]'; -var mapTag = '[object Map]'; -var numberTag = '[object Number]'; -var objectTag = '[object Object]'; -var regexpTag = '[object RegExp]'; -var setTag = '[object Set]'; -var stringTag = '[object String]'; -var weakMapTag = '[object WeakMap]'; - -var arrayBufferTag = '[object ArrayBuffer]'; -var dataViewTag = '[object DataView]'; -var float32Tag = '[object Float32Array]'; -var float64Tag = '[object Float64Array]'; -var int8Tag = '[object Int8Array]'; -var int16Tag = '[object Int16Array]'; -var int32Tag = '[object Int32Array]'; -var uint8Tag = '[object Uint8Array]'; -var uint8ClampedTag = '[object Uint8ClampedArray]'; -var uint16Tag = '[object Uint16Array]'; -var uint32Tag = '[object Uint32Array]'; - -/** Used to identify `toStringTag` values of typed arrays. */ -var typedArrayTags = {}; -typedArrayTags[float32Tag] = typedArrayTags[float64Tag] = -typedArrayTags[int8Tag] = typedArrayTags[int16Tag] = -typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] = -typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] = -typedArrayTags[uint32Tag] = true; -typedArrayTags[argsTag$1] = typedArrayTags[arrayTag] = -typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] = -typedArrayTags[dataViewTag] = typedArrayTags[dateTag] = -typedArrayTags[errorTag] = typedArrayTags[funcTag$1] = -typedArrayTags[mapTag] = typedArrayTags[numberTag] = -typedArrayTags[objectTag] = typedArrayTags[regexpTag] = -typedArrayTags[setTag] = typedArrayTags[stringTag] = -typedArrayTags[weakMapTag] = false; - -/** - * The base implementation of `_.isTypedArray` without Node.js optimizations. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - */ -function baseIsTypedArray(value) { - return isObjectLike(value) && - isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; -} - -/** - * The base implementation of `_.unary` without support for storing metadata. - * - * @private - * @param {Function} func The function to cap arguments for. - * @returns {Function} Returns the new capped function. - */ -function baseUnary(func) { - return function(value) { - return func(value); - }; -} - -/** Detect free variable `exports`. */ -var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; - -/** Detect free variable `module`. */ -var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; - -/** Detect the popular CommonJS extension `module.exports`. */ -var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; - -/** Detect free variable `process` from Node.js. */ -var freeProcess = moduleExports$1 && freeGlobal.process; - -/** Used to access faster Node.js helpers. */ -var nodeUtil = (function() { - try { - return freeProcess && freeProcess.binding('util'); - } catch (e) {} -}()); - -/* Node.js helper references. */ -var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; - -/** - * Checks if `value` is classified as a typed array. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. - * @example - * - * _.isTypedArray(new Uint8Array); - * // => true - * - * _.isTypedArray([]); - * // => false - */ -var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; - -/** Used for built-in method references. */ -var objectProto$2 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$1 = objectProto$2.hasOwnProperty; - -/** - * Creates an array of the enumerable property names of the array-like `value`. - * - * @private - * @param {*} value The value to query. - * @param {boolean} inherited Specify returning inherited property names. - * @returns {Array} Returns the array of property names. - */ -function arrayLikeKeys(value, inherited) { - var isArr = isArray(value), - isArg = !isArr && isArguments(value), - isBuff = !isArr && !isArg && isBuffer(value), - isType = !isArr && !isArg && !isBuff && isTypedArray(value), - skipIndexes = isArr || isArg || isBuff || isType, - result = skipIndexes ? baseTimes(value.length, String) : [], - length = result.length; - - for (var key in value) { - if ((inherited || hasOwnProperty$1.call(value, key)) && - !(skipIndexes && ( - // Safari 9 has enumerable `arguments.length` in strict mode. - key == 'length' || - // Node.js 0.10 has enumerable non-index properties on buffers. - (isBuff && (key == 'offset' || key == 'parent')) || - // PhantomJS 2 has enumerable non-index properties on typed arrays. - (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || - // Skip index properties. - isIndex(key, length) - ))) { - result.push(key); - } - } - return result; -} - -/** Used for built-in method references. */ -var objectProto$5 = Object.prototype; - -/** - * Checks if `value` is likely a prototype object. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. - */ -function isPrototype(value) { - var Ctor = value && value.constructor, - proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$5; - - return value === proto; -} - -/** - * Creates a unary function that invokes `func` with its argument transformed. - * - * @private - * @param {Function} func The function to wrap. - * @param {Function} transform The argument transform. - * @returns {Function} Returns the new function. - */ -function overArg(func, transform) { - return function(arg) { - return func(transform(arg)); - }; -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeKeys = overArg(Object.keys, Object); - -/** Used for built-in method references. */ -var objectProto$4 = Object.prototype; - -/** Used to check objects for own properties. */ -var hasOwnProperty$3 = objectProto$4.hasOwnProperty; - -/** - * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. - * - * @private - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - */ -function baseKeys(object) { - if (!isPrototype(object)) { - return nativeKeys(object); - } - var result = []; - for (var key in Object(object)) { - if (hasOwnProperty$3.call(object, key) && key != 'constructor') { - result.push(key); - } - } - return result; -} - -/** - * Creates an array of the own enumerable property names of `object`. - * - * **Note:** Non-object values are coerced to objects. See the - * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) - * for more details. - * - * @static - * @since 0.1.0 - * @memberOf _ - * @category Object - * @param {Object} object The object to query. - * @returns {Array} Returns the array of property names. - * @example - * - * function Foo() { - * this.a = 1; - * this.b = 2; - * } - * - * Foo.prototype.c = 3; - * - * _.keys(new Foo); - * // => ['a', 'b'] (iteration order is not guaranteed) - * - * _.keys('hi'); - * // => ['0', '1'] - */ -function keys(object) { - return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); -} - -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? {value: coll[i], key: i} : null; - } -} - -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) - return null; - i++; - return {value: item.value, key: i}; - } -} - -function createObjectIterator(obj) { - var okeys = keys(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? {value: obj[key], key: key} : null; - }; -} - -function iterator(coll) { - if (isArrayLike(coll)) { - return createArrayIterator(coll); - } - - var iterator = getIterator(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} - -function onlyOnce(fn) { - return function() { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} - -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = once(callback || noop); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = iterator(obj); - var done = false; - var running = 0; - - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } - else if (value === breakLoop || (done && running <= 0)) { - done = true; - return callback(null); - } - else { - replenish(); - } - } - - function replenish () { - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, onlyOnce(iterateeCallback)); - } - } - - replenish(); - }; -} - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, wrapAsync(iteratee), callback); -} - -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = once(callback || noop); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if ((++completed === length) || value === breakLoop) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, onlyOnce(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = doLimit(eachOfLimit, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -var eachOf = function(coll, iteratee, callback) { - var eachOfImplementation = isArrayLike(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, wrapAsync(iteratee), callback); -}; - -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(eachOf, obj, wrapAsync(iteratee), callback); - }; -} - -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || noop; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = wrapAsync(iteratee); - - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} - -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -var map = doParallel(_asyncMap); - -/** - * Applies the provided arguments to each function in the array, calling - * `callback` after all functions have completed. If you only provide the first - * argument, `fns`, then it will return a function which lets you pass in the - * arguments as if it were a single function call. If more arguments are - * provided, `callback` is required while `args` is still optional. - * - * @name applyEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s - * to all call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument, `fns`, is provided, it will - * return a function which lets you pass in the arguments as if it were a single - * function call. The signature is `(..args, callback)`. If invoked with any - * arguments, `callback` is required. - * @example - * - * async.applyEach([enableSearch, updateSchema], 'bucket', callback); - * - * // partial application example: - * async.each( - * buckets, - * async.applyEach([enableSearch, updateSchema]), - * callback - * ); - */ -var applyEach = applyEach$1(map); - -function doParallelLimit(fn) { - return function (obj, limit, iteratee, callback) { - return fn(_eachOfLimit(limit), obj, wrapAsync(iteratee), callback); - }; -} - -/** - * The same as [`map`]{@link module:Collections.map} but runs a maximum of `limit` async operations at a time. - * - * @name mapLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapLimit = doParallelLimit(_asyncMap); - -/** - * The same as [`map`]{@link module:Collections.map} but runs only a single async operation at a time. - * - * @name mapSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.map]{@link module:Collections.map} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an array of the - * transformed items from the `coll`. Invoked with (err, results). - */ -var mapSeries = doLimit(mapLimit, 1); - -/** - * The same as [`applyEach`]{@link module:ControlFlow.applyEach} but runs only a single async operation at a time. - * - * @name applyEachSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.applyEach]{@link module:ControlFlow.applyEach} - * @category Control Flow - * @param {Array|Iterable|Object} fns - A collection of {@link AsyncFunction}s to all - * call with the same arguments - * @param {...*} [args] - any number of separate arguments to pass to the - * function. - * @param {Function} [callback] - the final argument should be the callback, - * called when all functions have completed processing. - * @returns {Function} - If only the first argument is provided, it will return - * a function which lets you pass in the arguments as if it were a single - * function call. - */ -var applyEachSeries = applyEach$1(mapSeries); - -/** - * Creates a continuation function with some arguments already applied. - * - * Useful as a shorthand when combined with other control flow functions. Any - * arguments passed to the returned function are added to the arguments - * originally passed to apply. - * - * @name apply - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {Function} fn - The function you want to eventually apply all - * arguments to. Invokes with (arguments...). - * @param {...*} arguments... - Any number of arguments to automatically apply - * when the continuation is called. - * @returns {Function} the partially-applied function - * @example - * - * // using apply - * async.parallel([ - * async.apply(fs.writeFile, 'testfile1', 'test1'), - * async.apply(fs.writeFile, 'testfile2', 'test2') - * ]); - * - * - * // the same process without using apply - * async.parallel([ - * function(callback) { - * fs.writeFile('testfile1', 'test1', callback); - * }, - * function(callback) { - * fs.writeFile('testfile2', 'test2', callback); - * } - * ]); - * - * // It's possible to pass any number of additional arguments when calling the - * // continuation: - * - * node> var fn = async.apply(sys.puts, 'one'); - * node> fn('two', 'three'); - * one - * two - * three - */ -var apply = function(fn/*, ...args*/) { - var args = slice(arguments, 1); - return function(/*callArgs*/) { - var callArgs = slice(arguments); - return fn.apply(null, args.concat(callArgs)); - }; -}; - -/** - * A specialized version of `_.forEach` for arrays without support for - * iteratee shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns `array`. - */ -function arrayEach(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length; - - while (++index < length) { - if (iteratee(array[index], index, array) === false) { - break; - } - } - return array; -} - -/** - * Creates a base function for methods like `_.forIn` and `_.forOwn`. - * - * @private - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Function} Returns the new base function. - */ -function createBaseFor(fromRight) { - return function(object, iteratee, keysFunc) { - var index = -1, - iterable = Object(object), - props = keysFunc(object), - length = props.length; - - while (length--) { - var key = props[fromRight ? length : ++index]; - if (iteratee(iterable[key], key, iterable) === false) { - break; - } - } - return object; - }; -} - -/** - * The base implementation of `baseForOwn` which iterates over `object` - * properties returned by `keysFunc` and invokes `iteratee` for each property. - * Iteratee functions may exit iteration early by explicitly returning `false`. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @param {Function} keysFunc The function to get the keys of `object`. - * @returns {Object} Returns `object`. - */ -var baseFor = createBaseFor(); - -/** - * The base implementation of `_.forOwn` without support for iteratee shorthands. - * - * @private - * @param {Object} object The object to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Object} Returns `object`. - */ -function baseForOwn(object, iteratee) { - return object && baseFor(object, iteratee, keys); -} - -/** - * The base implementation of `_.findIndex` and `_.findLastIndex` without - * support for iteratee shorthands. - * - * @private - * @param {Array} array The array to inspect. - * @param {Function} predicate The function invoked per iteration. - * @param {number} fromIndex The index to search from. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseFindIndex(array, predicate, fromIndex, fromRight) { - var length = array.length, - index = fromIndex + (fromRight ? 1 : -1); - - while ((fromRight ? index-- : ++index < length)) { - if (predicate(array[index], index, array)) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.isNaN` without support for number objects. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. - */ -function baseIsNaN(value) { - return value !== value; -} - -/** - * A specialized version of `_.indexOf` which performs strict equality - * comparisons of values, i.e. `===`. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function strictIndexOf(array, value, fromIndex) { - var index = fromIndex - 1, - length = array.length; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; -} - -/** - * The base implementation of `_.indexOf` without `fromIndex` bounds checks. - * - * @private - * @param {Array} array The array to inspect. - * @param {*} value The value to search for. - * @param {number} fromIndex The index to search from. - * @returns {number} Returns the index of the matched value, else `-1`. - */ -function baseIndexOf(array, value, fromIndex) { - return value === value - ? strictIndexOf(array, value, fromIndex) - : baseFindIndex(array, baseIsNaN, fromIndex); -} - -/** - * Determines the best order for running the {@link AsyncFunction}s in `tasks`, based on - * their requirements. Each function can optionally depend on other functions - * being completed first, and each function is run as soon as its requirements - * are satisfied. - * - * If any of the {@link AsyncFunction}s pass an error to their callback, the `auto` sequence - * will stop. Further tasks will not execute (so any other functions depending - * on it will not run), and the main `callback` is immediately called with the - * error. - * - * {@link AsyncFunction}s also receive an object containing the results of functions which - * have completed so far as the first argument, if they have dependencies. If a - * task function has no dependencies, it will only be passed a callback. - * - * @name auto - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Object} tasks - An object. Each of its properties is either a - * function or an array of requirements, with the {@link AsyncFunction} itself the last item - * in the array. The object's key of a property serves as the name of the task - * defined by that property, i.e. can be used when specifying requirements for - * other tasks. The function receives one or two arguments: - * * a `results` object, containing the results of the previously executed - * functions, only passed if the task has any dependencies, - * * a `callback(err, result)` function, which must be called when finished, - * passing an `error` (which can be `null`) and the result of the function's - * execution. - * @param {number} [concurrency=Infinity] - An optional `integer` for - * determining the maximum number of tasks that can be run in parallel. By - * default, as many as possible. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback. Results are always returned; however, if an - * error occurs, no further `tasks` will be performed, and the results object - * will only contain partial results. Invoked with (err, results). - * @returns undefined - * @example - * - * async.auto({ - * // this function will just be passed a callback - * readData: async.apply(fs.readFile, 'data.txt', 'utf-8'), - * showData: ['readData', function(results, cb) { - * // results.readData is the file's contents - * // ... - * }] - * }, callback); - * - * async.auto({ - * get_data: function(callback) { - * console.log('in get_data'); - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * console.log('in make_folder'); - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: ['get_data', 'make_folder', function(results, callback) { - * console.log('in write_file', JSON.stringify(results)); - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(results, callback) { - * console.log('in email_link', JSON.stringify(results)); - * // once the file is written let's email a link to it... - * // results.write_file contains the filename returned by write_file. - * callback(null, {'file':results.write_file, 'email':'user@example.com'}); - * }] - * }, function(err, results) { - * console.log('err = ', err); - * console.log('results = ', results); - * }); - */ -var auto = function (tasks, concurrency, callback) { - if (typeof concurrency === 'function') { - // concurrency is optional, shift the args. - callback = concurrency; - concurrency = null; - } - callback = once(callback || noop); - var keys$$1 = keys(tasks); - var numTasks = keys$$1.length; - if (!numTasks) { - return callback(null); - } - if (!concurrency) { - concurrency = numTasks; - } - - var results = {}; - var runningTasks = 0; - var hasError = false; - - var listeners = Object.create(null); - - var readyTasks = []; - - // for cycle detection: - var readyToCheck = []; // tasks that have been identified as reachable - // without the possibility of returning to an ancestor task - var uncheckedDependencies = {}; - - baseForOwn(tasks, function (task, key) { - if (!isArray(task)) { - // no dependencies - enqueueTask(key, [task]); - readyToCheck.push(key); - return; - } - - var dependencies = task.slice(0, task.length - 1); - var remainingDependencies = dependencies.length; - if (remainingDependencies === 0) { - enqueueTask(key, task); - readyToCheck.push(key); - return; - } - uncheckedDependencies[key] = remainingDependencies; - - arrayEach(dependencies, function (dependencyName) { - if (!tasks[dependencyName]) { - throw new Error('async.auto task `' + key + - '` has a non-existent dependency `' + - dependencyName + '` in ' + - dependencies.join(', ')); - } - addListener(dependencyName, function () { - remainingDependencies--; - if (remainingDependencies === 0) { - enqueueTask(key, task); - } - }); - }); - }); - - checkForDeadlocks(); - processQueue(); - - function enqueueTask(key, task) { - readyTasks.push(function () { - runTask(key, task); - }); - } - - function processQueue() { - if (readyTasks.length === 0 && runningTasks === 0) { - return callback(null, results); - } - while(readyTasks.length && runningTasks < concurrency) { - var run = readyTasks.shift(); - run(); - } - - } - - function addListener(taskName, fn) { - var taskListeners = listeners[taskName]; - if (!taskListeners) { - taskListeners = listeners[taskName] = []; - } - - taskListeners.push(fn); - } - - function taskComplete(taskName) { - var taskListeners = listeners[taskName] || []; - arrayEach(taskListeners, function (fn) { - fn(); - }); - processQueue(); - } - - - function runTask(key, task) { - if (hasError) return; - - var taskCallback = onlyOnce(function(err, result) { - runningTasks--; - if (arguments.length > 2) { - result = slice(arguments, 1); - } - if (err) { - var safeResults = {}; - baseForOwn(results, function(val, rkey) { - safeResults[rkey] = val; - }); - safeResults[key] = result; - hasError = true; - listeners = Object.create(null); - - callback(err, safeResults); - } else { - results[key] = result; - taskComplete(key); - } - }); - - runningTasks++; - var taskFn = wrapAsync(task[task.length - 1]); - if (task.length > 1) { - taskFn(results, taskCallback); - } else { - taskFn(taskCallback); - } - } - - function checkForDeadlocks() { - // Kahn's algorithm - // https://en.wikipedia.org/wiki/Topological_sorting#Kahn.27s_algorithm - // http://connalle.blogspot.com/2013/10/topological-sortingkahn-algorithm.html - var currentTask; - var counter = 0; - while (readyToCheck.length) { - currentTask = readyToCheck.pop(); - counter++; - arrayEach(getDependents(currentTask), function (dependent) { - if (--uncheckedDependencies[dependent] === 0) { - readyToCheck.push(dependent); - } - }); - } - - if (counter !== numTasks) { - throw new Error( - 'async.auto cannot execute tasks due to a recursive dependency' - ); - } - } - - function getDependents(taskName) { - var result = []; - baseForOwn(tasks, function (task, key) { - if (isArray(task) && baseIndexOf(task, taskName, 0) >= 0) { - result.push(key); - } - }); - return result; - } -}; - -/** - * A specialized version of `_.map` for arrays without support for iteratee - * shorthands. - * - * @private - * @param {Array} [array] The array to iterate over. - * @param {Function} iteratee The function invoked per iteration. - * @returns {Array} Returns the new mapped array. - */ -function arrayMap(array, iteratee) { - var index = -1, - length = array == null ? 0 : array.length, - result = Array(length); - - while (++index < length) { - result[index] = iteratee(array[index], index, array); - } - return result; -} - -/** `Object#toString` result references. */ -var symbolTag = '[object Symbol]'; - -/** - * Checks if `value` is classified as a `Symbol` primitive or object. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. - * @example - * - * _.isSymbol(Symbol.iterator); - * // => true - * - * _.isSymbol('abc'); - * // => false - */ -function isSymbol(value) { - return typeof value == 'symbol' || - (isObjectLike(value) && baseGetTag(value) == symbolTag); -} - -/** Used as references for various `Number` constants. */ -var INFINITY = 1 / 0; - -/** Used to convert symbols to primitives and strings. */ -var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined; -var symbolToString = symbolProto ? symbolProto.toString : undefined; - -/** - * The base implementation of `_.toString` which doesn't convert nullish - * values to empty strings. - * - * @private - * @param {*} value The value to process. - * @returns {string} Returns the string. - */ -function baseToString(value) { - // Exit early for strings to avoid a performance hit in some environments. - if (typeof value == 'string') { - return value; - } - if (isArray(value)) { - // Recursively convert values (susceptible to call stack limits). - return arrayMap(value, baseToString) + ''; - } - if (isSymbol(value)) { - return symbolToString ? symbolToString.call(value) : ''; - } - var result = (value + ''); - return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result; -} - -/** - * The base implementation of `_.slice` without an iteratee call guard. - * - * @private - * @param {Array} array The array to slice. - * @param {number} [start=0] The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the slice of `array`. - */ -function baseSlice(array, start, end) { - var index = -1, - length = array.length; - - if (start < 0) { - start = -start > length ? 0 : (length + start); - } - end = end > length ? length : end; - if (end < 0) { - end += length; - } - length = start > end ? 0 : ((end - start) >>> 0); - start >>>= 0; - - var result = Array(length); - while (++index < length) { - result[index] = array[index + start]; - } - return result; -} - -/** - * Casts `array` to a slice if it's needed. - * - * @private - * @param {Array} array The array to inspect. - * @param {number} start The start position. - * @param {number} [end=array.length] The end position. - * @returns {Array} Returns the cast slice. - */ -function castSlice(array, start, end) { - var length = array.length; - end = end === undefined ? length : end; - return (!start && end >= length) ? array : baseSlice(array, start, end); -} - -/** - * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the last unmatched string symbol. - */ -function charsEndIndex(strSymbols, chrSymbols) { - var index = strSymbols.length; - - while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** - * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol - * that is not found in the character symbols. - * - * @private - * @param {Array} strSymbols The string symbols to inspect. - * @param {Array} chrSymbols The character symbols to find. - * @returns {number} Returns the index of the first unmatched string symbol. - */ -function charsStartIndex(strSymbols, chrSymbols) { - var index = -1, - length = strSymbols.length; - - while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {} - return index; -} - -/** - * Converts an ASCII `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function asciiToArray(string) { - return string.split(''); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange = '\\ud800-\\udfff'; -var rsComboMarksRange = '\\u0300-\\u036f\\ufe20-\\ufe23'; -var rsComboSymbolsRange = '\\u20d0-\\u20f0'; -var rsVarRange = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsZWJ = '\\u200d'; - -/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ -var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboMarksRange + rsComboSymbolsRange + rsVarRange + ']'); - -/** - * Checks if `string` contains Unicode symbols. - * - * @private - * @param {string} string The string to inspect. - * @returns {boolean} Returns `true` if a symbol is found, else `false`. - */ -function hasUnicode(string) { - return reHasUnicode.test(string); -} - -/** Used to compose unicode character classes. */ -var rsAstralRange$1 = '\\ud800-\\udfff'; -var rsComboMarksRange$1 = '\\u0300-\\u036f\\ufe20-\\ufe23'; -var rsComboSymbolsRange$1 = '\\u20d0-\\u20f0'; -var rsVarRange$1 = '\\ufe0e\\ufe0f'; - -/** Used to compose unicode capture groups. */ -var rsAstral = '[' + rsAstralRange$1 + ']'; -var rsCombo = '[' + rsComboMarksRange$1 + rsComboSymbolsRange$1 + ']'; -var rsFitz = '\\ud83c[\\udffb-\\udfff]'; -var rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')'; -var rsNonAstral = '[^' + rsAstralRange$1 + ']'; -var rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}'; -var rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]'; -var rsZWJ$1 = '\\u200d'; - -/** Used to compose unicode regexes. */ -var reOptMod = rsModifier + '?'; -var rsOptVar = '[' + rsVarRange$1 + ']?'; -var rsOptJoin = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*'; -var rsSeq = rsOptVar + reOptMod + rsOptJoin; -var rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; - -/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ -var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); - -/** - * Converts a Unicode `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function unicodeToArray(string) { - return string.match(reUnicode) || []; -} - -/** - * Converts `string` to an array. - * - * @private - * @param {string} string The string to convert. - * @returns {Array} Returns the converted array. - */ -function stringToArray(string) { - return hasUnicode(string) - ? unicodeToArray(string) - : asciiToArray(string); -} - -/** - * Converts `value` to a string. An empty string is returned for `null` - * and `undefined` values. The sign of `-0` is preserved. - * - * @static - * @memberOf _ - * @since 4.0.0 - * @category Lang - * @param {*} value The value to convert. - * @returns {string} Returns the converted string. - * @example - * - * _.toString(null); - * // => '' - * - * _.toString(-0); - * // => '-0' - * - * _.toString([1, 2, 3]); - * // => '1,2,3' - */ -function toString(value) { - return value == null ? '' : baseToString(value); -} - -/** Used to match leading and trailing whitespace. */ -var reTrim = /^\s+|\s+$/g; - -/** - * Removes leading and trailing whitespace or specified characters from `string`. - * - * @static - * @memberOf _ - * @since 3.0.0 - * @category String - * @param {string} [string=''] The string to trim. - * @param {string} [chars=whitespace] The characters to trim. - * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. - * @returns {string} Returns the trimmed string. - * @example - * - * _.trim(' abc '); - * // => 'abc' - * - * _.trim('-_-abc-_-', '_-'); - * // => 'abc' - * - * _.map([' foo ', ' bar '], _.trim); - * // => ['foo', 'bar'] - */ -function trim(string, chars, guard) { - string = toString(string); - if (string && (guard || chars === undefined)) { - return string.replace(reTrim, ''); - } - if (!string || !(chars = baseToString(chars))) { - return string; - } - var strSymbols = stringToArray(string), - chrSymbols = stringToArray(chars), - start = charsStartIndex(strSymbols, chrSymbols), - end = charsEndIndex(strSymbols, chrSymbols) + 1; - - return castSlice(strSymbols, start, end).join(''); -} - -var FN_ARGS = /^(?:async\s+)?(function)?\s*[^\(]*\(\s*([^\)]*)\)/m; -var FN_ARG_SPLIT = /,/; -var FN_ARG = /(=.+)?(\s*)$/; -var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; - -function parseParams(func) { - func = func.toString().replace(STRIP_COMMENTS, ''); - func = func.match(FN_ARGS)[2].replace(' ', ''); - func = func ? func.split(FN_ARG_SPLIT) : []; - func = func.map(function (arg){ - return trim(arg.replace(FN_ARG, '')); - }); - return func; -} - -/** - * A dependency-injected version of the [async.auto]{@link module:ControlFlow.auto} function. Dependent - * tasks are specified as parameters to the function, after the usual callback - * parameter, with the parameter names matching the names of the tasks it - * depends on. This can provide even more readable task graphs which can be - * easier to maintain. - * - * If a final callback is specified, the task results are similarly injected, - * specified as named parameters after the initial error parameter. - * - * The autoInject function is purely syntactic sugar and its semantics are - * otherwise equivalent to [async.auto]{@link module:ControlFlow.auto}. - * - * @name autoInject - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.auto]{@link module:ControlFlow.auto} - * @category Control Flow - * @param {Object} tasks - An object, each of whose properties is an {@link AsyncFunction} of - * the form 'func([dependencies...], callback). The object's key of a property - * serves as the name of the task defined by that property, i.e. can be used - * when specifying requirements for other tasks. - * * The `callback` parameter is a `callback(err, result)` which must be called - * when finished, passing an `error` (which can be `null`) and the result of - * the function's execution. The remaining parameters name other tasks on - * which the task is dependent, and the results from those tasks are the - * arguments of those parameters. - * @param {Function} [callback] - An optional callback which is called when all - * the tasks have been completed. It receives the `err` argument if any `tasks` - * pass an error to their callback, and a `results` object with any completed - * task results, similar to `auto`. - * @example - * - * // The example from `auto` can be rewritten as follows: - * async.autoInject({ - * get_data: function(callback) { - * // async code to get some data - * callback(null, 'data', 'converted to array'); - * }, - * make_folder: function(callback) { - * // async code to create a directory to store a file in - * // this is run at the same time as getting the data - * callback(null, 'folder'); - * }, - * write_file: function(get_data, make_folder, callback) { - * // once there is some data and the directory exists, - * // write the data to a file in the directory - * callback(null, 'filename'); - * }, - * email_link: function(write_file, callback) { - * // once the file is written let's email a link to it... - * // write_file contains the filename returned by write_file. - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * } - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - * - * // If you are using a JS minifier that mangles parameter names, `autoInject` - * // will not work with plain functions, since the parameter names will be - * // collapsed to a single letter identifier. To work around this, you can - * // explicitly specify the names of the parameters your task function needs - * // in an array, similar to Angular.js dependency injection. - * - * // This still has an advantage over plain `auto`, since the results a task - * // depends on are still spread into arguments. - * async.autoInject({ - * //... - * write_file: ['get_data', 'make_folder', function(get_data, make_folder, callback) { - * callback(null, 'filename'); - * }], - * email_link: ['write_file', function(write_file, callback) { - * callback(null, {'file':write_file, 'email':'user@example.com'}); - * }] - * //... - * }, function(err, results) { - * console.log('err = ', err); - * console.log('email_link = ', results.email_link); - * }); - */ -function autoInject(tasks, callback) { - var newTasks = {}; - - baseForOwn(tasks, function (taskFn, key) { - var params; - var fnIsAsync = isAsync(taskFn); - var hasNoDeps = - (!fnIsAsync && taskFn.length === 1) || - (fnIsAsync && taskFn.length === 0); - - if (isArray(taskFn)) { - params = taskFn.slice(0, -1); - taskFn = taskFn[taskFn.length - 1]; - - newTasks[key] = params.concat(params.length > 0 ? newTask : taskFn); - } else if (hasNoDeps) { - // no dependencies, use the function as-is - newTasks[key] = taskFn; - } else { - params = parseParams(taskFn); - if (taskFn.length === 0 && !fnIsAsync && params.length === 0) { - throw new Error("autoInject task functions require explicit parameters."); - } - - // remove callback param - if (!fnIsAsync) params.pop(); - - newTasks[key] = params.concat(newTask); - } - - function newTask(results, taskCb) { - var newArgs = arrayMap(params, function (name) { - return results[name]; - }); - newArgs.push(taskCb); - wrapAsync(taskFn).apply(null, newArgs); - } - }); - - auto(newTasks, callback); -} - -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} - -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} - -DLL.prototype.removeLink = function(node) { - if (node.prev) node.prev.next = node.next; - else this.head = node.next; - if (node.next) node.next.prev = node.prev; - else this.tail = node.prev; - - node.prev = node.next = null; - this.length -= 1; - return node; -}; - -DLL.prototype.empty = function () { - while(this.head) this.shift(); - return this; -}; - -DLL.prototype.insertAfter = function(node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode; - else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; - -DLL.prototype.insertBefore = function(node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode; - else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; - -DLL.prototype.unshift = function(node) { - if (this.head) this.insertBefore(this.head, node); - else setInitial(this, node); -}; - -DLL.prototype.push = function(node) { - if (this.tail) this.insertAfter(this.tail, node); - else setInitial(this, node); -}; - -DLL.prototype.shift = function() { - return this.head && this.removeLink(this.head); -}; - -DLL.prototype.pop = function() { - return this.tail && this.removeLink(this.tail); -}; - -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for(var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; -}; - -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while(!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; - -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } - else if(concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var _worker = wrapAsync(worker); - var numRunning = 0; - var workersList = []; - - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || noop - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } - setImmediate$1(q.process); - } - - function _next(tasks) { - return function(err){ - numRunning -= 1; - - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; - - var index = baseIndexOf(workersList, task, 0); - if (index >= 0) { - workersList.splice(index, 1); - } - - task.callback.apply(task, arguments); - - if (err != null) { - q.error(err, task.data); - } - } - - if (numRunning <= (q.concurrency - q.buffer) ) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } - - var isProcessing = false; - var q = { - _tasks: new DLL(), - concurrency: concurrency, - payload: payload, - saturated: noop, - unsaturated:noop, - buffer: concurrency / 4, - empty: noop, - drain: noop, - error: noop, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = noop; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while(!q.paused && numRunning < q.concurrency && q._tasks.length){ - var tasks = [], data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } - - numRunning += 1; - - if (q._tasks.length === 0) { - q.empty(); - } - - if (numRunning === q.concurrency) { - q.saturated(); - } - - var cb = onlyOnce(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function() { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { return; } - q.paused = false; - setImmediate$1(q.process); - } - }; - return q; -} - -/** - * A cargo of tasks for the worker function to complete. Cargo inherits all of - * the same methods and event callbacks as [`queue`]{@link module:ControlFlow.queue}. - * @typedef {Object} CargoObject - * @memberOf module:ControlFlow - * @property {Function} length - A function returning the number of items - * waiting to be processed. Invoke like `cargo.length()`. - * @property {number} payload - An `integer` for determining how many tasks - * should be process per round. This property can be changed after a `cargo` is - * created to alter the payload on-the-fly. - * @property {Function} push - Adds `task` to the `queue`. The callback is - * called once the `worker` has finished processing the task. Instead of a - * single task, an array of `tasks` can be submitted. The respective callback is - * used for every task in the list. Invoke like `cargo.push(task, [callback])`. - * @property {Function} saturated - A callback that is called when the - * `queue.length()` hits the concurrency and further tasks will be queued. - * @property {Function} empty - A callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - A callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke like `cargo.idle()`. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke like `cargo.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke like `cargo.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. Invoke like `cargo.kill()`. - */ - -/** - * Creates a `cargo` object with the specified payload. Tasks added to the - * cargo will be processed altogether (up to the `payload` limit). If the - * `worker` is in progress, the task is queued until it becomes available. Once - * the `worker` has completed some tasks, each callback of those tasks is - * called. Check out [these](https://camo.githubusercontent.com/6bbd36f4cf5b35a0f11a96dcd2e97711ffc2fb37/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130382f62626330636662302d356632392d313165322d393734662d3333393763363464633835382e676966) [animations](https://camo.githubusercontent.com/f4810e00e1c5f5f8addbe3e9f49064fd5d102699/68747470733a2f2f662e636c6f75642e6769746875622e636f6d2f6173736574732f313637363837312f36383130312f38346339323036362d356632392d313165322d383134662d3964336430323431336266642e676966) - * for how `cargo` and `queue` work. - * - * While [`queue`]{@link module:ControlFlow.queue} passes only one task to one of a group of workers - * at a time, cargo passes an array of tasks to a single worker, repeating - * when the worker is finished. - * - * @name cargo - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An asynchronous function for processing an array - * of queued tasks. Invoked with `(tasks, callback)`. - * @param {number} [payload=Infinity] - An optional `integer` for determining - * how many tasks should be processed per round; if omitted, the default is - * unlimited. - * @returns {module:ControlFlow.CargoObject} A cargo object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the cargo and inner queue. - * @example - * - * // create a cargo object with payload 2 - * var cargo = async.cargo(function(tasks, callback) { - * for (var i=0; i true - */ -function identity(value) { - return value; -} - -function _createTester(check, getResult) { - return function(eachfn, arr, iteratee, cb) { - cb = cb || noop; - var testPassed = false; - var testResult; - eachfn(arr, function(value, _, callback) { - iteratee(value, function(err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, breakLoop); - } else { - callback(); - } - }); - }, function(err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} - -function _findGetResult(v, x) { - return x; -} - -/** - * Returns the first value in `coll` that passes an async truth test. The - * `iteratee` is applied in parallel, meaning the first iteratee to return - * `true` will fire the detect `callback` with that result. That means the - * result might not be the first item in the original `coll` (in terms of order) - * that passes the test. - - * If order within the original `coll` is important, then look at - * [`detectSeries`]{@link module:Collections.detectSeries}. - * - * @name detect - * @static - * @memberOf module:Collections - * @method - * @alias find - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - * @example - * - * async.detect(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // result now equals the first file in the list that exists - * }); - */ -var detect = doParallel(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs a maximum of `limit` async operations at a - * time. - * - * @name detectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findLimit - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectLimit = doParallelLimit(_createTester(identity, _findGetResult)); - -/** - * The same as [`detect`]{@link module:Collections.detect} but runs only a single async operation at a time. - * - * @name detectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.detect]{@link module:Collections.detect} - * @alias findSeries - * @category Collections - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A truth test to apply to each item in `coll`. - * The iteratee must complete with a boolean value as its result. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the `iteratee` functions have finished. - * Result will be the first item in the array that passes the truth test - * (iteratee) or the value `undefined` if none passed. Invoked with - * (err, result). - */ -var detectSeries = doLimit(detectLimit, 1); - -function consoleFunc(name) { - return function (fn/*, ...args*/) { - var args = slice(arguments, 1); - args.push(function (err/*, ...args*/) { - var args = slice(arguments, 1); - if (typeof console === 'object') { - if (err) { - if (console.error) { - console.error(err); - } - } else if (console[name]) { - arrayEach(args, function (x) { - console[name](x); - }); - } - } - }); - wrapAsync(fn).apply(null, args); - }; -} - -/** - * Logs the result of an [`async` function]{@link AsyncFunction} to the - * `console` using `console.dir` to display the properties of the resulting object. - * Only works in Node.js or in browsers that support `console.dir` and - * `console.error` (such as FF and Chrome). - * If multiple arguments are returned from the async function, - * `console.dir` is called on each argument in order. - * - * @name dir - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, {hello: name}); - * }, 1000); - * }; - * - * // in the node repl - * node> async.dir(hello, 'world'); - * {hello: 'world'} - */ -var dir = consoleFunc('dir'); - -/** - * The post-check version of [`during`]{@link module:ControlFlow.during}. To reflect the difference in - * the order of operations, the arguments `test` and `fn` are switched. - * - * Also a version of [`doWhilst`]{@link module:ControlFlow.doWhilst} with asynchronous `test` function. - * @name doDuring - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.during]{@link module:ControlFlow.during} - * @category Control Flow - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (...args, callback), where `...args` are the - * non-error args from the previous callback of `fn`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error if one occurred, otherwise `null`. - */ -function doDuring(fn, test, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - args.push(check); - _test.apply(this, args); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - check(null, true); - -} - -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - var args = slice(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} - -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - doWhilst(iteratee, function() { - return !test.apply(this, arguments); - }, callback); -} - -/** - * Like [`whilst`]{@link module:ControlFlow.whilst}, except the `test` is an asynchronous function that - * is passed a callback in the form of `function (err, truth)`. If error is - * passed to `test` or `fn`, the main callback is immediately called with the - * value of the error. - * - * @name during - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} test - asynchronous truth test to perform before each - * execution of `fn`. Invoked with (callback). - * @param {AsyncFunction} fn - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `fn` has stopped. `callback` - * will be passed an error, if one occurred, otherwise `null`. - * @example - * - * var count = 0; - * - * async.during( - * function (callback) { - * return callback(null, count < 5); - * }, - * function (callback) { - * count++; - * setTimeout(callback, 1000); - * }, - * function (err) { - * // 5 seconds have passed - * } - * ); - */ -function during(test, fn, callback) { - callback = onlyOnce(callback || noop); - var _fn = wrapAsync(fn); - var _test = wrapAsync(test); - - function next(err) { - if (err) return callback(err); - _test(check); - } - - function check(err, truth) { - if (err) return callback(err); - if (!truth) return callback(null); - _fn(next); - } - - _test(check); -} - -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - eachOf(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit$1(coll, limit, iteratee, callback) { - _eachOfLimit(limit)(coll, _withoutIndex(wrapAsync(iteratee)), callback); -} - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -var eachSeries = doLimit(eachLimit$1, 1); - -/** - * Wrap an async function and ensure it calls its callback on a later tick of - * the event loop. If the function already calls its callback on a next tick, - * no extra deferral is added. This is useful for preventing stack overflows - * (`RangeError: Maximum call stack size exceeded`) and generally keeping - * [Zalgo](http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony) - * contained. ES2017 `async` functions are returned as-is -- they are immune - * to Zalgo's corrupting influences, as they always resolve on a later tick. - * - * @name ensureAsync - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - an async function, one that expects a node-style - * callback as its last argument. - * @returns {AsyncFunction} Returns a wrapped function with the exact same call - * signature as the function passed in. - * @example - * - * function sometimesAsync(arg, callback) { - * if (cache[arg]) { - * return callback(null, cache[arg]); // this would be synchronous!! - * } else { - * doSomeIO(arg, callback); // this IO would be asynchronous - * } - * } - * - * // this has a risk of stack overflows if many results are cached in a row - * async.mapSeries(args, sometimesAsync, done); - * - * // this will defer sometimesAsync's callback if necessary, - * // preventing stack overflows - * async.mapSeries(args, async.ensureAsync(sometimesAsync), done); - */ -function ensureAsync(fn) { - if (isAsync(fn)) return fn; - return initialParams(function (args, callback) { - var sync = true; - args.push(function () { - var innerArgs = arguments; - if (sync) { - setImmediate$1(function () { - callback.apply(null, innerArgs); - }); - } else { - callback.apply(null, innerArgs); - } - }); - fn.apply(this, args); - sync = false; - }); -} - -function notId(v) { - return !v; -} - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -var every = doParallel(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs a maximum of `limit` async operations at a time. - * - * @name everyLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everyLimit = doParallelLimit(_createTester(notId, notId)); - -/** - * The same as [`every`]{@link module:Collections.every} but runs only a single async operation at a time. - * - * @name everySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.every]{@link module:Collections.every} - * @alias allSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in series. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - */ -var everySeries = doLimit(everyLimit, 1); - -/** - * The base implementation of `_.property` without support for deep paths. - * - * @private - * @param {string} key The key of the property to get. - * @returns {Function} Returns the new accessor function. - */ -function baseProperty(key) { - return function(object) { - return object == null ? undefined : object[key]; - }; -} - -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} - -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({index: index, value: x}); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, arrayMap(results.sort(function (a, b) { - return a.index - b.index; - }), baseProperty('value'))); - } - }); -} - -function _filter(eachfn, coll, iteratee, callback) { - var filter = isArrayLike(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, wrapAsync(iteratee), callback || noop); -} - -/** - * Returns a new array of all the values in `coll` which pass an async truth - * test. This operation is performed in parallel, but the results array will be - * in the same order as the original. - * - * @name filter - * @static - * @memberOf module:Collections - * @method - * @alias select - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.filter(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of the existing files - * }); - */ -var filter = doParallel(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs a maximum of `limit` async operations at a - * time. - * - * @name filterLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var filterLimit = doParallelLimit(_filter); - -/** - * The same as [`filter`]{@link module:Collections.filter} but runs only a single async operation at a time. - * - * @name filterSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @alias selectSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - A truth test to apply to each item in `coll`. - * The `iteratee` is passed a `callback(err, truthValue)`, which must be called - * with a boolean argument once it has completed. Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results) - */ -var filterSeries = doLimit(filterLimit, 1); - -/** - * Calls the asynchronous function `fn` with a callback parameter that allows it - * to call itself again, in series, indefinitely. - - * If an error is passed to the callback then `errback` is called with the - * error, and execution stops, otherwise it will never be called. - * - * @name forever - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} fn - an async function to call repeatedly. - * Invoked with (next). - * @param {Function} [errback] - when `fn` passes an error to it's callback, - * this function will be called, and execution stops. Invoked with (err). - * @example - * - * async.forever( - * function(next) { - * // next is suitable for passing to things that need a callback(err [, whatever]); - * // it will result in this function being called again. - * }, - * function(err) { - * // if next is called with a value in its first parameter, it will appear - * // in here as 'err', and execution will stop. - * } - * ); - */ -function forever(fn, errback) { - var done = onlyOnce(errback || noop); - var task = wrapAsync(ensureAsync(fn)); - - function next(err) { - if (err) return done(err); - task(next); - } - next(); -} - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs a maximum of `limit` async operations at a time. - * - * @name groupByLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupByLimit = function(coll, limit, iteratee, callback) { - callback = callback || noop; - var _iteratee = wrapAsync(iteratee); - mapLimit(coll, limit, function(val, callback) { - _iteratee(val, function(err, key) { - if (err) return callback(err); - return callback(null, {key: key, val: val}); - }); - }, function(err, mapResults) { - var result = {}; - // from MDN, handle object having an `hasOwnProperty` prop - var hasOwnProperty = Object.prototype.hasOwnProperty; - - for (var i = 0; i < mapResults.length; i++) { - if (mapResults[i]) { - var key = mapResults[i].key; - var val = mapResults[i].val; - - if (hasOwnProperty.call(result, key)) { - result[key].push(val); - } else { - result[key] = [val]; - } - } - } - - return callback(err, result); - }); -}; - -/** - * Returns a new object, where each value corresponds to an array of items, from - * `coll`, that returned the corresponding key. That is, the keys of the object - * correspond to the values passed to the `iteratee` callback. - * - * Note: Since this function applies the `iteratee` to each item in parallel, - * there is no guarantee that the `iteratee` functions will complete in order. - * However, the values for each key in the `result` will be in the same order as - * the original `coll`. For Objects, the values will roughly be in the order of - * the original Objects' keys (but this can vary across JavaScript engines). - * - * @name groupBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - * @example - * - * async.groupBy(['userId1', 'userId2', 'userId3'], function(userId, callback) { - * db.findById(userId, function(err, user) { - * if (err) return callback(err); - * return callback(null, user.age); - * }); - * }, function(err, result) { - * // result is object containing the userIds grouped by age - * // e.g. { 30: ['userId1', 'userId3'], 42: ['userId2']}; - * }); - */ -var groupBy = doLimit(groupByLimit, Infinity); - -/** - * The same as [`groupBy`]{@link module:Collections.groupBy} but runs only a single async operation at a time. - * - * @name groupBySeries - * @static - * @memberOf module:Collections - * @method - * @see [async.groupBy]{@link module:Collections.groupBy} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a `key` to group the value under. - * Invoked with (value, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Result is an `Object` whoses - * properties are arrays of values which returned the corresponding key. - */ -var groupBySeries = doLimit(groupByLimit, 1); - -/** - * Logs the result of an `async` function to the `console`. Only works in - * Node.js or in browsers that support `console.log` and `console.error` (such - * as FF and Chrome). If multiple arguments are returned from the async - * function, `console.log` is called on each argument in order. - * - * @name log - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} function - The function you want to eventually apply - * all arguments to. - * @param {...*} arguments... - Any number of arguments to apply to the function. - * @example - * - * // in a module - * var hello = function(name, callback) { - * setTimeout(function() { - * callback(null, 'hello ' + name); - * }, 1000); - * }; - * - * // in the node repl - * node> async.log(hello, 'world'); - * 'hello world' - */ -var log = consoleFunc('log'); - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs a maximum of `limit` async operations at a - * time. - * - * @name mapValuesLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -function mapValuesLimit(obj, limit, iteratee, callback) { - callback = once(callback || noop); - var newObj = {}; - var _iteratee = wrapAsync(iteratee); - eachOfLimit(obj, limit, function(val, key, next) { - _iteratee(val, key, function (err, result) { - if (err) return next(err); - newObj[key] = result; - next(); - }); - }, function (err) { - callback(err, newObj); - }); -} - -/** - * A relative of [`map`]{@link module:Collections.map}, designed for use with objects. - * - * Produces a new Object by mapping each value of `obj` through the `iteratee` - * function. The `iteratee` is called each `value` and `key` from `obj` and a - * callback for when it has finished processing. Each of these callbacks takes - * two arguments: an `error`, and the transformed item from `obj`. If `iteratee` - * passes an error to its callback, the main `callback` (for the `mapValues` - * function) is immediately called with the error. - * - * Note, the order of the keys in the result is not guaranteed. The keys will - * be roughly in the order they complete, (but this is very engine-specific) - * - * @name mapValues - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - * @example - * - * async.mapValues({ - * f1: 'file1', - * f2: 'file2', - * f3: 'file3' - * }, function (file, key, callback) { - * fs.stat(file, callback); - * }, function(err, result) { - * // result is now a map of stats for each file, e.g. - * // { - * // f1: [stats for file1], - * // f2: [stats for file2], - * // f3: [stats for file3] - * // } - * }); - */ - -var mapValues = doLimit(mapValuesLimit, Infinity); - -/** - * The same as [`mapValues`]{@link module:Collections.mapValues} but runs only a single async operation at a time. - * - * @name mapValuesSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.mapValues]{@link module:Collections.mapValues} - * @category Collection - * @param {Object} obj - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each value and key - * in `coll`. - * The iteratee should complete with the transformed value as its result. - * Invoked with (value, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. `result` is a new object consisting - * of each key from `obj`, with each transformed value on the right-hand side. - * Invoked with (err, result). - */ -var mapValuesSeries = doLimit(mapValuesLimit, 1); - -function has(obj, key) { - return key in obj; -} - -/** - * Caches the results of an async function. When creating a hash to store - * function results against, the callback is omitted from the hash and an - * optional hash function can be used. - * - * If no hash function is specified, the first argument is used as a hash key, - * which may work reasonably if it is a string or a data type that converts to a - * distinct string. Note that objects and arrays will not behave reasonably. - * Neither will cases where the other arguments are significant. In such cases, - * specify your own hash function. - * - * The cache of results is exposed as the `memo` property of the function - * returned by `memoize`. - * - * @name memoize - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function to proxy and cache results from. - * @param {Function} hasher - An optional function for generating a custom hash - * for storing results. It has all the arguments applied to it apart from the - * callback, and must be synchronous. - * @returns {AsyncFunction} a memoized version of `fn` - * @example - * - * var slow_fn = function(name, callback) { - * // do something - * callback(null, result); - * }; - * var fn = async.memoize(slow_fn); - * - * // fn can now be used as if it were slow_fn - * fn('some name', function() { - * // callback - * }); - */ -function memoize(fn, hasher) { - var memo = Object.create(null); - var queues = Object.create(null); - hasher = hasher || identity; - var _fn = wrapAsync(fn); - var memoized = initialParams(function memoized(args, callback) { - var key = hasher.apply(null, args); - if (has(memo, key)) { - setImmediate$1(function() { - callback.apply(null, memo[key]); - }); - } else if (has(queues, key)) { - queues[key].push(callback); - } else { - queues[key] = [callback]; - _fn.apply(null, args.concat(function(/*args*/) { - var args = slice(arguments); - memo[key] = args; - var q = queues[key]; - delete queues[key]; - for (var i = 0, l = q.length; i < l; i++) { - q[i].apply(null, args); - } - })); - } - }); - memoized.memo = memo; - memoized.unmemoized = fn; - return memoized; -} - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `setImmediate`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name nextTick - * @static - * @memberOf module:Utils - * @method - * @alias setImmediate - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -var _defer$1; - -if (hasNextTick) { - _defer$1 = process.nextTick; -} else if (hasSetImmediate) { - _defer$1 = setImmediate; -} else { - _defer$1 = fallback; -} - -var nextTick = wrap(_defer$1); - -function _parallel(eachfn, tasks, callback) { - callback = callback || noop; - var results = isArrayLike(tasks) ? [] : {}; - - eachfn(tasks, function (task, key, callback) { - wrapAsync(task)(function (err, result) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} - -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - _parallel(eachOf, tasks, callback); -} - -/** - * The same as [`parallel`]{@link module:ControlFlow.parallel} but runs a maximum of `limit` async operations at a - * time. - * - * @name parallelLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.parallel]{@link module:ControlFlow.parallel} - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - */ -function parallelLimit$1(tasks, limit, callback) { - _parallel(_eachOfLimit(limit), tasks, callback); -} - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ -var queue$1 = function (worker, concurrency) { - var _worker = wrapAsync(worker); - return queue(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; - -/** - * The same as [async.queue]{@link module:ControlFlow.queue} only tasks are assigned a priority and - * completed in ascending priority order. - * - * @name priorityQueue - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.queue]{@link module:ControlFlow.queue} - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. - * Invoked with (task, callback). - * @param {number} concurrency - An `integer` for determining how many `worker` - * functions should be run in parallel. If omitted, the concurrency defaults to - * `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A priorityQueue object to manage the tasks. There are two - * differences between `queue` and `priorityQueue` objects: - * * `push(task, priority, [callback])` - `priority` should be a number. If an - * array of `tasks` is given, all tasks will be assigned the same priority. - * * The `unshift` method was removed. - */ -var priorityQueue = function(worker, concurrency) { - // Start with a normal queue - var q = queue$1(worker, concurrency); - - // Override push to accept second parameter representing priority - q.push = function(data, priority, callback) { - if (callback == null) callback = noop; - if (typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!isArray(data)) { - data = [data]; - } - if (data.length === 0) { - // call drain immediately if there are no tasks - return setImmediate$1(function() { - q.drain(); - }); - } - - priority = priority || 0; - var nextNode = q._tasks.head; - while (nextNode && priority >= nextNode.priority) { - nextNode = nextNode.next; - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - priority: priority, - callback: callback - }; - - if (nextNode) { - q._tasks.insertBefore(nextNode, item); - } else { - q._tasks.push(item); - } - } - setImmediate$1(q.process); - }; - - // Remove unshift function - delete q.unshift; - - return q; -}; - -/** - * Runs the `tasks` array of functions in parallel, without waiting until the - * previous function has completed. Once any of the `tasks` complete or pass an - * error to its callback, the main `callback` is immediately called. It's - * equivalent to `Promise.race()`. - * - * @name race - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array containing [async functions]{@link AsyncFunction} - * to run. Each function can complete with an optional `result` value. - * @param {Function} callback - A callback to run once any of the functions have - * completed. This function gets an error or result from the first function that - * completed. Invoked with (err, result). - * @returns undefined - * @example - * - * async.race([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // main callback - * function(err, result) { - * // the result will be equal to 'two' as it finishes earlier - * }); - */ -function race(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new TypeError('First argument to race must be an array of functions')); - if (!tasks.length) return callback(); - for (var i = 0, l = tasks.length; i < l; i++) { - wrapAsync(tasks[i])(callback); - } -} - -/** - * Same as [`reduce`]{@link module:Collections.reduce}, only operates on `array` in reverse order. - * - * @name reduceRight - * @static - * @memberOf module:Collections - * @method - * @see [async.reduce]{@link module:Collections.reduce} - * @alias foldr - * @category Collection - * @param {Array} array - A collection to iterate over. - * @param {*} memo - The initial state of the reduction. - * @param {AsyncFunction} iteratee - A function applied to each item in the - * array to produce the next step in the reduction. - * The `iteratee` should complete with the next state of the reduction. - * If the iteratee complete with an error, the reduction is stopped and the - * main `callback` is immediately called with the error. - * Invoked with (memo, item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the reduced value. Invoked with - * (err, result). - */ -function reduceRight (array, memo, iteratee, callback) { - var reversed = slice(array).reverse(); - reduce(reversed, memo, iteratee, callback); -} - -/** - * Wraps the async function in another function that always completes with a - * result object, even when it errors. - * - * The result object has either the property `error` or `value`. - * - * @name reflect - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} fn - The async function you want to wrap - * @returns {Function} - A function that always passes null to it's callback as - * the error. The second argument to the callback will be an `object` with - * either an `error` or a `value` property. - * @example - * - * async.parallel([ - * async.reflect(function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }), - * async.reflect(function(callback) { - * // do some more stuff but error ... - * callback('bad stuff happened'); - * }), - * async.reflect(function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * }) - * ], - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = 'bad stuff happened' - * // results[2].value = 'two' - * }); - */ -function reflect(fn) { - var _fn = wrapAsync(fn); - return initialParams(function reflectOn(args, reflectCallback) { - args.push(function callback(error, cbArg) { - if (error) { - reflectCallback(null, { error: error }); - } else { - var value; - if (arguments.length <= 2) { - value = cbArg; - } else { - value = slice(arguments, 1); - } - reflectCallback(null, { value: value }); - } - }); - - return _fn.apply(this, args); - }); -} - -function reject$1(eachfn, arr, iteratee, callback) { - _filter(eachfn, arr, function(value, cb) { - iteratee(value, function(err, v) { - cb(err, !v); - }); - }, callback); -} - -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -var reject = doParallel(reject$1); - -/** - * A helper function that wraps an array or an object of functions with `reflect`. - * - * @name reflectAll - * @static - * @memberOf module:Utils - * @method - * @see [async.reflect]{@link module:Utils.reflect} - * @category Util - * @param {Array|Object|Iterable} tasks - The collection of - * [async functions]{@link AsyncFunction} to wrap in `async.reflect`. - * @returns {Array} Returns an array of async functions, each wrapped in - * `async.reflect` - * @example - * - * let tasks = [ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * // do some more stuff but error ... - * callback(new Error('bad stuff happened')); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ]; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results[0].value = 'one' - * // results[1].error = Error('bad stuff happened') - * // results[2].value = 'two' - * }); - * - * // an example using an object instead of an array - * let tasks = { - * one: function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * two: function(callback) { - * callback('two'); - * }, - * three: function(callback) { - * setTimeout(function() { - * callback(null, 'three'); - * }, 100); - * } - * }; - * - * async.parallel(async.reflectAll(tasks), - * // optional callback - * function(err, results) { - * // values - * // results.one.value = 'one' - * // results.two.error = 'two' - * // results.three.value = 'three' - * }); - */ -function reflectAll(tasks) { - var results; - if (isArray(tasks)) { - results = arrayMap(tasks, reflect); - } else { - results = {}; - baseForOwn(tasks, function(task, key) { - results[key] = reflect.call(this, task); - }); - } - return results; -} - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs a maximum of `limit` async operations at a - * time. - * - * @name rejectLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectLimit = doParallelLimit(reject$1); - -/** - * The same as [`reject`]{@link module:Collections.reject} but runs only a single async operation at a time. - * - * @name rejectSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.reject]{@link module:Collections.reject} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - */ -var rejectSeries = doLimit(rejectLimit, 1); - -/** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @since 2.4.0 - * @category Util - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new constant function. - * @example - * - * var objects = _.times(2, _.constant({ 'a': 1 })); - * - * console.log(objects); - * // => [{ 'a': 1 }, { 'a': 1 }] - * - * console.log(objects[0] === objects[1]); - * // => true - */ -function constant$1(value) { - return function() { - return value; - }; -} - -/** - * Attempts to get a successful response from `task` no more than `times` times - * before returning an error. If the task is successful, the `callback` will be - * passed the result of the successful task. If all attempts fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name retry - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @see [async.retryable]{@link module:ControlFlow.retryable} - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - Can be either an - * object with `times` and `interval` or a number. - * * `times` - The number of attempts to make before giving up. The default - * is `5`. - * * `interval` - The time to wait between retries, in milliseconds. The - * default is `0`. The interval may also be specified as a function of the - * retry count (see example). - * * `errorFilter` - An optional synchronous function that is invoked on - * erroneous result. If it returns `true` the retry attempts will continue; - * if the function returns `false` the retry flow is aborted with the current - * attempt's error and result being returned to the final callback. - * Invoked with (err). - * * If `opts` is a number, the number specifies the number of times to retry, - * with the default interval of `0`. - * @param {AsyncFunction} task - An async function to retry. - * Invoked with (callback). - * @param {Function} [callback] - An optional callback which is called when the - * task has succeeded, or after the final failed attempt. It receives the `err` - * and `result` arguments of the last attempt at completing the `task`. Invoked - * with (err, results). - * - * @example - * - * // The `retry` function can be used as a stand-alone control flow by passing - * // a callback, as shown below: - * - * // try calling apiMethod 3 times - * async.retry(3, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 3 times, waiting 200 ms between each retry - * async.retry({times: 3, interval: 200}, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod 10 times with exponential backoff - * // (i.e. intervals of 100, 200, 400, 800, 1600, ... milliseconds) - * async.retry({ - * times: 10, - * interval: function(retryCount) { - * return 50 * Math.pow(2, retryCount); - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod the default 5 times no delay between each retry - * async.retry(apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // try calling apiMethod only when error condition satisfies, all other - * // errors will abort the retry control flow and return to final callback - * async.retry({ - * errorFilter: function(err) { - * return err.message === 'Temporary error'; // only retry on a specific error - * } - * }, apiMethod, function(err, result) { - * // do something with the result - * }); - * - * // It can also be embedded within other control flow functions to retry - * // individual methods that are not as reliable, like this: - * async.auto({ - * users: api.getUsers.bind(api), - * payments: async.retryable(3, api.getPayments.bind(api)) - * }, function(err, results) { - * // do something with the results - * }); - * - */ -function retry(opts, task, callback) { - var DEFAULT_TIMES = 5; - var DEFAULT_INTERVAL = 0; - - var options = { - times: DEFAULT_TIMES, - intervalFunc: constant$1(DEFAULT_INTERVAL) - }; - - function parseTimes(acc, t) { - if (typeof t === 'object') { - acc.times = +t.times || DEFAULT_TIMES; - - acc.intervalFunc = typeof t.interval === 'function' ? - t.interval : - constant$1(+t.interval || DEFAULT_INTERVAL); - - acc.errorFilter = t.errorFilter; - } else if (typeof t === 'number' || typeof t === 'string') { - acc.times = +t || DEFAULT_TIMES; - } else { - throw new Error("Invalid arguments for async.retry"); - } - } - - if (arguments.length < 3 && typeof opts === 'function') { - callback = task || noop; - task = opts; - } else { - parseTimes(options, opts); - callback = callback || noop; - } - - if (typeof task !== 'function') { - throw new Error("Invalid arguments for async.retry"); - } - - var _task = wrapAsync(task); - - var attempt = 1; - function retryAttempt() { - _task(function(err) { - if (err && attempt++ < options.times && - (typeof options.errorFilter != 'function' || - options.errorFilter(err))) { - setTimeout(retryAttempt, options.intervalFunc(attempt)); - } else { - callback.apply(null, arguments); - } - }); - } - - retryAttempt(); -} - -/** - * A close relative of [`retry`]{@link module:ControlFlow.retry}. This method - * wraps a task and makes it retryable, rather than immediately calling it - * with retries. - * - * @name retryable - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.retry]{@link module:ControlFlow.retry} - * @category Control Flow - * @param {Object|number} [opts = {times: 5, interval: 0}| 5] - optional - * options, exactly the same as from `retry` - * @param {AsyncFunction} task - the asynchronous function to wrap. - * This function will be passed any arguments passed to the returned wrapper. - * Invoked with (...args, callback). - * @returns {AsyncFunction} The wrapped function, which when invoked, will - * retry on an error, based on the parameters specified in `opts`. - * This function will accept the same parameters as `task`. - * @example - * - * async.auto({ - * dep1: async.retryable(3, getFromFlakyService), - * process: ["dep1", async.retryable(3, function (results, cb) { - * maybeProcessData(results.dep1, cb); - * })] - * }, callback); - */ -var retryable = function (opts, task) { - if (!task) { - task = opts; - opts = null; - } - var _task = wrapAsync(task); - return initialParams(function (args, callback) { - function taskFn(cb) { - _task.apply(null, args.concat(cb)); - } - - if (opts) retry(opts, taskFn, callback); - else retry(taskFn, callback); - - }); -}; - -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - _parallel(eachOfSeries, tasks, callback); -} - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -var some = doParallel(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs a maximum of `limit` async operations at a time. - * - * @name someLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anyLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someLimit = doParallelLimit(_createTester(Boolean, identity)); - -/** - * The same as [`some`]{@link module:Collections.some} but runs only a single async operation at a time. - * - * @name someSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.some]{@link module:Collections.some} - * @alias anySeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in series. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - */ -var someSeries = doLimit(someLimit, 1); - -/** - * Sorts a list by the results of running each `coll` value through an async - * `iteratee`. - * - * @name sortBy - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with a value to use as the sort criteria as - * its `result`. - * Invoked with (item, callback). - * @param {Function} callback - A callback which is called after all the - * `iteratee` functions have finished, or an error occurs. Results is the items - * from the original `coll` sorted by the values returned by the `iteratee` - * calls. Invoked with (err, results). - * @example - * - * async.sortBy(['file1','file2','file3'], function(file, callback) { - * fs.stat(file, function(err, stats) { - * callback(err, stats.mtime); - * }); - * }, function(err, results) { - * // results is now the original array of files sorted by - * // modified date - * }); - * - * // By modifying the callback parameter the - * // sorting order can be influenced: - * - * // ascending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x); - * }, function(err,result) { - * // result callback - * }); - * - * // descending order - * async.sortBy([1,9,3,5], function(x, callback) { - * callback(null, x*-1); //<- x*-1 instead of x, turns the order around - * }, function(err,result) { - * // result callback - * }); - */ -function sortBy (coll, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - map(coll, function (x, callback) { - _iteratee(x, function (err, criteria) { - if (err) return callback(err); - callback(null, {value: x, criteria: criteria}); - }); - }, function (err, results) { - if (err) return callback(err); - callback(null, arrayMap(results.sort(comparator), baseProperty('value'))); - }); - - function comparator(left, right) { - var a = left.criteria, b = right.criteria; - return a < b ? -1 : a > b ? 1 : 0; - } -} - -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = wrapAsync(asyncFn); - - return initialParams(function (args, callback) { - var timedOut = false; - var timer; - - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} - -/* Built-in method references for those with the same name as other `lodash` methods. */ -var nativeCeil = Math.ceil; -var nativeMax = Math.max; - -/** - * The base implementation of `_.range` and `_.rangeRight` which doesn't - * coerce arguments. - * - * @private - * @param {number} start The start of the range. - * @param {number} end The end of the range. - * @param {number} step The value to increment or decrement by. - * @param {boolean} [fromRight] Specify iterating from right to left. - * @returns {Array} Returns the range of numbers. - */ -function baseRange(start, end, step, fromRight) { - var index = -1, - length = nativeMax(nativeCeil((end - start) / (step || 1)), 0), - result = Array(length); - - while (length--) { - result[fromRight ? length : ++index] = start; - start += step; - } - return result; -} - -/** - * The same as [times]{@link module:ControlFlow.times} but runs a maximum of `limit` async operations at a - * time. - * - * @name timesLimit - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} count - The number of times to run the function. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see [async.map]{@link module:Collections.map}. - */ -function timeLimit(count, limit, iteratee, callback) { - var _iteratee = wrapAsync(iteratee); - mapLimit(baseRange(0, count, 1), limit, _iteratee, callback); -} - -/** - * Calls the `iteratee` function `n` times, and accumulates results in the same - * manner you would use with [map]{@link module:Collections.map}. - * - * @name times - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.map]{@link module:Collections.map} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - * @example - * - * // Pretend this is some complicated async factory - * var createUser = function(id, callback) { - * callback(null, { - * id: 'user' + id - * }); - * }; - * - * // generate 5 users - * async.times(5, function(n, next) { - * createUser(n, function(err, user) { - * next(err, user); - * }); - * }, function(err, users) { - * // we should now have 5 users - * }); - */ -var times = doLimit(timeLimit, Infinity); - -/** - * The same as [times]{@link module:ControlFlow.times} but runs only a single async operation at a time. - * - * @name timesSeries - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.times]{@link module:ControlFlow.times} - * @category Control Flow - * @param {number} n - The number of times to run the function. - * @param {AsyncFunction} iteratee - The async function to call `n` times. - * Invoked with the iteration index and a callback: (n, next). - * @param {Function} callback - see {@link module:Collections.map}. - */ -var timesSeries = doLimit(timeLimit, 1); - -/** - * A relative of `reduce`. Takes an Object or Array, and iterates over each - * element in series, each step potentially mutating an `accumulator` value. - * The type of the accumulator defaults to the type of collection passed in. - * - * @name transform - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {*} [accumulator] - The initial state of the transform. If omitted, - * it will default to an empty Object or Array, depending on the type of `coll` - * @param {AsyncFunction} iteratee - A function applied to each item in the - * collection that potentially modifies the accumulator. - * Invoked with (accumulator, item, key, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result is the transformed accumulator. - * Invoked with (err, result). - * @example - * - * async.transform([1,2,3], function(acc, item, index, callback) { - * // pointless async: - * process.nextTick(function() { - * acc.push(item * 2) - * callback(null) - * }); - * }, function(err, result) { - * // result is now equal to [2, 4, 6] - * }); - * - * @example - * - * async.transform({a: 1, b: 2, c: 3}, function (obj, val, key, callback) { - * setImmediate(function () { - * obj[key] = val * 2; - * callback(); - * }) - * }, function (err, result) { - * // result is equal to {a: 2, b: 4, c: 6} - * }) - */ -function transform (coll, accumulator, iteratee, callback) { - if (arguments.length <= 3) { - callback = iteratee; - iteratee = accumulator; - accumulator = isArray(coll) ? [] : {}; - } - callback = once(callback || noop); - var _iteratee = wrapAsync(iteratee); - - eachOf(coll, function(v, k, cb) { - _iteratee(accumulator, v, k, cb); - }, function(err) { - callback(err, accumulator); - }); -} - -/** - * It runs each task in series but stops whenever any of the functions were - * successful. If one of the tasks were successful, the `callback` will be - * passed the result of the successful task. If all tasks fail, the callback - * will be passed the error and result (if any) of the final attempt. - * - * @name tryEach - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing functions to - * run, each function is passed a `callback(err, result)` it must call on - * completion with an error `err` (which can be `null`) and an optional `result` - * value. - * @param {Function} [callback] - An optional callback which is called when one - * of the tasks has succeeded, or all have failed. It receives the `err` and - * `result` arguments of the last attempt at completing the `task`. Invoked with - * (err, results). - * @example - * async.try([ - * function getDataFromFirstWebsite(callback) { - * // Try getting the data from the first website - * callback(err, data); - * }, - * function getDataFromSecondWebsite(callback) { - * // First website failed, - * // Try getting the data from the backup website - * callback(err, data); - * } - * ], - * // optional callback - * function(err, results) { - * Now do something with the data. - * }); - * - */ -function tryEach(tasks, callback) { - var error = null; - var result; - callback = callback || noop; - eachSeries(tasks, function(task, callback) { - wrapAsync(task)(function (err, res/*, ...args*/) { - if (arguments.length > 2) { - result = slice(arguments, 1); - } else { - result = res; - } - error = err; - callback(!err); - }); - }, function () { - callback(error, result); - }); -} - -/** - * Undoes a [memoize]{@link module:Utils.memoize}d function, reverting it to the original, - * unmemoized form. Handy for testing. - * - * @name unmemoize - * @static - * @memberOf module:Utils - * @method - * @see [async.memoize]{@link module:Utils.memoize} - * @category Util - * @param {AsyncFunction} fn - the memoized function - * @returns {AsyncFunction} a function that calls the original unmemoized function - */ -function unmemoize(fn) { - return function () { - return (fn.unmemoized || fn).apply(null, arguments); - }; -} - -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = onlyOnce(callback || noop); - var _iteratee = wrapAsync(iteratee); - if (!test()) return callback(null); - var next = function(err/*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = slice(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} - -/** - * Repeatedly call `iteratee` until `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. `callback` will be passed an error and any - * arguments passed to the final `iteratee`'s callback. - * - * The inverse of [whilst]{@link module:ControlFlow.whilst}. - * - * @name until - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function until(test, iteratee, callback) { - whilst(function() { - return !test.apply(this, arguments); - }, iteratee, callback); -} - -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -var waterfall = function(tasks, callback) { - callback = once(callback || noop); - if (!isArray(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = wrapAsync(tasks[taskIndex++]); - args.push(onlyOnce(next)); - task.apply(null, args); - } - - function next(err/*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask(slice(arguments, 1)); - } - - nextTask([]); -}; - -/** - * An "async function" in the context of Async is an asynchronous function with - * a variable number of parameters, with the final parameter being a callback. - * (`function (arg1, arg2, ..., callback) {}`) - * The final callback is of the form `callback(err, results...)`, which must be - * called once the function is completed. The callback should be called with a - * Error as its first argument to signal that an error occurred. - * Otherwise, if no error occurred, it should be called with `null` as the first - * argument, and any additional `result` arguments that may apply, to signal - * successful completion. - * The callback must be called exactly once, ideally on a later tick of the - * JavaScript event loop. - * - * This type of function is also referred to as a "Node-style async function", - * or a "continuation passing-style function" (CPS). Most of the methods of this - * library are themselves CPS/Node-style async functions, or functions that - * return CPS/Node-style async functions. - * - * Wherever we accept a Node-style async function, we also directly accept an - * [ES2017 `async` function]{@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function}. - * In this case, the `async` function will not be passed a final callback - * argument, and any thrown error will be used as the `err` argument of the - * implicit callback, and the return value will be used as the `result` value. - * (i.e. a `rejected` of the returned Promise becomes the `err` callback - * argument, and a `resolved` value becomes the `result`.) - * - * Note, due to JavaScript limitations, we can only detect native `async` - * functions and not transpilied implementations. - * Your environment must have `async`/`await` support for this to work. - * (e.g. Node > v7.6, or a recent version of a modern browser). - * If you are using `async` functions through a transpiler (e.g. Babel), you - * must still wrap the function with [asyncify]{@link module:Utils.asyncify}, - * because the `async function` will be compiled to an ordinary function that - * returns a promise. - * - * @typedef {Function} AsyncFunction - * @static - */ - -/** - * Async is a utility module which provides straight-forward, powerful functions - * for working with asynchronous JavaScript. Although originally designed for - * use with [Node.js](http://nodejs.org) and installable via - * `npm install --save async`, it can also be used directly in the browser. - * @module async - * @see AsyncFunction - */ - - -/** - * A collection of `async` functions for manipulating collections, such as - * arrays and objects. - * @module Collections - */ - -/** - * A collection of `async` functions for controlling the flow through a script. - * @module ControlFlow - */ - -/** - * A collection of `async` utility functions. - * @module Utils - */ - -var index = { - applyEach: applyEach, - applyEachSeries: applyEachSeries, - apply: apply, - asyncify: asyncify, - auto: auto, - autoInject: autoInject, - cargo: cargo, - compose: compose, - concat: concat, - concatLimit: concatLimit, - concatSeries: concatSeries, - constant: constant, - detect: detect, - detectLimit: detectLimit, - detectSeries: detectSeries, - dir: dir, - doDuring: doDuring, - doUntil: doUntil, - doWhilst: doWhilst, - during: during, - each: eachLimit, - eachLimit: eachLimit$1, - eachOf: eachOf, - eachOfLimit: eachOfLimit, - eachOfSeries: eachOfSeries, - eachSeries: eachSeries, - ensureAsync: ensureAsync, - every: every, - everyLimit: everyLimit, - everySeries: everySeries, - filter: filter, - filterLimit: filterLimit, - filterSeries: filterSeries, - forever: forever, - groupBy: groupBy, - groupByLimit: groupByLimit, - groupBySeries: groupBySeries, - log: log, - map: map, - mapLimit: mapLimit, - mapSeries: mapSeries, - mapValues: mapValues, - mapValuesLimit: mapValuesLimit, - mapValuesSeries: mapValuesSeries, - memoize: memoize, - nextTick: nextTick, - parallel: parallelLimit, - parallelLimit: parallelLimit$1, - priorityQueue: priorityQueue, - queue: queue$1, - race: race, - reduce: reduce, - reduceRight: reduceRight, - reflect: reflect, - reflectAll: reflectAll, - reject: reject, - rejectLimit: rejectLimit, - rejectSeries: rejectSeries, - retry: retry, - retryable: retryable, - seq: seq, - series: series, - setImmediate: setImmediate$1, - some: some, - someLimit: someLimit, - someSeries: someSeries, - sortBy: sortBy, - timeout: timeout, - times: times, - timesLimit: timeLimit, - timesSeries: timesSeries, - transform: transform, - tryEach: tryEach, - unmemoize: unmemoize, - until: until, - waterfall: waterfall, - whilst: whilst, - - // aliases - all: every, - any: some, - forEach: eachLimit, - forEachSeries: eachSeries, - forEachLimit: eachLimit$1, - forEachOf: eachOf, - forEachOfSeries: eachOfSeries, - forEachOfLimit: eachOfLimit, - inject: reduce, - foldl: reduce, - foldr: reduceRight, - select: filter, - selectLimit: filterLimit, - selectSeries: filterSeries, - wrapSync: asyncify -}; - -exports['default'] = index; -exports.applyEach = applyEach; -exports.applyEachSeries = applyEachSeries; -exports.apply = apply; -exports.asyncify = asyncify; -exports.auto = auto; -exports.autoInject = autoInject; -exports.cargo = cargo; -exports.compose = compose; -exports.concat = concat; -exports.concatLimit = concatLimit; -exports.concatSeries = concatSeries; -exports.constant = constant; -exports.detect = detect; -exports.detectLimit = detectLimit; -exports.detectSeries = detectSeries; -exports.dir = dir; -exports.doDuring = doDuring; -exports.doUntil = doUntil; -exports.doWhilst = doWhilst; -exports.during = during; -exports.each = eachLimit; -exports.eachLimit = eachLimit$1; -exports.eachOf = eachOf; -exports.eachOfLimit = eachOfLimit; -exports.eachOfSeries = eachOfSeries; -exports.eachSeries = eachSeries; -exports.ensureAsync = ensureAsync; -exports.every = every; -exports.everyLimit = everyLimit; -exports.everySeries = everySeries; -exports.filter = filter; -exports.filterLimit = filterLimit; -exports.filterSeries = filterSeries; -exports.forever = forever; -exports.groupBy = groupBy; -exports.groupByLimit = groupByLimit; -exports.groupBySeries = groupBySeries; -exports.log = log; -exports.map = map; -exports.mapLimit = mapLimit; -exports.mapSeries = mapSeries; -exports.mapValues = mapValues; -exports.mapValuesLimit = mapValuesLimit; -exports.mapValuesSeries = mapValuesSeries; -exports.memoize = memoize; -exports.nextTick = nextTick; -exports.parallel = parallelLimit; -exports.parallelLimit = parallelLimit$1; -exports.priorityQueue = priorityQueue; -exports.queue = queue$1; -exports.race = race; -exports.reduce = reduce; -exports.reduceRight = reduceRight; -exports.reflect = reflect; -exports.reflectAll = reflectAll; -exports.reject = reject; -exports.rejectLimit = rejectLimit; -exports.rejectSeries = rejectSeries; -exports.retry = retry; -exports.retryable = retryable; -exports.seq = seq; -exports.series = series; -exports.setImmediate = setImmediate$1; -exports.some = some; -exports.someLimit = someLimit; -exports.someSeries = someSeries; -exports.sortBy = sortBy; -exports.timeout = timeout; -exports.times = times; -exports.timesLimit = timeLimit; -exports.timesSeries = timesSeries; -exports.transform = transform; -exports.tryEach = tryEach; -exports.unmemoize = unmemoize; -exports.until = until; -exports.waterfall = waterfall; -exports.whilst = whilst; -exports.all = every; -exports.allLimit = everyLimit; -exports.allSeries = everySeries; -exports.any = some; -exports.anyLimit = someLimit; -exports.anySeries = someSeries; -exports.find = detect; -exports.findLimit = detectLimit; -exports.findSeries = detectSeries; -exports.forEach = eachLimit; -exports.forEachSeries = eachSeries; -exports.forEachLimit = eachLimit$1; -exports.forEachOf = eachOf; -exports.forEachOfSeries = eachOfSeries; -exports.forEachOfLimit = eachOfLimit; -exports.inject = reduce; -exports.foldl = reduce; -exports.foldr = reduceRight; -exports.select = filter; -exports.selectLimit = filterLimit; -exports.selectSeries = filterSeries; -exports.wrapSync = asyncify; - -Object.defineProperty(exports, '__esModule', { value: true }); - -}))); - -}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{"_process":1009}],18:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doUntil; - -var _doWhilst = require('./doWhilst'); - -var _doWhilst2 = _interopRequireDefault(_doWhilst); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Like ['doWhilst']{@link module:ControlFlow.doWhilst}, except the `test` is inverted. Note the - * argument ordering differs from `until`. - * - * @name doUntil - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.doWhilst]{@link module:ControlFlow.doWhilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` fails. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has passed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - */ -function doUntil(iteratee, test, callback) { - (0, _doWhilst2.default)(iteratee, function () { - return !test.apply(this, arguments); - }, callback); -} -module.exports = exports['default']; -},{"./doWhilst":19}],19:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doWhilst; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The post-check version of [`whilst`]{@link module:ControlFlow.whilst}. To reflect the difference in - * the order of operations, the arguments `test` and `iteratee` are switched. - * - * `doWhilst` is to `whilst` as `do while` is to `while` in plain JavaScript. - * - * @name doWhilst - * @static - * @memberOf module:ControlFlow - * @method - * @see [async.whilst]{@link module:ControlFlow.whilst} - * @category Control Flow - * @param {AsyncFunction} iteratee - A function which is called each time `test` - * passes. Invoked with (callback). - * @param {Function} test - synchronous truth test to perform after each - * execution of `iteratee`. Invoked with any non-error callback results of - * `iteratee`. - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. - * `callback` will be passed an error and any arguments passed to the final - * `iteratee`'s callback. Invoked with (err, [results]); - */ -function doWhilst(iteratee, test, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - var args = (0, _slice2.default)(arguments, 1); - if (test.apply(this, args)) return _iteratee(next); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} -module.exports = exports['default']; -},{"./internal/onlyOnce":40,"./internal/slice":45,"./internal/wrapAsync":47,"lodash/noop":490}],20:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Applies the function `iteratee` to each item in `coll`, in parallel. - * The `iteratee` is called with an item from the list, and a callback for when - * it has finished. If the `iteratee` passes an error to its `callback`, the - * main `callback` (for the `each` function) is immediately called with the - * error. - * - * Note, that since this function applies `iteratee` to each item in parallel, - * there is no guarantee that the iteratee functions will complete in order. - * - * @name each - * @static - * @memberOf module:Collections - * @method - * @alias forEach - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to - * each item in `coll`. Invoked with (item, callback). - * The array index is not passed to the iteratee. - * If you need the index, use `eachOf`. - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * // assuming openFiles is an array of file names and saveFile is a function - * // to save the modified contents of that file: - * - * async.each(openFiles, saveFile, function(err){ - * // if any of the saves produced an error, err would equal that error - * }); - * - * // assuming openFiles is an array of file names - * async.each(openFiles, function(file, callback) { - * - * // Perform operation on file here. - * console.log('Processing file ' + file); - * - * if( file.length > 32 ) { - * console.log('This file name is too long'); - * callback('File name too long'); - * } else { - * // Do work to process file here - * console.log('File processed'); - * callback(); - * } - * }, function(err) { - * // if any of the file processing produced an error, err would equal that error - * if( err ) { - * // One of the iterations produced an error. - * // All processing will now stop. - * console.log('A file failed to process'); - * } else { - * console.log('All files have been processed successfully'); - * } - * }); - */ -function eachLimit(coll, iteratee, callback) { - (0, _eachOf2.default)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default']; -},{"./eachOf":22,"./internal/withoutIndex":46,"./internal/wrapAsync":47}],21:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachLimit; - -var _eachOfLimit = require('./internal/eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _withoutIndex = require('./internal/withoutIndex'); - -var _withoutIndex2 = _interopRequireDefault(_withoutIndex); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs a maximum of `limit` async operations at a time. - * - * @name eachLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfLimit`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit2.default)(limit)(coll, (0, _withoutIndex2.default)((0, _wrapAsync2.default)(iteratee)), callback); -} -module.exports = exports['default']; -},{"./internal/eachOfLimit":32,"./internal/withoutIndex":46,"./internal/wrapAsync":47}],22:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll, iteratee, callback) { - var eachOfImplementation = (0, _isArrayLike2.default)(coll) ? eachOfArrayLike : eachOfGeneric; - eachOfImplementation(coll, (0, _wrapAsync2.default)(iteratee), callback); -}; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _breakLoop = require('./internal/breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -// eachOf implementation optimized for array-likes -function eachOfArrayLike(coll, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - var index = 0, - completed = 0, - length = coll.length; - if (length === 0) { - callback(null); - } - - function iteratorCallback(err, value) { - if (err) { - callback(err); - } else if (++completed === length || value === _breakLoop2.default) { - callback(null); - } - } - - for (; index < length; index++) { - iteratee(coll[index], index, (0, _onlyOnce2.default)(iteratorCallback)); - } -} - -// a generic version of eachOf which can handle array, object, and iterator cases. -var eachOfGeneric = (0, _doLimit2.default)(_eachOfLimit2.default, Infinity); - -/** - * Like [`each`]{@link module:Collections.each}, except that it passes the key (or index) as the second argument - * to the iteratee. - * - * @name eachOf - * @static - * @memberOf module:Collections - * @method - * @alias forEachOf - * @category Collection - * @see [async.each]{@link module:Collections.each} - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - A function to apply to each - * item in `coll`. - * The `key` is the item's key, or index in the case of an array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - * @example - * - * var obj = {dev: "/dev.json", test: "/test.json", prod: "/prod.json"}; - * var configs = {}; - * - * async.forEachOf(obj, function (value, key, callback) { - * fs.readFile(__dirname + value, "utf8", function (err, data) { - * if (err) return callback(err); - * try { - * configs[key] = JSON.parse(data); - * } catch (e) { - * return callback(e); - * } - * callback(); - * }); - * }, function (err) { - * if (err) console.error(err.message); - * // configs is now a map of JSON data - * doSomethingWith(configs); - * }); - */ -module.exports = exports['default']; -},{"./eachOfLimit":23,"./internal/breakLoop":28,"./internal/doLimit":30,"./internal/once":39,"./internal/onlyOnce":40,"./internal/wrapAsync":47,"lodash/isArrayLike":480,"lodash/noop":490}],23:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = eachOfLimit; - -var _eachOfLimit2 = require('./internal/eachOfLimit'); - -var _eachOfLimit3 = _interopRequireDefault(_eachOfLimit2); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs a maximum of `limit` async operations at a - * time. - * - * @name eachOfLimit - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfLimit - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {number} limit - The maximum number of async operations at a time. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. The `key` is the item's key, or index in the case of an - * array. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -function eachOfLimit(coll, limit, iteratee, callback) { - (0, _eachOfLimit3.default)(limit)(coll, (0, _wrapAsync2.default)(iteratee), callback); -} -module.exports = exports['default']; -},{"./internal/eachOfLimit":32,"./internal/wrapAsync":47}],24:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachOfLimit = require('./eachOfLimit'); - -var _eachOfLimit2 = _interopRequireDefault(_eachOfLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`eachOf`]{@link module:Collections.eachOf} but runs only a single async operation at a time. - * - * @name eachOfSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.eachOf]{@link module:Collections.eachOf} - * @alias forEachOfSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * Invoked with (item, key, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachOfLimit2.default, 1); -module.exports = exports['default']; -},{"./eachOfLimit":23,"./internal/doLimit":30}],25:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _eachLimit = require('./eachLimit'); - -var _eachLimit2 = _interopRequireDefault(_eachLimit); - -var _doLimit = require('./internal/doLimit'); - -var _doLimit2 = _interopRequireDefault(_doLimit); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The same as [`each`]{@link module:Collections.each} but runs only a single async operation at a time. - * - * @name eachSeries - * @static - * @memberOf module:Collections - * @method - * @see [async.each]{@link module:Collections.each} - * @alias forEachSeries - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each - * item in `coll`. - * The array index is not passed to the iteratee. - * If you need the index, use `eachOfSeries`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all - * `iteratee` functions have finished, or an error occurs. Invoked with (err). - */ -exports.default = (0, _doLimit2.default)(_eachLimit2.default, 1); -module.exports = exports['default']; -},{"./eachLimit":21,"./internal/doLimit":30}],26:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _notId = require('./internal/notId'); - -var _notId2 = _interopRequireDefault(_notId); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if every element in `coll` satisfies an async test. If any - * iteratee call returns `false`, the main `callback` is immediately called. - * - * @name every - * @static - * @memberOf module:Collections - * @method - * @alias all - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collection in parallel. - * The iteratee must complete with a boolean result value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Result will be either `true` or `false` - * depending on the values of the async tests. Invoked with (err, result). - * @example - * - * async.every(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then every file exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(_notId2.default, _notId2.default)); -module.exports = exports['default']; -},{"./internal/createTester":29,"./internal/doParallel":31,"./internal/notId":38}],27:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = DLL; -// Simple doubly linked list (https://en.wikipedia.org/wiki/Doubly_linked_list) implementation -// used for queues. This implementation assumes that the node provided by the user can be modified -// to adjust the next and last properties. We implement only the minimal functionality -// for queue support. -function DLL() { - this.head = this.tail = null; - this.length = 0; -} - -function setInitial(dll, node) { - dll.length = 1; - dll.head = dll.tail = node; -} - -DLL.prototype.removeLink = function (node) { - if (node.prev) node.prev.next = node.next;else this.head = node.next; - if (node.next) node.next.prev = node.prev;else this.tail = node.prev; - - node.prev = node.next = null; - this.length -= 1; - return node; -}; - -DLL.prototype.empty = function () { - while (this.head) this.shift(); - return this; -}; - -DLL.prototype.insertAfter = function (node, newNode) { - newNode.prev = node; - newNode.next = node.next; - if (node.next) node.next.prev = newNode;else this.tail = newNode; - node.next = newNode; - this.length += 1; -}; - -DLL.prototype.insertBefore = function (node, newNode) { - newNode.prev = node.prev; - newNode.next = node; - if (node.prev) node.prev.next = newNode;else this.head = newNode; - node.prev = newNode; - this.length += 1; -}; - -DLL.prototype.unshift = function (node) { - if (this.head) this.insertBefore(this.head, node);else setInitial(this, node); -}; - -DLL.prototype.push = function (node) { - if (this.tail) this.insertAfter(this.tail, node);else setInitial(this, node); -}; - -DLL.prototype.shift = function () { - return this.head && this.removeLink(this.head); -}; - -DLL.prototype.pop = function () { - return this.tail && this.removeLink(this.tail); -}; - -DLL.prototype.toArray = function () { - var arr = Array(this.length); - var curr = this.head; - for (var idx = 0; idx < this.length; idx++) { - arr[idx] = curr.data; - curr = curr.next; - } - return arr; -}; - -DLL.prototype.remove = function (testFn) { - var curr = this.head; - while (!!curr) { - var next = curr.next; - if (testFn(curr)) { - this.removeLink(curr); - } - curr = next; - } - return this; -}; -module.exports = exports["default"]; -},{}],28:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -// A temporary value used to identify if the loop should be broken. -// See #1064, #1293 -exports.default = {}; -module.exports = exports["default"]; -},{}],29:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _createTester; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _breakLoop = require('./breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _createTester(check, getResult) { - return function (eachfn, arr, iteratee, cb) { - cb = cb || _noop2.default; - var testPassed = false; - var testResult; - eachfn(arr, function (value, _, callback) { - iteratee(value, function (err, result) { - if (err) { - callback(err); - } else if (check(result) && !testResult) { - testPassed = true; - testResult = getResult(true, value); - callback(null, _breakLoop2.default); - } else { - callback(); - } - }); - }, function (err) { - if (err) { - cb(err); - } else { - cb(null, testPassed ? testResult : getResult(false)); - } - }); - }; -} -module.exports = exports['default']; -},{"./breakLoop":28,"lodash/noop":490}],30:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doLimit; -function doLimit(fn, limit) { - return function (iterable, iteratee, callback) { - return fn(iterable, limit, iteratee, callback); - }; -} -module.exports = exports["default"]; -},{}],31:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = doParallel; - -var _eachOf = require('../eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function doParallel(fn) { - return function (obj, iteratee, callback) { - return fn(_eachOf2.default, obj, (0, _wrapAsync2.default)(iteratee), callback); - }; -} -module.exports = exports['default']; -},{"../eachOf":22,"./wrapAsync":47}],32:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _eachOfLimit; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./once'); - -var _once2 = _interopRequireDefault(_once); - -var _iterator = require('./iterator'); - -var _iterator2 = _interopRequireDefault(_iterator); - -var _onlyOnce = require('./onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _breakLoop = require('./breakLoop'); - -var _breakLoop2 = _interopRequireDefault(_breakLoop); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _eachOfLimit(limit) { - return function (obj, iteratee, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (limit <= 0 || !obj) { - return callback(null); - } - var nextElem = (0, _iterator2.default)(obj); - var done = false; - var running = 0; - - function iterateeCallback(err, value) { - running -= 1; - if (err) { - done = true; - callback(err); - } else if (value === _breakLoop2.default || done && running <= 0) { - done = true; - return callback(null); - } else { - replenish(); - } - } - - function replenish() { - while (running < limit && !done) { - var elem = nextElem(); - if (elem === null) { - done = true; - if (running <= 0) { - callback(null); - } - return; - } - running += 1; - iteratee(elem.value, elem.key, (0, _onlyOnce2.default)(iterateeCallback)); - } - } - - replenish(); - }; -} -module.exports = exports['default']; -},{"./breakLoop":28,"./iterator":36,"./once":39,"./onlyOnce":40,"lodash/noop":490}],33:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _filter; - -var _arrayMap = require('lodash/_arrayMap'); - -var _arrayMap2 = _interopRequireDefault(_arrayMap); - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _baseProperty = require('lodash/_baseProperty'); - -var _baseProperty2 = _interopRequireDefault(_baseProperty); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function filterArray(eachfn, arr, iteratee, callback) { - var truthValues = new Array(arr.length); - eachfn(arr, function (x, index, callback) { - iteratee(x, function (err, v) { - truthValues[index] = !!v; - callback(err); - }); - }, function (err) { - if (err) return callback(err); - var results = []; - for (var i = 0; i < arr.length; i++) { - if (truthValues[i]) results.push(arr[i]); - } - callback(null, results); - }); -} - -function filterGeneric(eachfn, coll, iteratee, callback) { - var results = []; - eachfn(coll, function (x, index, callback) { - iteratee(x, function (err, v) { - if (err) { - callback(err); - } else { - if (v) { - results.push({ index: index, value: x }); - } - callback(); - } - }); - }, function (err) { - if (err) { - callback(err); - } else { - callback(null, (0, _arrayMap2.default)(results.sort(function (a, b) { - return a.index - b.index; - }), (0, _baseProperty2.default)('value'))); - } - }); -} - -function _filter(eachfn, coll, iteratee, callback) { - var filter = (0, _isArrayLike2.default)(coll) ? filterArray : filterGeneric; - filter(eachfn, coll, (0, _wrapAsync2.default)(iteratee), callback || _noop2.default); -} -module.exports = exports['default']; -},{"./wrapAsync":47,"lodash/_arrayMap":454,"lodash/_baseProperty":462,"lodash/isArrayLike":480,"lodash/noop":490}],34:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (coll) { - return iteratorSymbol && coll[iteratorSymbol] && coll[iteratorSymbol](); -}; - -var iteratorSymbol = typeof Symbol === 'function' && Symbol.iterator; - -module.exports = exports['default']; -},{}],35:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (fn) { - return function () /*...args, callback*/{ - var args = (0, _slice2.default)(arguments); - var callback = args.pop(); - fn.call(this, args, callback); - }; -}; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; -},{"./slice":45}],36:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = iterator; - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _getIterator = require('./getIterator'); - -var _getIterator2 = _interopRequireDefault(_getIterator); - -var _keys = require('lodash/keys'); - -var _keys2 = _interopRequireDefault(_keys); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function createArrayIterator(coll) { - var i = -1; - var len = coll.length; - return function next() { - return ++i < len ? { value: coll[i], key: i } : null; - }; -} - -function createES2015Iterator(iterator) { - var i = -1; - return function next() { - var item = iterator.next(); - if (item.done) return null; - i++; - return { value: item.value, key: i }; - }; -} - -function createObjectIterator(obj) { - var okeys = (0, _keys2.default)(obj); - var i = -1; - var len = okeys.length; - return function next() { - var key = okeys[++i]; - return i < len ? { value: obj[key], key: key } : null; - }; -} - -function iterator(coll) { - if ((0, _isArrayLike2.default)(coll)) { - return createArrayIterator(coll); - } - - var iterator = (0, _getIterator2.default)(coll); - return iterator ? createES2015Iterator(iterator) : createObjectIterator(coll); -} -module.exports = exports['default']; -},{"./getIterator":34,"lodash/isArrayLike":480,"lodash/keys":489}],37:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _asyncMap; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _asyncMap(eachfn, arr, iteratee, callback) { - callback = callback || _noop2.default; - arr = arr || []; - var results = []; - var counter = 0; - var _iteratee = (0, _wrapAsync2.default)(iteratee); - - eachfn(arr, function (value, _, callback) { - var index = counter++; - _iteratee(value, function (err, v) { - results[index] = v; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default']; -},{"./wrapAsync":47,"lodash/noop":490}],38:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = notId; -function notId(v) { - return !v; -} -module.exports = exports["default"]; -},{}],39:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = once; -function once(fn) { - return function () { - if (fn === null) return; - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; -},{}],40:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = onlyOnce; -function onlyOnce(fn) { - return function () { - if (fn === null) throw new Error("Callback was already called."); - var callFn = fn; - fn = null; - callFn.apply(this, arguments); - }; -} -module.exports = exports["default"]; -},{}],41:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _parallel; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _isArrayLike = require('lodash/isArrayLike'); - -var _isArrayLike2 = _interopRequireDefault(_isArrayLike); - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function _parallel(eachfn, tasks, callback) { - callback = callback || _noop2.default; - var results = (0, _isArrayLike2.default)(tasks) ? [] : {}; - - eachfn(tasks, function (task, key, callback) { - (0, _wrapAsync2.default)(task)(function (err, result) { - if (arguments.length > 2) { - result = (0, _slice2.default)(arguments, 1); - } - results[key] = result; - callback(err); - }); - }, function (err) { - callback(err, results); - }); -} -module.exports = exports['default']; -},{"./slice":45,"./wrapAsync":47,"lodash/isArrayLike":480,"lodash/noop":490}],42:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = queue; - -var _baseIndexOf = require('lodash/_baseIndexOf'); - -var _baseIndexOf2 = _interopRequireDefault(_baseIndexOf); - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _onlyOnce = require('./onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _setImmediate = require('./setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -var _DoublyLinkedList = require('./DoublyLinkedList'); - -var _DoublyLinkedList2 = _interopRequireDefault(_DoublyLinkedList); - -var _wrapAsync = require('./wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function queue(worker, concurrency, payload) { - if (concurrency == null) { - concurrency = 1; - } else if (concurrency === 0) { - throw new Error('Concurrency must not be zero'); - } - - var _worker = (0, _wrapAsync2.default)(worker); - var numRunning = 0; - var workersList = []; - - function _insert(data, insertAtFront, callback) { - if (callback != null && typeof callback !== 'function') { - throw new Error('task callback must be a function'); - } - q.started = true; - if (!(0, _isArray2.default)(data)) { - data = [data]; - } - if (data.length === 0 && q.idle()) { - // call drain immediately if there are no tasks - return (0, _setImmediate2.default)(function () { - q.drain(); - }); - } - - for (var i = 0, l = data.length; i < l; i++) { - var item = { - data: data[i], - callback: callback || _noop2.default - }; - - if (insertAtFront) { - q._tasks.unshift(item); - } else { - q._tasks.push(item); - } - } - (0, _setImmediate2.default)(q.process); - } - - function _next(tasks) { - return function (err) { - numRunning -= 1; - - for (var i = 0, l = tasks.length; i < l; i++) { - var task = tasks[i]; - - var index = (0, _baseIndexOf2.default)(workersList, task, 0); - if (index >= 0) { - workersList.splice(index, 1); - } - - task.callback.apply(task, arguments); - - if (err != null) { - q.error(err, task.data); - } - } - - if (numRunning <= q.concurrency - q.buffer) { - q.unsaturated(); - } - - if (q.idle()) { - q.drain(); - } - q.process(); - }; - } - - var isProcessing = false; - var q = { - _tasks: new _DoublyLinkedList2.default(), - concurrency: concurrency, - payload: payload, - saturated: _noop2.default, - unsaturated: _noop2.default, - buffer: concurrency / 4, - empty: _noop2.default, - drain: _noop2.default, - error: _noop2.default, - started: false, - paused: false, - push: function (data, callback) { - _insert(data, false, callback); - }, - kill: function () { - q.drain = _noop2.default; - q._tasks.empty(); - }, - unshift: function (data, callback) { - _insert(data, true, callback); - }, - remove: function (testFn) { - q._tasks.remove(testFn); - }, - process: function () { - // Avoid trying to start too many processing operations. This can occur - // when callbacks resolve synchronously (#1267). - if (isProcessing) { - return; - } - isProcessing = true; - while (!q.paused && numRunning < q.concurrency && q._tasks.length) { - var tasks = [], - data = []; - var l = q._tasks.length; - if (q.payload) l = Math.min(l, q.payload); - for (var i = 0; i < l; i++) { - var node = q._tasks.shift(); - tasks.push(node); - workersList.push(node); - data.push(node.data); - } - - numRunning += 1; - - if (q._tasks.length === 0) { - q.empty(); - } - - if (numRunning === q.concurrency) { - q.saturated(); - } - - var cb = (0, _onlyOnce2.default)(_next(tasks)); - _worker(data, cb); - } - isProcessing = false; - }, - length: function () { - return q._tasks.length; - }, - running: function () { - return numRunning; - }, - workersList: function () { - return workersList; - }, - idle: function () { - return q._tasks.length + numRunning === 0; - }, - pause: function () { - q.paused = true; - }, - resume: function () { - if (q.paused === false) { - return; - } - q.paused = false; - (0, _setImmediate2.default)(q.process); - } - }; - return q; -} -module.exports = exports['default']; -},{"./DoublyLinkedList":27,"./onlyOnce":40,"./setImmediate":44,"./wrapAsync":47,"lodash/_baseIndexOf":457,"lodash/isArray":479,"lodash/noop":490}],43:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = reject; - -var _filter = require('./filter'); - -var _filter2 = _interopRequireDefault(_filter); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -function reject(eachfn, arr, iteratee, callback) { - (0, _filter2.default)(eachfn, arr, function (value, cb) { - iteratee(value, function (err, v) { - cb(err, !v); - }); - }, callback); -} -module.exports = exports['default']; -},{"./filter":33}],44:[function(require,module,exports){ -(function (process){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.hasNextTick = exports.hasSetImmediate = undefined; -exports.fallback = fallback; -exports.wrap = wrap; - -var _slice = require('./slice'); - -var _slice2 = _interopRequireDefault(_slice); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var hasSetImmediate = exports.hasSetImmediate = typeof setImmediate === 'function' && setImmediate; -var hasNextTick = exports.hasNextTick = typeof process === 'object' && typeof process.nextTick === 'function'; - -function fallback(fn) { - setTimeout(fn, 0); -} - -function wrap(defer) { - return function (fn /*, ...args*/) { - var args = (0, _slice2.default)(arguments, 1); - defer(function () { - fn.apply(null, args); - }); - }; -} - -var _defer; - -if (hasSetImmediate) { - _defer = setImmediate; -} else if (hasNextTick) { - _defer = process.nextTick; -} else { - _defer = fallback; -} - -exports.default = wrap(_defer); -}).call(this,require('_process')) -},{"./slice":45,"_process":1009}],45:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = slice; -function slice(arrayLike, start) { - start = start | 0; - var newLen = Math.max(arrayLike.length - start, 0); - var newArr = Array(newLen); - for (var idx = 0; idx < newLen; idx++) { - newArr[idx] = arrayLike[start + idx]; - } - return newArr; -} -module.exports = exports["default"]; -},{}],46:[function(require,module,exports){ -"use strict"; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = _withoutIndex; -function _withoutIndex(iteratee) { - return function (value, index, callback) { - return iteratee(value, callback); - }; -} -module.exports = exports["default"]; -},{}],47:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.isAsync = undefined; - -var _asyncify = require('../asyncify'); - -var _asyncify2 = _interopRequireDefault(_asyncify); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -var supportsSymbol = typeof Symbol === 'function'; - -function isAsync(fn) { - return supportsSymbol && fn[Symbol.toStringTag] === 'AsyncFunction'; -} - -function wrapAsync(asyncFn) { - return isAsync(asyncFn) ? (0, _asyncify2.default)(asyncFn) : asyncFn; -} - -exports.default = wrapAsync; -exports.isAsync = isAsync; -},{"../asyncify":16}],48:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _map = require('./internal/map'); - -var _map2 = _interopRequireDefault(_map); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Produces a new collection of values by mapping each value in `coll` through - * the `iteratee` function. The `iteratee` is called with an item from `coll` - * and a callback for when it has finished processing. Each of these callback - * takes 2 arguments: an `error`, and the transformed item from `coll`. If - * `iteratee` passes an error to its callback, the main `callback` (for the - * `map` function) is immediately called with the error. - * - * Note, that since this function applies the `iteratee` to each item in - * parallel, there is no guarantee that the `iteratee` functions will complete - * in order. However, the results array will be in the same order as the - * original `coll`. - * - * If `map` is passed an Object, the results will be an Array. The results - * will roughly be in the order of the original Objects' keys (but this can - * vary across JavaScript engines). - * - * @name map - * @static - * @memberOf module:Collections - * @method - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async function to apply to each item in - * `coll`. - * The iteratee should complete with the transformed item. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called when all `iteratee` - * functions have finished, or an error occurs. Results is an Array of the - * transformed items from the `coll`. Invoked with (err, results). - * @example - * - * async.map(['file1','file2','file3'], fs.stat, function(err, results) { - * // results is now an array of stats for each file - * }); - */ -exports.default = (0, _doParallel2.default)(_map2.default); -module.exports = exports['default']; -},{"./internal/doParallel":31,"./internal/map":37}],49:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = parallelLimit; - -var _eachOf = require('./eachOf'); - -var _eachOf2 = _interopRequireDefault(_eachOf); - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Run the `tasks` collection of functions in parallel, without waiting until - * the previous function has completed. If any of the functions pass an error to - * its callback, the main `callback` is immediately called with the value of the - * error. Once the `tasks` have completed, the results are passed to the final - * `callback` as an array. - * - * **Note:** `parallel` is about kicking-off I/O tasks in parallel, not about - * parallel execution of code. If your tasks do not use any timers or perform - * any I/O, they will actually be executed in series. Any synchronous setup - * sections for each task will happen one after the other. JavaScript remains - * single-threaded. - * - * **Hint:** Use [`reflect`]{@link module:Utils.reflect} to continue the - * execution of other tasks when a task fails. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.parallel}. - * - * @name parallel - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection of - * [async functions]{@link AsyncFunction} to run. - * Each async function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed successfully. This function gets a results array - * (or object) containing all the result arguments passed to the task callbacks. - * Invoked with (err, results). - * - * @example - * async.parallel([ - * function(callback) { - * setTimeout(function() { - * callback(null, 'one'); - * }, 200); - * }, - * function(callback) { - * setTimeout(function() { - * callback(null, 'two'); - * }, 100); - * } - * ], - * // optional callback - * function(err, results) { - * // the results array will equal ['one','two'] even though - * // the second function had a shorter timeout. - * }); - * - * // an example using an object instead of an array - * async.parallel({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback) { - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equals to: {one: 1, two: 2} - * }); - */ -function parallelLimit(tasks, callback) { - (0, _parallel2.default)(_eachOf2.default, tasks, callback); -} -module.exports = exports['default']; -},{"./eachOf":22,"./internal/parallel":41}],50:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (worker, concurrency) { - var _worker = (0, _wrapAsync2.default)(worker); - return (0, _queue2.default)(function (items, cb) { - _worker(items[0], cb); - }, concurrency, 1); -}; - -var _queue = require('./internal/queue'); - -var _queue2 = _interopRequireDefault(_queue); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * A queue of tasks for the worker function to complete. - * @typedef {Object} QueueObject - * @memberOf module:ControlFlow - * @property {Function} length - a function returning the number of items - * waiting to be processed. Invoke with `queue.length()`. - * @property {boolean} started - a boolean indicating whether or not any - * items have been pushed and processed by the queue. - * @property {Function} running - a function returning the number of items - * currently being processed. Invoke with `queue.running()`. - * @property {Function} workersList - a function returning the array of items - * currently being processed. Invoke with `queue.workersList()`. - * @property {Function} idle - a function returning false if there are items - * waiting or being processed, or true if not. Invoke with `queue.idle()`. - * @property {number} concurrency - an integer for determining how many `worker` - * functions should be run in parallel. This property can be changed after a - * `queue` is created to alter the concurrency on-the-fly. - * @property {Function} push - add a new task to the `queue`. Calls `callback` - * once the `worker` has finished processing the task. Instead of a single task, - * a `tasks` array can be submitted. The respective callback is used for every - * task in the list. Invoke with `queue.push(task, [callback])`, - * @property {Function} unshift - add a new task to the front of the `queue`. - * Invoke with `queue.unshift(task, [callback])`. - * @property {Function} remove - remove items from the queue that match a test - * function. The test function will be passed an object with a `data` property, - * and a `priority` property, if this is a - * [priorityQueue]{@link module:ControlFlow.priorityQueue} object. - * Invoked with `queue.remove(testFn)`, where `testFn` is of the form - * `function ({data, priority}) {}` and returns a Boolean. - * @property {Function} saturated - a callback that is called when the number of - * running workers hits the `concurrency` limit, and further tasks will be - * queued. - * @property {Function} unsaturated - a callback that is called when the number - * of running workers is less than the `concurrency` & `buffer` limits, and - * further tasks will not be queued. - * @property {number} buffer - A minimum threshold buffer in order to say that - * the `queue` is `unsaturated`. - * @property {Function} empty - a callback that is called when the last item - * from the `queue` is given to a `worker`. - * @property {Function} drain - a callback that is called when the last item - * from the `queue` has returned from the `worker`. - * @property {Function} error - a callback that is called when a task errors. - * Has the signature `function(error, task)`. - * @property {boolean} paused - a boolean for determining whether the queue is - * in a paused state. - * @property {Function} pause - a function that pauses the processing of tasks - * until `resume()` is called. Invoke with `queue.pause()`. - * @property {Function} resume - a function that resumes the processing of - * queued tasks when the queue is paused. Invoke with `queue.resume()`. - * @property {Function} kill - a function that removes the `drain` callback and - * empties remaining tasks from the queue forcing it to go idle. No more tasks - * should be pushed to the queue after calling this function. Invoke with `queue.kill()`. - */ - -/** - * Creates a `queue` object with the specified `concurrency`. Tasks added to the - * `queue` are processed in parallel (up to the `concurrency` limit). If all - * `worker`s are in progress, the task is queued until one becomes available. - * Once a `worker` completes a `task`, that `task`'s callback is called. - * - * @name queue - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {AsyncFunction} worker - An async function for processing a queued task. - * If you want to handle errors from an individual task, pass a callback to - * `q.push()`. Invoked with (task, callback). - * @param {number} [concurrency=1] - An `integer` for determining how many - * `worker` functions should be run in parallel. If omitted, the concurrency - * defaults to `1`. If the concurrency is `0`, an error is thrown. - * @returns {module:ControlFlow.QueueObject} A queue object to manage the tasks. Callbacks can - * attached as certain properties to listen for specific events during the - * lifecycle of the queue. - * @example - * - * // create a queue object with concurrency 2 - * var q = async.queue(function(task, callback) { - * console.log('hello ' + task.name); - * callback(); - * }, 2); - * - * // assign a callback - * q.drain = function() { - * console.log('all items have been processed'); - * }; - * - * // add some items to the queue - * q.push({name: 'foo'}, function(err) { - * console.log('finished processing foo'); - * }); - * q.push({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - * - * // add some items to the queue (batch-wise) - * q.push([{name: 'baz'},{name: 'bay'},{name: 'bax'}], function(err) { - * console.log('finished processing item'); - * }); - * - * // add some items to the front of the queue - * q.unshift({name: 'bar'}, function (err) { - * console.log('finished processing bar'); - * }); - */ -},{"./internal/queue":42,"./internal/wrapAsync":47}],51:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _reject = require('./internal/reject'); - -var _reject2 = _interopRequireDefault(_reject); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * The opposite of [`filter`]{@link module:Collections.filter}. Removes values that pass an `async` truth test. - * - * @name reject - * @static - * @memberOf module:Collections - * @method - * @see [async.filter]{@link module:Collections.filter} - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {Function} iteratee - An async truth test to apply to each item in - * `coll`. - * The should complete with a boolean value as its `result`. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called after all the - * `iteratee` functions have finished. Invoked with (err, results). - * @example - * - * async.reject(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, results) { - * // results now equals an array of missing files - * createFiles(results); - * }); - */ -exports.default = (0, _doParallel2.default)(_reject2.default); -module.exports = exports['default']; -},{"./internal/doParallel":31,"./internal/reject":43}],52:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = series; - -var _parallel = require('./internal/parallel'); - -var _parallel2 = _interopRequireDefault(_parallel); - -var _eachOfSeries = require('./eachOfSeries'); - -var _eachOfSeries2 = _interopRequireDefault(_eachOfSeries); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Run the functions in the `tasks` collection in series, each one running once - * the previous function has completed. If any functions in the series pass an - * error to its callback, no more functions are run, and `callback` is - * immediately called with the value of the error. Otherwise, `callback` - * receives an array of results when `tasks` have completed. - * - * It is also possible to use an object instead of an array. Each property will - * be run as a function, and the results will be passed to the final `callback` - * as an object instead of an array. This can be a more readable way of handling - * results from {@link async.series}. - * - * **Note** that while many implementations preserve the order of object - * properties, the [ECMAScript Language Specification](http://www.ecma-international.org/ecma-262/5.1/#sec-8.6) - * explicitly states that - * - * > The mechanics and order of enumerating the properties is not specified. - * - * So if you rely on the order in which your series of functions are executed, - * and want this to work on all platforms, consider using an array. - * - * @name series - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array|Iterable|Object} tasks - A collection containing - * [async functions]{@link AsyncFunction} to run in series. - * Each function can complete with any number of optional `result` values. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This function gets a results array (or object) - * containing all the result arguments passed to the `task` callbacks. Invoked - * with (err, result). - * @example - * async.series([ - * function(callback) { - * // do some stuff ... - * callback(null, 'one'); - * }, - * function(callback) { - * // do some more stuff ... - * callback(null, 'two'); - * } - * ], - * // optional callback - * function(err, results) { - * // results is now equal to ['one', 'two'] - * }); - * - * async.series({ - * one: function(callback) { - * setTimeout(function() { - * callback(null, 1); - * }, 200); - * }, - * two: function(callback){ - * setTimeout(function() { - * callback(null, 2); - * }, 100); - * } - * }, function(err, results) { - * // results is now equal to: {one: 1, two: 2} - * }); - */ -function series(tasks, callback) { - (0, _parallel2.default)(_eachOfSeries2.default, tasks, callback); -} -module.exports = exports['default']; -},{"./eachOfSeries":24,"./internal/parallel":41}],53:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _setImmediate = require('./internal/setImmediate'); - -var _setImmediate2 = _interopRequireDefault(_setImmediate); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Calls `callback` on a later loop around the event loop. In Node.js this just - * calls `setImmediate`. In the browser it will use `setImmediate` if - * available, otherwise `setTimeout(callback, 0)`, which means other higher - * priority events may precede the execution of `callback`. - * - * This is used internally for browser-compatibility purposes. - * - * @name setImmediate - * @static - * @memberOf module:Utils - * @method - * @alias nextTick - * @category Util - * @param {Function} callback - The function to call on a later loop around - * the event loop. Invoked with (args...). - * @param {...*} args... - any number of additional arguments to pass to the - * callback on the next tick. - * @example - * - * var call_order = []; - * async.nextTick(function() { - * call_order.push('two'); - * // call_order now equals ['one','two'] - * }); - * call_order.push('one'); - * - * async.setImmediate(function (a, b, c) { - * // a, b, and c equal 1, 2, and 3 - * }, 1, 2, 3); - */ -exports.default = _setImmediate2.default; -module.exports = exports['default']; -},{"./internal/setImmediate":44}],54:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -var _createTester = require('./internal/createTester'); - -var _createTester2 = _interopRequireDefault(_createTester); - -var _doParallel = require('./internal/doParallel'); - -var _doParallel2 = _interopRequireDefault(_doParallel); - -var _identity = require('lodash/identity'); - -var _identity2 = _interopRequireDefault(_identity); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Returns `true` if at least one element in the `coll` satisfies an async test. - * If any iteratee call returns `true`, the main `callback` is immediately - * called. - * - * @name some - * @static - * @memberOf module:Collections - * @method - * @alias any - * @category Collection - * @param {Array|Iterable|Object} coll - A collection to iterate over. - * @param {AsyncFunction} iteratee - An async truth test to apply to each item - * in the collections in parallel. - * The iteratee should complete with a boolean `result` value. - * Invoked with (item, callback). - * @param {Function} [callback] - A callback which is called as soon as any - * iteratee returns `true`, or after all the iteratee functions have finished. - * Result will be either `true` or `false` depending on the values of the async - * tests. Invoked with (err, result). - * @example - * - * async.some(['file1','file2','file3'], function(filePath, callback) { - * fs.access(filePath, function(err) { - * callback(null, !err) - * }); - * }, function(err, result) { - * // if result is true then at least one of the files exists - * }); - */ -exports.default = (0, _doParallel2.default)((0, _createTester2.default)(Boolean, _identity2.default)); -module.exports = exports['default']; -},{"./internal/createTester":29,"./internal/doParallel":31,"lodash/identity":476}],55:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = timeout; - -var _initialParams = require('./internal/initialParams'); - -var _initialParams2 = _interopRequireDefault(_initialParams); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Sets a time limit on an asynchronous function. If the function does not call - * its callback within the specified milliseconds, it will be called with a - * timeout error. The code property for the error object will be `'ETIMEDOUT'`. - * - * @name timeout - * @static - * @memberOf module:Utils - * @method - * @category Util - * @param {AsyncFunction} asyncFn - The async function to limit in time. - * @param {number} milliseconds - The specified time limit. - * @param {*} [info] - Any variable you want attached (`string`, `object`, etc) - * to timeout Error for more information.. - * @returns {AsyncFunction} Returns a wrapped function that can be used with any - * of the control flow functions. - * Invoke this function with the same parameters as you would `asyncFunc`. - * @example - * - * function myFunction(foo, callback) { - * doAsyncTask(foo, function(err, data) { - * // handle errors - * if (err) return callback(err); - * - * // do some stuff ... - * - * // return processed data - * return callback(null, data); - * }); - * } - * - * var wrapped = async.timeout(myFunction, 1000); - * - * // call `wrapped` as you would `myFunction` - * wrapped({ bar: 'bar' }, function(err, data) { - * // if `myFunction` takes < 1000 ms to execute, `err` - * // and `data` will have their expected values - * - * // else `err` will be an Error with the code 'ETIMEDOUT' - * }); - */ -function timeout(asyncFn, milliseconds, info) { - var fn = (0, _wrapAsync2.default)(asyncFn); - - return (0, _initialParams2.default)(function (args, callback) { - var timedOut = false; - var timer; - - function timeoutCallback() { - var name = asyncFn.name || 'anonymous'; - var error = new Error('Callback function "' + name + '" timed out.'); - error.code = 'ETIMEDOUT'; - if (info) { - error.info = info; - } - timedOut = true; - callback(error); - } - - args.push(function () { - if (!timedOut) { - callback.apply(null, arguments); - clearTimeout(timer); - } - }); - - // setup timer and call original function - timer = setTimeout(timeoutCallback, milliseconds); - fn.apply(null, args); - }); -} -module.exports = exports['default']; -},{"./internal/initialParams":35,"./internal/wrapAsync":47}],56:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); - -exports.default = function (tasks, callback) { - callback = (0, _once2.default)(callback || _noop2.default); - if (!(0, _isArray2.default)(tasks)) return callback(new Error('First argument to waterfall must be an array of functions')); - if (!tasks.length) return callback(); - var taskIndex = 0; - - function nextTask(args) { - var task = (0, _wrapAsync2.default)(tasks[taskIndex++]); - args.push((0, _onlyOnce2.default)(next)); - task.apply(null, args); - } - - function next(err /*, ...args*/) { - if (err || taskIndex === tasks.length) { - return callback.apply(null, arguments); - } - nextTask((0, _slice2.default)(arguments, 1)); - } - - nextTask([]); -}; - -var _isArray = require('lodash/isArray'); - -var _isArray2 = _interopRequireDefault(_isArray); - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _once = require('./internal/once'); - -var _once2 = _interopRequireDefault(_once); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -module.exports = exports['default']; - -/** - * Runs the `tasks` array of functions in series, each passing their results to - * the next in the array. However, if any of the `tasks` pass an error to their - * own callback, the next function is not executed, and the main `callback` is - * immediately called with the error. - * - * @name waterfall - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Array} tasks - An array of [async functions]{@link AsyncFunction} - * to run. - * Each function should complete with any number of `result` values. - * The `result` values will be passed as arguments, in order, to the next task. - * @param {Function} [callback] - An optional callback to run once all the - * functions have completed. This will be passed the results of the last task's - * callback. Invoked with (err, [results]). - * @returns undefined - * @example - * - * async.waterfall([ - * function(callback) { - * callback(null, 'one', 'two'); - * }, - * function(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * }, - * function(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - * ], function (err, result) { - * // result now equals 'done' - * }); - * - * // Or, with named functions: - * async.waterfall([ - * myFirstFunction, - * mySecondFunction, - * myLastFunction, - * ], function (err, result) { - * // result now equals 'done' - * }); - * function myFirstFunction(callback) { - * callback(null, 'one', 'two'); - * } - * function mySecondFunction(arg1, arg2, callback) { - * // arg1 now equals 'one' and arg2 now equals 'two' - * callback(null, 'three'); - * } - * function myLastFunction(arg1, callback) { - * // arg1 now equals 'three' - * callback(null, 'done'); - * } - */ -},{"./internal/once":39,"./internal/onlyOnce":40,"./internal/slice":45,"./internal/wrapAsync":47,"lodash/isArray":479,"lodash/noop":490}],57:[function(require,module,exports){ -'use strict'; - -Object.defineProperty(exports, "__esModule", { - value: true -}); -exports.default = whilst; - -var _noop = require('lodash/noop'); - -var _noop2 = _interopRequireDefault(_noop); - -var _slice = require('./internal/slice'); - -var _slice2 = _interopRequireDefault(_slice); - -var _onlyOnce = require('./internal/onlyOnce'); - -var _onlyOnce2 = _interopRequireDefault(_onlyOnce); - -var _wrapAsync = require('./internal/wrapAsync'); - -var _wrapAsync2 = _interopRequireDefault(_wrapAsync); - -function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } - -/** - * Repeatedly call `iteratee`, while `test` returns `true`. Calls `callback` when - * stopped, or an error occurs. - * - * @name whilst - * @static - * @memberOf module:ControlFlow - * @method - * @category Control Flow - * @param {Function} test - synchronous truth test to perform before each - * execution of `iteratee`. Invoked with (). - * @param {AsyncFunction} iteratee - An async function which is called each time - * `test` passes. Invoked with (callback). - * @param {Function} [callback] - A callback which is called after the test - * function has failed and repeated execution of `iteratee` has stopped. `callback` - * will be passed an error and any arguments passed to the final `iteratee`'s - * callback. Invoked with (err, [results]); - * @returns undefined - * @example - * - * var count = 0; - * async.whilst( - * function() { return count < 5; }, - * function(callback) { - * count++; - * setTimeout(function() { - * callback(null, count); - * }, 1000); - * }, - * function (err, n) { - * // 5 seconds have passed, n = 5 - * } - * ); - */ -function whilst(test, iteratee, callback) { - callback = (0, _onlyOnce2.default)(callback || _noop2.default); - var _iteratee = (0, _wrapAsync2.default)(iteratee); - if (!test()) return callback(null); - var next = function (err /*, ...args*/) { - if (err) return callback(err); - if (test()) return _iteratee(next); - var args = (0, _slice2.default)(arguments, 1); - callback.apply(null, [null].concat(args)); - }; - _iteratee(next); -} -module.exports = exports['default']; -},{"./internal/onlyOnce":40,"./internal/slice":45,"./internal/wrapAsync":47,"lodash/noop":490}],58:[function(require,module,exports){ -(function (Buffer){ -// base-x encoding -// Forked from https://github.com/cryptocoinjs/bs58 -// Originally written by Mike Hearn for BitcoinJ -// Copyright (c) 2011 Google Inc -// Ported to JavaScript by Stefan Thomas -// Merged Buffer refactorings from base58-native by Stephen Pair -// Copyright (c) 2013 BitPay Inc - -module.exports = function base (ALPHABET) { - var ALPHABET_MAP = {} - var BASE = ALPHABET.length - var LEADER = ALPHABET.charAt(0) - - // pre-compute lookup table - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z) - - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z - } - - function encode (source) { - if (source.length === 0) return '' - - var digits = [0] - for (var i = 0; i < source.length; ++i) { - for (var j = 0, carry = source[i]; j < digits.length; ++j) { - carry += digits[j] << 8 - digits[j] = carry % BASE - carry = (carry / BASE) | 0 - } - - while (carry > 0) { - digits.push(carry % BASE) - carry = (carry / BASE) | 0 - } - } - - var string = '' - - // deal with leading zeros - for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += ALPHABET[0] - // convert digits to a string - for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]] - - return string - } - - function decodeUnsafe (string) { - if (string.length === 0) return Buffer.allocUnsafe(0) - - var bytes = [0] - for (var i = 0; i < string.length; i++) { - var value = ALPHABET_MAP[string[i]] - if (value === undefined) return - - for (var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * BASE - bytes[j] = carry & 0xff - carry >>= 8 - } - - while (carry > 0) { - bytes.push(carry & 0xff) - carry >>= 8 - } - } - - // deal with leading zeros - for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) { - bytes.push(0) - } - - return Buffer.from(bytes.reverse()) - } - - function decode (string) { - var buffer = decodeUnsafe(string) - if (buffer) return buffer - - throw new Error('Non-base' + BASE + ' character') - } - - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],59:[function(require,module,exports){ -"use strict"; - -/** - * Generate a character map. - * @param {string} alphabet e.g. "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567" - * @param {object} mappings map overrides from key to value - * @method - */ - -var charmap = function (alphabet, mappings) { - mappings || (mappings = {}); - alphabet.split("").forEach(function (c, i) { - if (!(c in mappings)) mappings[c] = i; - }); - return mappings; -} - -/** - * The RFC 4648 base 32 alphabet and character map. - * @see {@link https://tools.ietf.org/html/rfc4648} - */ - -var rfc4648 = { - alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", - charmap: { - 0: 14, - 1: 8 - } -}; - -rfc4648.charmap = charmap(rfc4648.alphabet, rfc4648.charmap); - -/** - * The Crockford base 32 alphabet and character map. - * @see {@link http://www.crockford.com/wrmg/base32.html} - */ - -var crockford = { - alphabet: "0123456789ABCDEFGHJKMNPQRSTVWXYZ", - charmap: { - O: 0, - I: 1, - L: 1 - } -}; - -crockford.charmap = charmap(crockford.alphabet, crockford.charmap); - -/** - * base32hex - * @see {@link https://en.wikipedia.org/wiki/Base32#base32hex} - */ - -var base32hex = { - alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUV", - charmap: {} -}; - -base32hex.charmap = charmap(base32hex.alphabet, base32hex.charmap); - -/** - * Create a new `Decoder` with the given options. - * - * @param {object} [options] - * @param {string} [type] Supported Base-32 variants are "rfc4648" and - * "crockford". - * @param {object} [charmap] Override the character map used in decoding. - * @constructor - */ - -function Decoder (options) { - this.buf = []; - this.shift = 8; - this.carry = 0; - - if (options) { - - switch (options.type) { - case "rfc4648": - this.charmap = exports.rfc4648.charmap; - break; - case "crockford": - this.charmap = exports.crockford.charmap; - break; - case "base32hex": - this.charmap = exports.base32hex.charmap; - break; - default: - throw new Error("invalid type"); - } - - if (options.charmap) this.charmap = options.charmap; - } -} - -/** - * The default character map coresponds to RFC4648. - */ - -Decoder.prototype.charmap = rfc4648.charmap; - -/** - * Decode a string, continuing from the previous state. - * - * @param {string} str - * @return {Decoder} this - */ - -Decoder.prototype.write = function (str) { - var charmap = this.charmap; - var buf = this.buf; - var shift = this.shift; - var carry = this.carry; - - // decode string - str.toUpperCase().split("").forEach(function (char) { - - // ignore padding - if (char == "=") return; - - // lookup symbol - var symbol = charmap[char] & 0xff; - - // 1: 00000 000 - // 2: 00 00000 0 - // 3: 0000 0000 - // 4: 0 00000 00 - // 5: 000 00000 - // 6: 00000 000 - // 7: 00 00000 0 - - shift -= 5; - if (shift > 0) { - carry |= symbol << shift; - } else if (shift < 0) { - buf.push(carry | (symbol >> -shift)); - shift += 8; - carry = (symbol << shift) & 0xff; - } else { - buf.push(carry | symbol); - shift = 8; - carry = 0; - } - }); - - // save state - this.shift = shift; - this.carry = carry; - - // for chaining - return this; -}; - -/** - * Finish decoding. - * - * @param {string} [str] The final string to decode. - * @return {Array} Decoded byte array. - */ - -Decoder.prototype.finalize = function (str) { - if (str) { - this.write(str); - } - if (this.shift !== 8 && this.carry !== 0) { - this.buf.push(this.carry); - this.shift = 8; - this.carry = 0; - } - return this.buf; -}; - -/** - * Create a new `Encoder` with the given options. - * - * @param {object} [options] - * @param {string} [type] Supported Base-32 variants are "rfc4648" and - * "crockford". - * @param {object} [alphabet] Override the alphabet used in encoding. - * @constructor - */ - -function Encoder (options) { - this.buf = ""; - this.shift = 3; - this.carry = 0; - - if (options) { - - switch (options.type) { - case "rfc4648": - this.alphabet = exports.rfc4648.alphabet; - break; - case "crockford": - this.alphabet = exports.crockford.alphabet; - break; - case "base32hex": - this.alphabet = exports.base32hex.alphabet; - break; - default: - throw new Error("invalid type"); - } - - if (options.alphabet) this.alphabet = options.alphabet; - else if (options.lc) this.alphabet = this.alphabet.toLowerCase(); - } -} - -/** - * The default alphabet coresponds to RFC4648. - */ - -Encoder.prototype.alphabet = rfc4648.alphabet; - -/** - * Encode a byte array, continuing from the previous state. - * - * @param {byte[]} buf The byte array to encode. - * @return {Encoder} this - */ - -Encoder.prototype.write = function (buf) { - var shift = this.shift; - var carry = this.carry; - var symbol; - var byte; - var i; - - // encode each byte in buf - for (i = 0; i < buf.length; i++) { - byte = buf[i]; - - // 1: 00000 000 - // 2: 00 00000 0 - // 3: 0000 0000 - // 4: 0 00000 00 - // 5: 000 00000 - // 6: 00000 000 - // 7: 00 00000 0 - - symbol = carry | (byte >> shift); - this.buf += this.alphabet[symbol & 0x1f]; - - if (shift > 5) { - shift -= 5; - symbol = byte >> shift; - this.buf += this.alphabet[symbol & 0x1f]; - } - - shift = 5 - shift; - carry = byte << shift; - shift = 8 - shift; - } - - // save state - this.shift = shift; - this.carry = carry; - - // for chaining - return this; -}; - -/** - * Finish encoding. - * - * @param {byte[]} [buf] The final byte array to encode. - * @return {string} The encoded byte array. - */ - -Encoder.prototype.finalize = function (buf) { - if (buf) { - this.write(buf); - } - if (this.shift !== 3) { - this.buf += this.alphabet[this.carry & 0x1f]; - this.shift = 3; - this.carry = 0; - } - return this.buf; -}; - -/** - * Convenience encoder. - * - * @param {byte[]} buf The byte array to encode. - * @param {object} [options] Options to pass to the encoder. - * @return {string} The encoded string. - */ - -exports.encode = function (buf, options) { - return new Encoder(options).finalize(buf); -}; - -/** - * Convenience decoder. - * - * @param {string} str The string to decode. - * @param {object} [options] Options to pass to the decoder. - * @return {byte[]} The decoded byte array. - */ - -exports.decode = function (str, options) { - return new Decoder(options).finalize(str); -}; - -// Exports. -exports.Decoder = Decoder; -exports.Encoder = Encoder; -exports.charmap = charmap; -exports.crockford = crockford; -exports.rfc4648 = rfc4648; -exports.base32hex = base32hex; - -},{}],60:[function(require,module,exports){ -/*! bignumber.js v3.0.1 https://github.com/MikeMcl/bignumber.js/LICENCE */ - -;(function (globalObj) { - 'use strict'; - - /* - bignumber.js v3.0.1 - A JavaScript library for arbitrary-precision arithmetic. - https://github.com/MikeMcl/bignumber.js - Copyright (c) 2016 Michael Mclaughlin - MIT Expat Licence - */ - - - var BigNumber, parseNumeric, - 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(configObj) { - var div, - - // 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.shift(), 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.unshift(1); - } - } - } - - // 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.unshift(carry); - - 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.shift() ); - } - - // 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.unshift(0); - 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.unshift(0); - - // 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.shift(); - } - - 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.shift(), --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.unshift(a); - ++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.shift(); - } - - 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; - }; - - - // Aliases for BigDecimal methods. - //P.add = P.plus; // P.add included above - //P.subtract = P.minus; // P.sub included above - //P.multiply = P.times; // P.mul included above - //P.divide = P.div; - //P.remainder = P.mod; - //P.compareTo = P.cmp; - //P.negate = P.neg; - - - if ( configObj != null ) BigNumber.config(configObj); - - 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 ( typeof define == 'function' && define.amd ) { - define( function () { return BigNumber; } ); - - // 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); - -},{}],61:[function(require,module,exports){ -// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki -// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] -// NOTE: SIGHASH byte ignored AND restricted, truncate before use - -var Buffer = require('safe-buffer').Buffer - -function check (buffer) { - if (buffer.length < 8) return false - if (buffer.length > 72) return false - if (buffer[0] !== 0x30) return false - if (buffer[1] !== buffer.length - 2) return false - if (buffer[2] !== 0x02) return false - - var lenR = buffer[3] - if (lenR === 0) return false - if (5 + lenR >= buffer.length) return false - if (buffer[4 + lenR] !== 0x02) return false - - var lenS = buffer[5 + lenR] - if (lenS === 0) return false - if ((6 + lenR + lenS) !== buffer.length) return false - - if (buffer[4] & 0x80) return false - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false - - if (buffer[lenR + 6] & 0x80) return false - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false - return true -} - -function decode (buffer) { - if (buffer.length < 8) throw new Error('DER sequence length is too short') - if (buffer.length > 72) throw new Error('DER sequence length is too long') - if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') - if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') - if (buffer[2] !== 0x02) throw new Error('Expected DER integer') - - var lenR = buffer[3] - if (lenR === 0) throw new Error('R length is zero') - if (5 + lenR >= buffer.length) throw new Error('R length is too long') - if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') - - var lenS = buffer[5 + lenR] - if (lenS === 0) throw new Error('S length is zero') - if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') - - if (buffer[4] & 0x80) throw new Error('R value is negative') - if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') - - if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') - if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') - - // non-BIP66 - extract R, S values - return { - r: buffer.slice(4, 4 + lenR), - s: buffer.slice(6 + lenR) - } -} - -/* - * Expects r and s to be positive DER integers. - * - * The DER format uses the most significant bit as a sign bit (& 0x80). - * If the significant bit is set AND the integer is positive, a 0x00 is prepended. - * - * Examples: - * - * 0 => 0x00 - * 1 => 0x01 - * -1 => 0xff - * 127 => 0x7f - * -127 => 0x81 - * 128 => 0x0080 - * -128 => 0x80 - * 255 => 0x00ff - * -255 => 0xff01 - * 16300 => 0x3fac - * -16300 => 0xc054 - * 62300 => 0x00f35c - * -62300 => 0xff0ca4 -*/ -function encode (r, s) { - var lenR = r.length - var lenS = s.length - if (lenR === 0) throw new Error('R length is zero') - if (lenS === 0) throw new Error('S length is zero') - if (lenR > 33) throw new Error('R length is too long') - if (lenS > 33) throw new Error('S length is too long') - if (r[0] & 0x80) throw new Error('R value is negative') - if (s[0] & 0x80) throw new Error('S value is negative') - if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') - if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') - - var signature = Buffer.allocUnsafe(6 + lenR + lenS) - - // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] - signature[0] = 0x30 - signature[1] = signature.length - 2 - signature[2] = 0x02 - signature[3] = r.length - r.copy(signature, 4) - signature[4 + lenR] = 0x02 - signature[5 + lenR] = s.length - s.copy(signature, 6 + lenR) - - return signature -} - -module.exports = { - check: check, - decode: decode, - encode: encode -} - -},{"safe-buffer":656}],62:[function(require,module,exports){ -// Blake2B in pure Javascript -// Adapted from the reference implementation in RFC7693 -// Ported to Javascript by DC - https://github.com/dcposch - -var util = require('./util') - -// 64-bit unsigned addition -// Sets v[a,a+1] += v[b,b+1] -// v should be a Uint32Array -function ADD64AA (v, a, b) { - var o0 = v[a] + v[b] - var o1 = v[a + 1] + v[b + 1] - if (o0 >= 0x100000000) { - o1++ - } - v[a] = o0 - v[a + 1] = o1 -} - -// 64-bit unsigned addition -// Sets v[a,a+1] += b -// b0 is the low 32 bits of b, b1 represents the high 32 bits -function ADD64AC (v, a, b0, b1) { - var o0 = v[a] + b0 - if (b0 < 0) { - o0 += 0x100000000 - } - var o1 = v[a + 1] + b1 - if (o0 >= 0x100000000) { - o1++ - } - v[a] = o0 - v[a + 1] = o1 -} - -// Little-endian byte access -function B2B_GET32 (arr, i) { - return (arr[i] ^ - (arr[i + 1] << 8) ^ - (arr[i + 2] << 16) ^ - (arr[i + 3] << 24)) -} - -// G Mixing function -// The ROTRs are inlined for speed -function B2B_G (a, b, c, d, ix, iy) { - var x0 = m[ix] - var x1 = m[ix + 1] - var y0 = m[iy] - var y1 = m[iy + 1] - - ADD64AA(v, a, b) // v[a,a+1] += v[b,b+1] ... in JS we must store a uint64 as two uint32s - ADD64AC(v, a, x0, x1) // v[a, a+1] += x ... x0 is the low 32 bits of x, x1 is the high 32 bits - - // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated to the right by 32 bits - var xor0 = v[d] ^ v[a] - var xor1 = v[d + 1] ^ v[a + 1] - v[d] = xor1 - v[d + 1] = xor0 - - ADD64AA(v, c, d) - - // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 24 bits - xor0 = v[b] ^ v[c] - xor1 = v[b + 1] ^ v[c + 1] - v[b] = (xor0 >>> 24) ^ (xor1 << 8) - v[b + 1] = (xor1 >>> 24) ^ (xor0 << 8) - - ADD64AA(v, a, b) - ADD64AC(v, a, y0, y1) - - // v[d,d+1] = (v[d,d+1] xor v[a,a+1]) rotated right by 16 bits - xor0 = v[d] ^ v[a] - xor1 = v[d + 1] ^ v[a + 1] - v[d] = (xor0 >>> 16) ^ (xor1 << 16) - v[d + 1] = (xor1 >>> 16) ^ (xor0 << 16) - - ADD64AA(v, c, d) - - // v[b,b+1] = (v[b,b+1] xor v[c,c+1]) rotated right by 63 bits - xor0 = v[b] ^ v[c] - xor1 = v[b + 1] ^ v[c + 1] - v[b] = (xor1 >>> 31) ^ (xor0 << 1) - v[b + 1] = (xor0 >>> 31) ^ (xor1 << 1) -} - -// Initialization Vector -var BLAKE2B_IV32 = new Uint32Array([ - 0xF3BCC908, 0x6A09E667, 0x84CAA73B, 0xBB67AE85, - 0xFE94F82B, 0x3C6EF372, 0x5F1D36F1, 0xA54FF53A, - 0xADE682D1, 0x510E527F, 0x2B3E6C1F, 0x9B05688C, - 0xFB41BD6B, 0x1F83D9AB, 0x137E2179, 0x5BE0CD19 -]) - -var SIGMA8 = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, - 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, - 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, - 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, - 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, - 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, - 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, - 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, - 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0, - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3 -] - -// These are offsets into a uint64 buffer. -// Multiply them all by 2 to make them offsets into a uint32 buffer, -// because this is Javascript and we don't have uint64s -var SIGMA82 = new Uint8Array(SIGMA8.map(function (x) { return x * 2 })) - -// Compression function. 'last' flag indicates last block. -// Note we're representing 16 uint64s as 32 uint32s -var v = new Uint32Array(32) -var m = new Uint32Array(32) -function blake2bCompress (ctx, last) { - var i = 0 - - // init work variables - for (i = 0; i < 16; i++) { - v[i] = ctx.h[i] - v[i + 16] = BLAKE2B_IV32[i] - } - - // low 64 bits of offset - v[24] = v[24] ^ ctx.t - v[25] = v[25] ^ (ctx.t / 0x100000000) - // high 64 bits not supported, offset may not be higher than 2**53-1 - - // last block flag set ? - if (last) { - v[28] = ~v[28] - v[29] = ~v[29] - } - - // get little-endian words - for (i = 0; i < 32; i++) { - m[i] = B2B_GET32(ctx.b, 4 * i) - } - - // twelve rounds of mixing - // uncomment the DebugPrint calls to log the computation - // and match the RFC sample documentation - // util.debugPrint(' m[16]', m, 64) - for (i = 0; i < 12; i++) { - // util.debugPrint(' (i=' + (i < 10 ? ' ' : '') + i + ') v[16]', v, 64) - B2B_G(0, 8, 16, 24, SIGMA82[i * 16 + 0], SIGMA82[i * 16 + 1]) - B2B_G(2, 10, 18, 26, SIGMA82[i * 16 + 2], SIGMA82[i * 16 + 3]) - B2B_G(4, 12, 20, 28, SIGMA82[i * 16 + 4], SIGMA82[i * 16 + 5]) - B2B_G(6, 14, 22, 30, SIGMA82[i * 16 + 6], SIGMA82[i * 16 + 7]) - B2B_G(0, 10, 20, 30, SIGMA82[i * 16 + 8], SIGMA82[i * 16 + 9]) - B2B_G(2, 12, 22, 24, SIGMA82[i * 16 + 10], SIGMA82[i * 16 + 11]) - B2B_G(4, 14, 16, 26, SIGMA82[i * 16 + 12], SIGMA82[i * 16 + 13]) - B2B_G(6, 8, 18, 28, SIGMA82[i * 16 + 14], SIGMA82[i * 16 + 15]) - } - // util.debugPrint(' (i=12) v[16]', v, 64) - - for (i = 0; i < 16; i++) { - ctx.h[i] = ctx.h[i] ^ v[i] ^ v[i + 16] - } - // util.debugPrint('h[8]', ctx.h, 64) -} - -// Creates a BLAKE2b hashing context -// Requires an output length between 1 and 64 bytes -// Takes an optional Uint8Array key -function blake2bInit (outlen, key) { - if (outlen === 0 || outlen > 64) { - throw new Error('Illegal output length, expected 0 < length <= 64') - } - if (key && key.length > 64) { - throw new Error('Illegal key, expected Uint8Array with 0 < length <= 64') - } - - // state, 'param block' - var ctx = { - b: new Uint8Array(128), - h: new Uint32Array(16), - t: 0, // input count - c: 0, // pointer within buffer - outlen: outlen // output length in bytes - } - - // initialize hash state - for (var i = 0; i < 16; i++) { - ctx.h[i] = BLAKE2B_IV32[i] - } - var keylen = key ? key.length : 0 - ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen - - // key the hash, if applicable - if (key) { - blake2bUpdate(ctx, key) - // at the end - ctx.c = 128 - } - - return ctx -} - -// Updates a BLAKE2b streaming hash -// Requires hash context and Uint8Array (byte array) -function blake2bUpdate (ctx, input) { - for (var i = 0; i < input.length; i++) { - if (ctx.c === 128) { // buffer full ? - ctx.t += ctx.c // add counters - blake2bCompress(ctx, false) // compress (not last) - ctx.c = 0 // counter to zero - } - ctx.b[ctx.c++] = input[i] - } -} - -// Completes a BLAKE2b streaming hash -// Returns a Uint8Array containing the message digest -function blake2bFinal (ctx) { - ctx.t += ctx.c // mark last block offset - - while (ctx.c < 128) { // fill up with zeros - ctx.b[ctx.c++] = 0 - } - blake2bCompress(ctx, true) // final block flag = 1 - - // little endian convert and store - var out = new Uint8Array(ctx.outlen) - for (var i = 0; i < ctx.outlen; i++) { - out[i] = ctx.h[i >> 2] >> (8 * (i & 3)) - } - return out -} - -// Computes the BLAKE2B hash of a string or byte array, and returns a Uint8Array -// -// Returns a n-byte Uint8Array -// -// Parameters: -// - input - the input bytes, as a string, Buffer or Uint8Array -// - key - optional key Uint8Array, up to 64 bytes -// - outlen - optional output length in bytes, default 64 -function blake2b (input, key, outlen) { - // preprocess inputs - outlen = outlen || 64 - input = util.normalizeInput(input) - - // do the math - var ctx = blake2bInit(outlen, key) - blake2bUpdate(ctx, input) - return blake2bFinal(ctx) -} - -// Computes the BLAKE2B hash of a string or byte array -// -// Returns an n-byte hash in hex, all lowercase -// -// Parameters: -// - input - the input bytes, as a string, Buffer, or Uint8Array -// - key - optional key Uint8Array, up to 64 bytes -// - outlen - optional output length in bytes, default 64 -function blake2bHex (input, key, outlen) { - var output = blake2b(input, key, outlen) - return util.toHex(output) -} - -module.exports = { - blake2b: blake2b, - blake2bHex: blake2bHex, - blake2bInit: blake2bInit, - blake2bUpdate: blake2bUpdate, - blake2bFinal: blake2bFinal -} - -},{"./util":65}],63:[function(require,module,exports){ -// BLAKE2s hash function in pure Javascript -// Adapted from the reference implementation in RFC7693 -// Ported to Javascript by DC - https://github.com/dcposch - -var util = require('./util') - -// Little-endian byte access. -// Expects a Uint8Array and an index -// Returns the little-endian uint32 at v[i..i+3] -function B2S_GET32 (v, i) { - return v[i] ^ (v[i + 1] << 8) ^ (v[i + 2] << 16) ^ (v[i + 3] << 24) -} - -// Mixing function G. -function B2S_G (a, b, c, d, x, y) { - v[a] = v[a] + v[b] + x - v[d] = ROTR32(v[d] ^ v[a], 16) - v[c] = v[c] + v[d] - v[b] = ROTR32(v[b] ^ v[c], 12) - v[a] = v[a] + v[b] + y - v[d] = ROTR32(v[d] ^ v[a], 8) - v[c] = v[c] + v[d] - v[b] = ROTR32(v[b] ^ v[c], 7) -} - -// 32-bit right rotation -// x should be a uint32 -// y must be between 1 and 31, inclusive -function ROTR32 (x, y) { - return (x >>> y) ^ (x << (32 - y)) -} - -// Initialization Vector. -var BLAKE2S_IV = new Uint32Array([ - 0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, - 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19]) - -var SIGMA = new Uint8Array([ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3, - 11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4, - 7, 9, 3, 1, 13, 12, 11, 14, 2, 6, 5, 10, 4, 0, 15, 8, - 9, 0, 5, 7, 2, 4, 10, 15, 14, 1, 11, 12, 6, 8, 3, 13, - 2, 12, 6, 10, 0, 11, 8, 3, 4, 13, 7, 5, 15, 14, 1, 9, - 12, 5, 1, 15, 14, 13, 4, 10, 0, 7, 6, 3, 9, 2, 8, 11, - 13, 11, 7, 14, 12, 1, 3, 9, 5, 0, 15, 4, 8, 6, 2, 10, - 6, 15, 14, 9, 11, 3, 0, 8, 12, 2, 13, 7, 1, 4, 10, 5, - 10, 2, 8, 4, 7, 6, 1, 5, 15, 11, 9, 14, 3, 12, 13, 0]) - -// Compression function. "last" flag indicates last block -var v = new Uint32Array(16) -var m = new Uint32Array(16) -function blake2sCompress (ctx, last) { - var i = 0 - for (i = 0; i < 8; i++) { // init work variables - v[i] = ctx.h[i] - v[i + 8] = BLAKE2S_IV[i] - } - - v[12] ^= ctx.t // low 32 bits of offset - v[13] ^= (ctx.t / 0x100000000) // high 32 bits - if (last) { // last block flag set ? - v[14] = ~v[14] - } - - for (i = 0; i < 16; i++) { // get little-endian words - m[i] = B2S_GET32(ctx.b, 4 * i) - } - - // ten rounds of mixing - // uncomment the DebugPrint calls to log the computation - // and match the RFC sample documentation - // util.debugPrint(' m[16]', m, 32) - for (i = 0; i < 10; i++) { - // util.debugPrint(' (i=' + i + ') v[16]', v, 32) - B2S_G(0, 4, 8, 12, m[SIGMA[i * 16 + 0]], m[SIGMA[i * 16 + 1]]) - B2S_G(1, 5, 9, 13, m[SIGMA[i * 16 + 2]], m[SIGMA[i * 16 + 3]]) - B2S_G(2, 6, 10, 14, m[SIGMA[i * 16 + 4]], m[SIGMA[i * 16 + 5]]) - B2S_G(3, 7, 11, 15, m[SIGMA[i * 16 + 6]], m[SIGMA[i * 16 + 7]]) - B2S_G(0, 5, 10, 15, m[SIGMA[i * 16 + 8]], m[SIGMA[i * 16 + 9]]) - B2S_G(1, 6, 11, 12, m[SIGMA[i * 16 + 10]], m[SIGMA[i * 16 + 11]]) - B2S_G(2, 7, 8, 13, m[SIGMA[i * 16 + 12]], m[SIGMA[i * 16 + 13]]) - B2S_G(3, 4, 9, 14, m[SIGMA[i * 16 + 14]], m[SIGMA[i * 16 + 15]]) - } - // util.debugPrint(' (i=10) v[16]', v, 32) - - for (i = 0; i < 8; i++) { - ctx.h[i] ^= v[i] ^ v[i + 8] - } - // util.debugPrint('h[8]', ctx.h, 32) -} - -// Creates a BLAKE2s hashing context -// Requires an output length between 1 and 32 bytes -// Takes an optional Uint8Array key -function blake2sInit (outlen, key) { - if (!(outlen > 0 && outlen <= 32)) { - throw new Error('Incorrect output length, should be in [1, 32]') - } - var keylen = key ? key.length : 0 - if (key && !(keylen > 0 && keylen <= 32)) { - throw new Error('Incorrect key length, should be in [1, 32]') - } - - var ctx = { - h: new Uint32Array(BLAKE2S_IV), // hash state - b: new Uint32Array(64), // input block - c: 0, // pointer within block - t: 0, // input count - outlen: outlen // output length in bytes - } - ctx.h[0] ^= 0x01010000 ^ (keylen << 8) ^ outlen - - if (keylen > 0) { - blake2sUpdate(ctx, key) - ctx.c = 64 // at the end - } - - return ctx -} - -// Updates a BLAKE2s streaming hash -// Requires hash context and Uint8Array (byte array) -function blake2sUpdate (ctx, input) { - for (var i = 0; i < input.length; i++) { - if (ctx.c === 64) { // buffer full ? - ctx.t += ctx.c // add counters - blake2sCompress(ctx, false) // compress (not last) - ctx.c = 0 // counter to zero - } - ctx.b[ctx.c++] = input[i] - } -} - -// Completes a BLAKE2s streaming hash -// Returns a Uint8Array containing the message digest -function blake2sFinal (ctx) { - ctx.t += ctx.c // mark last block offset - while (ctx.c < 64) { // fill up with zeros - ctx.b[ctx.c++] = 0 - } - blake2sCompress(ctx, true) // final block flag = 1 - - // little endian convert and store - var out = new Uint8Array(ctx.outlen) - for (var i = 0; i < ctx.outlen; i++) { - out[i] = (ctx.h[i >> 2] >> (8 * (i & 3))) & 0xFF - } - return out -} - -// Computes the BLAKE2S hash of a string or byte array, and returns a Uint8Array -// -// Returns a n-byte Uint8Array -// -// Parameters: -// - input - the input bytes, as a string, Buffer, or Uint8Array -// - key - optional key Uint8Array, up to 32 bytes -// - outlen - optional output length in bytes, default 64 -function blake2s (input, key, outlen) { - // preprocess inputs - outlen = outlen || 32 - input = util.normalizeInput(input) - - // do the math - var ctx = blake2sInit(outlen, key) - blake2sUpdate(ctx, input) - return blake2sFinal(ctx) -} - -// Computes the BLAKE2S hash of a string or byte array -// -// Returns an n-byte hash in hex, all lowercase -// -// Parameters: -// - input - the input bytes, as a string, Buffer, or Uint8Array -// - key - optional key Uint8Array, up to 32 bytes -// - outlen - optional output length in bytes, default 64 -function blake2sHex (input, key, outlen) { - var output = blake2s(input, key, outlen) - return util.toHex(output) -} - -module.exports = { - blake2s: blake2s, - blake2sHex: blake2sHex, - blake2sInit: blake2sInit, - blake2sUpdate: blake2sUpdate, - blake2sFinal: blake2sFinal -} - -},{"./util":65}],64:[function(require,module,exports){ -var b2b = require('./blake2b') -var b2s = require('./blake2s') - -module.exports = { - blake2b: b2b.blake2b, - blake2bHex: b2b.blake2bHex, - blake2bInit: b2b.blake2bInit, - blake2bUpdate: b2b.blake2bUpdate, - blake2bFinal: b2b.blake2bFinal, - blake2s: b2s.blake2s, - blake2sHex: b2s.blake2sHex, - blake2sInit: b2s.blake2sInit, - blake2sUpdate: b2s.blake2sUpdate, - blake2sFinal: b2s.blake2sFinal -} - -},{"./blake2b":62,"./blake2s":63}],65:[function(require,module,exports){ -(function (Buffer){ -var ERROR_MSG_INPUT = 'Input must be an string, Buffer or Uint8Array' - -// For convenience, let people hash a string, not just a Uint8Array -function normalizeInput (input) { - var ret - if (input instanceof Uint8Array) { - ret = input - } else if (input instanceof Buffer) { - ret = new Uint8Array(input) - } else if (typeof (input) === 'string') { - ret = new Uint8Array(Buffer.from(input, 'utf8')) - } else { - throw new Error(ERROR_MSG_INPUT) - } - return ret -} - -// Converts a Uint8Array to a hexadecimal string -// For example, toHex([255, 0, 255]) returns "ff00ff" -function toHex (bytes) { - return Array.prototype.map.call(bytes, function (n) { - return (n < 16 ? '0' : '') + n.toString(16) - }).join('') -} - -// Converts any value in [0...2^32-1] to an 8-character hex string -function uint32ToHex (val) { - return (0x100000000 + val).toString(16).substring(1) -} - -// For debugging: prints out hash state in the same format as the RFC -// sample computation exactly, so that you can diff -function debugPrint (label, arr, size) { - var msg = '\n' + label + ' = ' - for (var i = 0; i < arr.length; i += 2) { - if (size === 32) { - msg += uint32ToHex(arr[i]).toUpperCase() - msg += ' ' - msg += uint32ToHex(arr[i + 1]).toUpperCase() - } else if (size === 64) { - msg += uint32ToHex(arr[i + 1]).toUpperCase() - msg += uint32ToHex(arr[i]).toUpperCase() - } else throw new Error('Invalid size ' + size) - if (i % 6 === 4) { - msg += '\n' + new Array(label.length + 4).join(' ') - } else if (i < arr.length - 2) { - msg += ' ' - } - } - console.log(msg) -} - -// For performance testing: generates N bytes of input, hashes M times -// Measures and prints MB/second hash performance each time -function testSpeed (hashFn, N, M) { - var startMs = new Date().getTime() - - var input = new Uint8Array(N) - for (var i = 0; i < N; i++) { - input[i] = i % 256 - } - var genMs = new Date().getTime() - console.log('Generated random input in ' + (genMs - startMs) + 'ms') - startMs = genMs - - for (i = 0; i < M; i++) { - var hashHex = hashFn(input) - var hashMs = new Date().getTime() - var ms = hashMs - startMs - startMs = hashMs - console.log('Hashed in ' + ms + 'ms: ' + hashHex.substring(0, 20) + '...') - console.log(Math.round(N / (1 << 20) / (ms / 1000) * 100) / 100 + ' MB PER SECOND') - } -} - -module.exports = { - normalizeInput: normalizeInput, - toHex: toHex, - debugPrint: debugPrint, - testSpeed: testSpeed -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],66:[function(require,module,exports){ -(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 { - // Obfuscate that we require Buffer, to reduce size - Buffer = require('buf' + 'fer').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 ? ''; - }; - - /* - - 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); - -},{}],67:[function(require,module,exports){ -'use strict' - -const Bignumber = require('bignumber.js') - -exports.MT = { - POS_INT: 0, - NEG_INT: 1, - BYTE_STRING: 2, - UTF8_STRING: 3, - ARRAY: 4, - MAP: 5, - TAG: 6, - SIMPLE_FLOAT: 7 -} - -exports.TAG = { - DATE_STRING: 0, - DATE_EPOCH: 1, - POS_BIGINT: 2, - NEG_BIGINT: 3, - DECIMAL_FRAC: 4, - BIGFLOAT: 5, - BASE64URL_EXPECTED: 21, - BASE64_EXPECTED: 22, - BASE16_EXPECTED: 23, - CBOR: 24, - URI: 32, - BASE64URL: 33, - BASE64: 34, - REGEXP: 35, - MIME: 36 -} - -exports.NUMBYTES = { - ZERO: 0, - ONE: 24, - TWO: 25, - FOUR: 26, - EIGHT: 27, - INDEFINITE: 31 -} - -exports.SIMPLE = { - FALSE: 20, - TRUE: 21, - NULL: 22, - UNDEFINED: 23 -} - -exports.SYMS = { - NULL: Symbol('null'), - UNDEFINED: Symbol('undef'), - PARENT: Symbol('parent'), - BREAK: Symbol('break'), - STREAM: Symbol('stream') -} - -exports.SHIFT32 = Math.pow(2, 32) -exports.SHIFT16 = Math.pow(2, 16) - -exports.MAX_SAFE_HIGH = 0x1fffff -exports.NEG_ONE = new Bignumber(-1) -exports.TEN = new Bignumber(10) -exports.TWO = new Bignumber(2) - -exports.PARENT = { - ARRAY: 0, - OBJECT: 1, - MAP: 2, - TAG: 3, - BYTE_STRING: 4, - UTF8_STRING: 5 -} - -},{"bignumber.js":60}],68:[function(require,module,exports){ -module.exports = function decodeAsm (stdlib, foreign, buffer) { - 'use asm' - - // -- Imports - - var heap = new stdlib.Uint8Array(buffer) - // var log = foreign.log - var pushInt = foreign.pushInt - var pushInt32 = foreign.pushInt32 - var pushInt32Neg = foreign.pushInt32Neg - var pushInt64 = foreign.pushInt64 - var pushInt64Neg = foreign.pushInt64Neg - var pushFloat = foreign.pushFloat - var pushFloatSingle = foreign.pushFloatSingle - var pushFloatDouble = foreign.pushFloatDouble - var pushTrue = foreign.pushTrue - var pushFalse = foreign.pushFalse - var pushUndefined = foreign.pushUndefined - var pushNull = foreign.pushNull - var pushInfinity = foreign.pushInfinity - var pushInfinityNeg = foreign.pushInfinityNeg - var pushNaN = foreign.pushNaN - var pushNaNNeg = foreign.pushNaNNeg - - var pushArrayStart = foreign.pushArrayStart - var pushArrayStartFixed = foreign.pushArrayStartFixed - var pushArrayStartFixed32 = foreign.pushArrayStartFixed32 - var pushArrayStartFixed64 = foreign.pushArrayStartFixed64 - var pushObjectStart = foreign.pushObjectStart - var pushObjectStartFixed = foreign.pushObjectStartFixed - var pushObjectStartFixed32 = foreign.pushObjectStartFixed32 - var pushObjectStartFixed64 = foreign.pushObjectStartFixed64 - - var pushByteString = foreign.pushByteString - var pushByteStringStart = foreign.pushByteStringStart - var pushUtf8String = foreign.pushUtf8String - var pushUtf8StringStart = foreign.pushUtf8StringStart - - var pushSimpleUnassigned = foreign.pushSimpleUnassigned - - var pushTagStart = foreign.pushTagStart - var pushTagStart4 = foreign.pushTagStart4 - var pushTagStart8 = foreign.pushTagStart8 - var pushTagUnassigned = foreign.pushTagUnassigned - - var pushBreak = foreign.pushBreak - - var pow = stdlib.Math.pow - - // -- Constants - - - // -- Mutable Variables - - var offset = 0 - var inputLength = 0 - var code = 0 - - // Decode a cbor string represented as Uint8Array - // which is allocated on the heap from 0 to inputLength - // - // input - Int - // - // Returns Code - Int, - // Success = 0 - // Error > 0 - function parse (input) { - input = input | 0 - - offset = 0 - inputLength = input - - while ((offset | 0) < (inputLength | 0)) { - code = jumpTable[heap[offset] & 255](heap[offset] | 0) | 0 - - if ((code | 0) > 0) { - break - } - } - - return code | 0 - } - - // -- Helper Function - - function checkOffset (n) { - n = n | 0 - - if ((((offset | 0) + (n | 0)) | 0) < (inputLength | 0)) { - return 0 - } - - return 1 - } - - function readUInt16 (n) { - n = n | 0 - - return ( - (heap[n | 0] << 8) | heap[(n + 1) | 0] - ) | 0 - } - - // -- Initial Byte Handlers - - function INT_P (octet) { - octet = octet | 0 - - pushInt(octet | 0) - - offset = (offset + 1) | 0 - - return 0 - } - - function UINT_P_8 (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 - } - - pushInt(heap[(offset + 1) | 0] | 0) - - offset = (offset + 2) | 0 - - return 0 - } - - function UINT_P_16 (octet) { - octet = octet | 0 - - if (checkOffset(2) | 0) { - return 1 - } - - pushInt( - readUInt16((offset + 1) | 0) | 0 - ) - - offset = (offset + 3) | 0 - - return 0 - } - - function UINT_P_32 (octet) { - octet = octet | 0 - - if (checkOffset(4) | 0) { - return 1 - } - - pushInt32( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) - - offset = (offset + 5) | 0 - - return 0 - } - - function UINT_P_64 (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } - - pushInt64( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) - - offset = (offset + 9) | 0 - - return 0 - } - - function INT_N (octet) { - octet = octet | 0 - - pushInt((-1 - ((octet - 32) | 0)) | 0) - - offset = (offset + 1) | 0 - - return 0 - } - - function UINT_N_8 (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 - } - - pushInt( - (-1 - (heap[(offset + 1) | 0] | 0)) | 0 - ) - - offset = (offset + 2) | 0 - - return 0 - } - - function UINT_N_16 (octet) { - octet = octet | 0 - - var val = 0 - - if (checkOffset(2) | 0) { - return 1 - } - - val = readUInt16((offset + 1) | 0) | 0 - pushInt((-1 - (val | 0)) | 0) - - offset = (offset + 3) | 0 - - return 0 - } - - function UINT_N_32 (octet) { - octet = octet | 0 - - if (checkOffset(4) | 0) { - return 1 - } - - pushInt32Neg( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) - - offset = (offset + 5) | 0 - - return 0 - } - - function UINT_N_64 (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } - - pushInt64Neg( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) - - offset = (offset + 9) | 0 - - return 0 - } - - function BYTE_STRING (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var step = 0 - - step = (octet - 64) | 0 - - if (checkOffset(step | 0) | 0) { - return 1 - } - - start = (offset + 1) | 0 - end = (((offset + 1) | 0) + (step | 0)) | 0 - - pushByteString(start | 0, end | 0) - - offset = end | 0 - - return 0 - } - - function BYTE_STRING_8 (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var length = 0 - - if (checkOffset(1) | 0) { - return 1 - } - - length = heap[(offset + 1) | 0] | 0 - start = (offset + 2) | 0 - end = (((offset + 2) | 0) + (length | 0)) | 0 - - if (checkOffset((length + 1) | 0) | 0) { - return 1 - } - - pushByteString(start | 0, end | 0) - - offset = end | 0 - - return 0 - } - - function BYTE_STRING_16 (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var length = 0 - - if (checkOffset(2) | 0) { - return 1 - } - - length = readUInt16((offset + 1) | 0) | 0 - start = (offset + 3) | 0 - end = (((offset + 3) | 0) + (length | 0)) | 0 - - - if (checkOffset((length + 2) | 0) | 0) { - return 1 - } - - pushByteString(start | 0, end | 0) - - offset = end | 0 - - return 0 - } - - function BYTE_STRING_32 (octet) { - octet = octet | 0 - - return 1 - } - - function BYTE_STRING_64 (octet) { - octet = octet | 0 - - return 1 - } - - function BYTE_STRING_BREAK (octet) { - octet = octet | 0 - - pushByteStringStart() - - offset = (offset + 1) | 0 - - return 0 - } - - function UTF8_STRING (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var step = 0 - - step = (octet - 96) | 0 - - if (checkOffset(step | 0) | 0) { - return 1 - } - - start = (offset + 1) | 0 - end = (((offset + 1) | 0) + (step | 0)) | 0 - - pushUtf8String(start | 0, end | 0) - - offset = end | 0 - - return 0 - } - - function UTF8_STRING_8 (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var length = 0 - - if (checkOffset(1) | 0) { - return 1 - } - - length = heap[(offset + 1) | 0] | 0 - start = (offset + 2) | 0 - end = (((offset + 2) | 0) + (length | 0)) | 0 - - if (checkOffset((length + 1) | 0) | 0) { - return 1 - } - - pushUtf8String(start | 0, end | 0) - - offset = end | 0 - - return 0 - } - - function UTF8_STRING_16 (octet) { - octet = octet | 0 - - var start = 0 - var end = 0 - var length = 0 - - if (checkOffset(2) | 0) { - return 1 - } - - length = readUInt16((offset + 1) | 0) | 0 - start = (offset + 3) | 0 - end = (((offset + 3) | 0) + (length | 0)) | 0 - - if (checkOffset((length + 2) | 0) | 0) { - return 1 - } - - pushUtf8String(start | 0, end | 0) - - offset = end | 0 - - return 0 - } - - function UTF8_STRING_32 (octet) { - octet = octet | 0 - - return 1 - } - - function UTF8_STRING_64 (octet) { - octet = octet | 0 - - return 1 - } - - function UTF8_STRING_BREAK (octet) { - octet = octet | 0 - - pushUtf8StringStart() - - offset = (offset + 1) | 0 - - return 0 - } - - function ARRAY (octet) { - octet = octet | 0 - - pushArrayStartFixed((octet - 128) | 0) - - offset = (offset + 1) | 0 - - return 0 - } - - function ARRAY_8 (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 - } - - pushArrayStartFixed(heap[(offset + 1) | 0] | 0) - - offset = (offset + 2) | 0 - - return 0 - } - - function ARRAY_16 (octet) { - octet = octet | 0 - - if (checkOffset(2) | 0) { - return 1 - } - - pushArrayStartFixed( - readUInt16((offset + 1) | 0) | 0 - ) - - offset = (offset + 3) | 0 - - return 1 - } - - function ARRAY_32 (octet) { - octet = octet | 0 - - if (checkOffset(4) | 0) { - return 1 - } - - pushArrayStartFixed32( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) - - offset = (offset + 5) | 0 - - return 0 - } - - function ARRAY_64 (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } - - pushArrayStartFixed64( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) - - offset = (offset + 9) | 0 - - return 0 - } - - function ARRAY_BREAK (octet) { - octet = octet | 0 - - pushArrayStart() - - offset = (offset + 1) | 0 - - return 0 - } - - function MAP (octet) { - octet = octet | 0 - - var step = 0 - - step = (octet - 160) | 0 - - if (checkOffset(step | 0) | 0) { - return 1 - } - - pushObjectStartFixed(step | 0) - - offset = (offset + 1) | 0 - - return 0 - } - - function MAP_8 (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 - } - - pushObjectStartFixed(heap[(offset + 1) | 0] | 0) - - offset = (offset + 2) | 0 - - return 0 - } - - function MAP_16 (octet) { - octet = octet | 0 - - if (checkOffset(2) | 0) { - return 1 - } - - pushObjectStartFixed( - readUInt16((offset + 1) | 0) | 0 - ) - - offset = (offset + 3) | 0 - - return 0 - } - - function MAP_32 (octet) { - octet = octet | 0 - - if (checkOffset(4) | 0) { - return 1 - } - - pushObjectStartFixed32( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) - - offset = (offset + 5) | 0 - - return 0 - } - - function MAP_64 (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } - - pushObjectStartFixed64( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) - - offset = (offset + 9) | 0 - - return 0 - } - - function MAP_BREAK (octet) { - octet = octet | 0 - - pushObjectStart() - - offset = (offset + 1) | 0 - - return 0 - } - - function TAG_KNOWN (octet) { - octet = octet | 0 - - pushTagStart((octet - 192| 0) | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_BIGNUM_POS (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_BIGNUM_NEG (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_FRAC (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_BIGNUM_FLOAT (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_UNASSIGNED (octet) { - octet = octet | 0 - - pushTagStart((octet - 192| 0) | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_BASE64_URL (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_BASE64 (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_BASE16 (octet) { - octet = octet | 0 - - pushTagStart(octet | 0) - - offset = (offset + 1 | 0) - - return 0 - } - - function TAG_MORE_1 (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 - } - - pushTagStart(heap[(offset + 1) | 0] | 0) - - offset = (offset + 2 | 0) - - return 0 - } - - function TAG_MORE_2 (octet) { - octet = octet | 0 - - if (checkOffset(2) | 0) { - return 1 - } - - pushTagStart( - readUInt16((offset + 1) | 0) | 0 - ) - - offset = (offset + 3 | 0) - - return 0 - } - - function TAG_MORE_4 (octet) { - octet = octet | 0 - - if (checkOffset(4) | 0) { - return 1 - } - - pushTagStart4( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0 - ) - - offset = (offset + 5 | 0) - - return 0 - } - - function TAG_MORE_8 (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } - - pushTagStart8( - readUInt16((offset + 1) | 0) | 0, - readUInt16((offset + 3) | 0) | 0, - readUInt16((offset + 5) | 0) | 0, - readUInt16((offset + 7) | 0) | 0 - ) - - offset = (offset + 9 | 0) - - return 0 - } - - function SIMPLE_UNASSIGNED (octet) { - octet = octet | 0 - - pushSimpleUnassigned(((octet | 0) - 224) | 0) - - offset = (offset + 1) | 0 - - return 0 - } - - function SIMPLE_FALSE (octet) { - octet = octet | 0 - - pushFalse() - - offset = (offset + 1) | 0 - - return 0 - } - - function SIMPLE_TRUE (octet) { - octet = octet | 0 - - pushTrue() - - offset = (offset + 1) | 0 - - return 0 - } - - function SIMPLE_NULL (octet) { - octet = octet | 0 - - pushNull() - - offset = (offset + 1) | 0 - - return 0 - } - - function SIMPLE_UNDEFINED (octet) { - octet = octet | 0 - - pushUndefined() - - offset = (offset + 1) | 0 - - return 0 - } - - function SIMPLE_BYTE (octet) { - octet = octet | 0 - - if (checkOffset(1) | 0) { - return 1 - } - - pushSimpleUnassigned(heap[(offset + 1) | 0] | 0) - - offset = (offset + 2) | 0 - - return 0 - } - - function SIMPLE_FLOAT_HALF (octet) { - octet = octet | 0 - - var f = 0 - var g = 0 - var sign = 1.0 - var exp = 0.0 - var mant = 0.0 - var r = 0.0 - if (checkOffset(2) | 0) { - return 1 - } - - f = heap[(offset + 1) | 0] | 0 - g = heap[(offset + 2) | 0] | 0 - - if ((f | 0) & 0x80) { - sign = -1.0 - } - - exp = +(((f | 0) & 0x7C) >> 2) - mant = +((((f | 0) & 0x03) << 8) | g) - - if (+exp == 0.0) { - pushFloat(+( - (+sign) * +5.9604644775390625e-8 * (+mant) - )) - } else if (+exp == 31.0) { - if (+sign == 1.0) { - if (+mant > 0.0) { - pushNaN() - } else { - pushInfinity() - } - } else { - if (+mant > 0.0) { - pushNaNNeg() - } else { - pushInfinityNeg() - } - } - } else { - pushFloat(+( - +sign * pow(+2, +(+exp - 25.0)) * +(1024.0 + mant) - )) - } - - offset = (offset + 3) | 0 - - return 0 - } - - function SIMPLE_FLOAT_SINGLE (octet) { - octet = octet | 0 - - if (checkOffset(4) | 0) { - return 1 - } - - pushFloatSingle( - heap[(offset + 1) | 0] | 0, - heap[(offset + 2) | 0] | 0, - heap[(offset + 3) | 0] | 0, - heap[(offset + 4) | 0] | 0 - ) - - offset = (offset + 5) | 0 - - return 0 - } - - function SIMPLE_FLOAT_DOUBLE (octet) { - octet = octet | 0 - - if (checkOffset(8) | 0) { - return 1 - } - - pushFloatDouble( - heap[(offset + 1) | 0] | 0, - heap[(offset + 2) | 0] | 0, - heap[(offset + 3) | 0] | 0, - heap[(offset + 4) | 0] | 0, - heap[(offset + 5) | 0] | 0, - heap[(offset + 6) | 0] | 0, - heap[(offset + 7) | 0] | 0, - heap[(offset + 8) | 0] | 0 - ) - - offset = (offset + 9) | 0 - - return 0 - } - - function ERROR (octet) { - octet = octet | 0 - - return 1 - } - - function BREAK (octet) { - octet = octet | 0 - - pushBreak() - - offset = (offset + 1) | 0 - - return 0 - } - - // -- Jump Table - - var jumpTable = [ - // Integer 0x00..0x17 (0..23) - INT_P, // 0x00 - INT_P, // 0x01 - INT_P, // 0x02 - INT_P, // 0x03 - INT_P, // 0x04 - INT_P, // 0x05 - INT_P, // 0x06 - INT_P, // 0x07 - INT_P, // 0x08 - INT_P, // 0x09 - INT_P, // 0x0A - INT_P, // 0x0B - INT_P, // 0x0C - INT_P, // 0x0D - INT_P, // 0x0E - INT_P, // 0x0F - INT_P, // 0x10 - INT_P, // 0x11 - INT_P, // 0x12 - INT_P, // 0x13 - INT_P, // 0x14 - INT_P, // 0x15 - INT_P, // 0x16 - INT_P, // 0x17 - // Unsigned integer (one-byte uint8_t follows) - UINT_P_8, // 0x18 - // Unsigned integer (two-byte uint16_t follows) - UINT_P_16, // 0x19 - // Unsigned integer (four-byte uint32_t follows) - UINT_P_32, // 0x1a - // Unsigned integer (eight-byte uint64_t follows) - UINT_P_64, // 0x1b - ERROR, // 0x1c - ERROR, // 0x1d - ERROR, // 0x1e - ERROR, // 0x1f - // Negative integer -1-0x00..-1-0x17 (-1..-24) - INT_N, // 0x20 - INT_N, // 0x21 - INT_N, // 0x22 - INT_N, // 0x23 - INT_N, // 0x24 - INT_N, // 0x25 - INT_N, // 0x26 - INT_N, // 0x27 - INT_N, // 0x28 - INT_N, // 0x29 - INT_N, // 0x2A - INT_N, // 0x2B - INT_N, // 0x2C - INT_N, // 0x2D - INT_N, // 0x2E - INT_N, // 0x2F - INT_N, // 0x30 - INT_N, // 0x31 - INT_N, // 0x32 - INT_N, // 0x33 - INT_N, // 0x34 - INT_N, // 0x35 - INT_N, // 0x36 - INT_N, // 0x37 - // Negative integer -1-n (one-byte uint8_t for n follows) - UINT_N_8, // 0x38 - // Negative integer -1-n (two-byte uint16_t for n follows) - UINT_N_16, // 0x39 - // Negative integer -1-n (four-byte uint32_t for nfollows) - UINT_N_32, // 0x3a - // Negative integer -1-n (eight-byte uint64_t for n follows) - UINT_N_64, // 0x3b - ERROR, // 0x3c - ERROR, // 0x3d - ERROR, // 0x3e - ERROR, // 0x3f - // byte string (0x00..0x17 bytes follow) - BYTE_STRING, // 0x40 - BYTE_STRING, // 0x41 - BYTE_STRING, // 0x42 - BYTE_STRING, // 0x43 - BYTE_STRING, // 0x44 - BYTE_STRING, // 0x45 - BYTE_STRING, // 0x46 - BYTE_STRING, // 0x47 - BYTE_STRING, // 0x48 - BYTE_STRING, // 0x49 - BYTE_STRING, // 0x4A - BYTE_STRING, // 0x4B - BYTE_STRING, // 0x4C - BYTE_STRING, // 0x4D - BYTE_STRING, // 0x4E - BYTE_STRING, // 0x4F - BYTE_STRING, // 0x50 - BYTE_STRING, // 0x51 - BYTE_STRING, // 0x52 - BYTE_STRING, // 0x53 - BYTE_STRING, // 0x54 - BYTE_STRING, // 0x55 - BYTE_STRING, // 0x56 - BYTE_STRING, // 0x57 - // byte string (one-byte uint8_t for n, and then n bytes follow) - BYTE_STRING_8, // 0x58 - // byte string (two-byte uint16_t for n, and then n bytes follow) - BYTE_STRING_16, // 0x59 - // byte string (four-byte uint32_t for n, and then n bytes follow) - BYTE_STRING_32, // 0x5a - // byte string (eight-byte uint64_t for n, and then n bytes follow) - BYTE_STRING_64, // 0x5b - ERROR, // 0x5c - ERROR, // 0x5d - ERROR, // 0x5e - // byte string, byte strings follow, terminated by "break" - BYTE_STRING_BREAK, // 0x5f - // UTF-8 string (0x00..0x17 bytes follow) - UTF8_STRING, // 0x60 - UTF8_STRING, // 0x61 - UTF8_STRING, // 0x62 - UTF8_STRING, // 0x63 - UTF8_STRING, // 0x64 - UTF8_STRING, // 0x65 - UTF8_STRING, // 0x66 - UTF8_STRING, // 0x67 - UTF8_STRING, // 0x68 - UTF8_STRING, // 0x69 - UTF8_STRING, // 0x6A - UTF8_STRING, // 0x6B - UTF8_STRING, // 0x6C - UTF8_STRING, // 0x6D - UTF8_STRING, // 0x6E - UTF8_STRING, // 0x6F - UTF8_STRING, // 0x70 - UTF8_STRING, // 0x71 - UTF8_STRING, // 0x72 - UTF8_STRING, // 0x73 - UTF8_STRING, // 0x74 - UTF8_STRING, // 0x75 - UTF8_STRING, // 0x76 - UTF8_STRING, // 0x77 - // UTF-8 string (one-byte uint8_t for n, and then n bytes follow) - UTF8_STRING_8, // 0x78 - // UTF-8 string (two-byte uint16_t for n, and then n bytes follow) - UTF8_STRING_16, // 0x79 - // UTF-8 string (four-byte uint32_t for n, and then n bytes follow) - UTF8_STRING_32, // 0x7a - // UTF-8 string (eight-byte uint64_t for n, and then n bytes follow) - UTF8_STRING_64, // 0x7b - // UTF-8 string, UTF-8 strings follow, terminated by "break" - ERROR, // 0x7c - ERROR, // 0x7d - ERROR, // 0x7e - UTF8_STRING_BREAK, // 0x7f - // array (0x00..0x17 data items follow) - ARRAY, // 0x80 - ARRAY, // 0x81 - ARRAY, // 0x82 - ARRAY, // 0x83 - ARRAY, // 0x84 - ARRAY, // 0x85 - ARRAY, // 0x86 - ARRAY, // 0x87 - ARRAY, // 0x88 - ARRAY, // 0x89 - ARRAY, // 0x8A - ARRAY, // 0x8B - ARRAY, // 0x8C - ARRAY, // 0x8D - ARRAY, // 0x8E - ARRAY, // 0x8F - ARRAY, // 0x90 - ARRAY, // 0x91 - ARRAY, // 0x92 - ARRAY, // 0x93 - ARRAY, // 0x94 - ARRAY, // 0x95 - ARRAY, // 0x96 - ARRAY, // 0x97 - // array (one-byte uint8_t fo, and then n data items follow) - ARRAY_8, // 0x98 - // array (two-byte uint16_t for n, and then n data items follow) - ARRAY_16, // 0x99 - // array (four-byte uint32_t for n, and then n data items follow) - ARRAY_32, // 0x9a - // array (eight-byte uint64_t for n, and then n data items follow) - ARRAY_64, // 0x9b - // array, data items follow, terminated by "break" - ERROR, // 0x9c - ERROR, // 0x9d - ERROR, // 0x9e - ARRAY_BREAK, // 0x9f - // map (0x00..0x17 pairs of data items follow) - MAP, // 0xa0 - MAP, // 0xa1 - MAP, // 0xa2 - MAP, // 0xa3 - MAP, // 0xa4 - MAP, // 0xa5 - MAP, // 0xa6 - MAP, // 0xa7 - MAP, // 0xa8 - MAP, // 0xa9 - MAP, // 0xaA - MAP, // 0xaB - MAP, // 0xaC - MAP, // 0xaD - MAP, // 0xaE - MAP, // 0xaF - MAP, // 0xb0 - MAP, // 0xb1 - MAP, // 0xb2 - MAP, // 0xb3 - MAP, // 0xb4 - MAP, // 0xb5 - MAP, // 0xb6 - MAP, // 0xb7 - // map (one-byte uint8_t for n, and then n pairs of data items follow) - MAP_8, // 0xb8 - // map (two-byte uint16_t for n, and then n pairs of data items follow) - MAP_16, // 0xb9 - // map (four-byte uint32_t for n, and then n pairs of data items follow) - MAP_32, // 0xba - // map (eight-byte uint64_t for n, and then n pairs of data items follow) - MAP_64, // 0xbb - ERROR, // 0xbc - ERROR, // 0xbd - ERROR, // 0xbe - // map, pairs of data items follow, terminated by "break" - MAP_BREAK, // 0xbf - // Text-based date/time (data item follows; see Section 2.4.1) - TAG_KNOWN, // 0xc0 - // Epoch-based date/time (data item follows; see Section 2.4.1) - TAG_KNOWN, // 0xc1 - // Positive bignum (data item "byte string" follows) - TAG_KNOWN, // 0xc2 - // Negative bignum (data item "byte string" follows) - TAG_KNOWN, // 0xc3 - // Decimal Fraction (data item "array" follows; see Section 2.4.3) - TAG_KNOWN, // 0xc4 - // Bigfloat (data item "array" follows; see Section 2.4.3) - TAG_KNOWN, // 0xc5 - // (tagged item) - TAG_UNASSIGNED, // 0xc6 - TAG_UNASSIGNED, // 0xc7 - TAG_UNASSIGNED, // 0xc8 - TAG_UNASSIGNED, // 0xc9 - TAG_UNASSIGNED, // 0xca - TAG_UNASSIGNED, // 0xcb - TAG_UNASSIGNED, // 0xcc - TAG_UNASSIGNED, // 0xcd - TAG_UNASSIGNED, // 0xce - TAG_UNASSIGNED, // 0xcf - TAG_UNASSIGNED, // 0xd0 - TAG_UNASSIGNED, // 0xd1 - TAG_UNASSIGNED, // 0xd2 - TAG_UNASSIGNED, // 0xd3 - TAG_UNASSIGNED, // 0xd4 - // Expected Conversion (data item follows; see Section 2.4.4.2) - TAG_UNASSIGNED, // 0xd5 - TAG_UNASSIGNED, // 0xd6 - TAG_UNASSIGNED, // 0xd7 - // (more tagged items, 1/2/4/8 bytes and then a data item follow) - TAG_MORE_1, // 0xd8 - TAG_MORE_2, // 0xd9 - TAG_MORE_4, // 0xda - TAG_MORE_8, // 0xdb - ERROR, // 0xdc - ERROR, // 0xdd - ERROR, // 0xde - ERROR, // 0xdf - // (simple value) - SIMPLE_UNASSIGNED, // 0xe0 - SIMPLE_UNASSIGNED, // 0xe1 - SIMPLE_UNASSIGNED, // 0xe2 - SIMPLE_UNASSIGNED, // 0xe3 - SIMPLE_UNASSIGNED, // 0xe4 - SIMPLE_UNASSIGNED, // 0xe5 - SIMPLE_UNASSIGNED, // 0xe6 - SIMPLE_UNASSIGNED, // 0xe7 - SIMPLE_UNASSIGNED, // 0xe8 - SIMPLE_UNASSIGNED, // 0xe9 - SIMPLE_UNASSIGNED, // 0xea - SIMPLE_UNASSIGNED, // 0xeb - SIMPLE_UNASSIGNED, // 0xec - SIMPLE_UNASSIGNED, // 0xed - SIMPLE_UNASSIGNED, // 0xee - SIMPLE_UNASSIGNED, // 0xef - SIMPLE_UNASSIGNED, // 0xf0 - SIMPLE_UNASSIGNED, // 0xf1 - SIMPLE_UNASSIGNED, // 0xf2 - SIMPLE_UNASSIGNED, // 0xf3 - // False - SIMPLE_FALSE, // 0xf4 - // True - SIMPLE_TRUE, // 0xf5 - // Null - SIMPLE_NULL, // 0xf6 - // Undefined - SIMPLE_UNDEFINED, // 0xf7 - // (simple value, one byte follows) - SIMPLE_BYTE, // 0xf8 - // Half-Precision Float (two-byte IEEE 754) - SIMPLE_FLOAT_HALF, // 0xf9 - // Single-Precision Float (four-byte IEEE 754) - SIMPLE_FLOAT_SINGLE, // 0xfa - // Double-Precision Float (eight-byte IEEE 754) - SIMPLE_FLOAT_DOUBLE, // 0xfb - ERROR, // 0xfc - ERROR, // 0xfd - ERROR, // 0xfe - // "break" stop code - BREAK // 0xff - ] - - // -- - - return { - parse: parse - } -} - -},{}],69:[function(require,module,exports){ -(function (global,Buffer){ -'use strict' - -const ieee754 = require('ieee754') -const Bignumber = require('bignumber.js') - -const parser = require('./decoder.asm') -const utils = require('./utils') -const c = require('./constants') -const Simple = require('./simple') -const Tagged = require('./tagged') -const url = require('url') - -/** - * Transform binary cbor data into JavaScript objects. - */ -class Decoder { - /** - * @param {Object} [opts={}] - * @param {number} [opts.size=65536] - Size of the allocated heap. - */ - constructor (opts) { - opts = opts || {} - - if (!opts.size || opts.size < 0x10000) { - opts.size = 0x10000 - } else { - // Ensure the size is a power of 2 - opts.size = utils.nextPowerOf2(opts.size) - } - - // Heap use to share the input with the parser - this._heap = new ArrayBuffer(opts.size) - this._heap8 = new Uint8Array(this._heap) - - this._reset() - - // Known tags - this._knownTags = Object.assign({ - 0: (val) => new Date(val), - 1: (val) => new Date(val * 1000), - 2: (val) => utils.arrayBufferToBignumber(val), - 3: (val) => c.NEG_ONE.minus(utils.arrayBufferToBignumber(val)), - 4: (v) => { - // const v = new Uint8Array(val) - return c.TEN.pow(v[0]).times(v[1]) - }, - 5: (v) => { - // const v = new Uint8Array(val) - return c.TWO.pow(v[0]).times(v[1]) - }, - 32: (val) => url.parse(val), - 35: (val) => new RegExp(val) - }, opts.tags) - - // Initialize asm based parser - this.parser = parser(global, { - log: console.log.bind(console), - pushInt: this.pushInt.bind(this), - pushInt32: this.pushInt32.bind(this), - pushInt32Neg: this.pushInt32Neg.bind(this), - pushInt64: this.pushInt64.bind(this), - pushInt64Neg: this.pushInt64Neg.bind(this), - pushFloat: this.pushFloat.bind(this), - pushFloatSingle: this.pushFloatSingle.bind(this), - pushFloatDouble: this.pushFloatDouble.bind(this), - pushTrue: this.pushTrue.bind(this), - pushFalse: this.pushFalse.bind(this), - pushUndefined: this.pushUndefined.bind(this), - pushNull: this.pushNull.bind(this), - pushInfinity: this.pushInfinity.bind(this), - pushInfinityNeg: this.pushInfinityNeg.bind(this), - pushNaN: this.pushNaN.bind(this), - pushNaNNeg: this.pushNaNNeg.bind(this), - pushArrayStart: this.pushArrayStart.bind(this), - pushArrayStartFixed: this.pushArrayStartFixed.bind(this), - pushArrayStartFixed32: this.pushArrayStartFixed32.bind(this), - pushArrayStartFixed64: this.pushArrayStartFixed64.bind(this), - pushObjectStart: this.pushObjectStart.bind(this), - pushObjectStartFixed: this.pushObjectStartFixed.bind(this), - pushObjectStartFixed32: this.pushObjectStartFixed32.bind(this), - pushObjectStartFixed64: this.pushObjectStartFixed64.bind(this), - pushByteString: this.pushByteString.bind(this), - pushByteStringStart: this.pushByteStringStart.bind(this), - pushUtf8String: this.pushUtf8String.bind(this), - pushUtf8StringStart: this.pushUtf8StringStart.bind(this), - pushSimpleUnassigned: this.pushSimpleUnassigned.bind(this), - pushTagUnassigned: this.pushTagUnassigned.bind(this), - pushTagStart: this.pushTagStart.bind(this), - pushTagStart4: this.pushTagStart4.bind(this), - pushTagStart8: this.pushTagStart8.bind(this), - pushBreak: this.pushBreak.bind(this) - }, this._heap) - } - - get _depth () { - return this._parents.length - } - - get _currentParent () { - return this._parents[this._depth - 1] - } - - get _ref () { - return this._currentParent.ref - } - - // Finish the current parent - _closeParent () { - var p = this._parents.pop() - - if (p.length > 0) { - throw new Error(`Missing ${p.length} elements`) - } - - switch (p.type) { - case c.PARENT.TAG: - this._push( - this.createTag(p.ref[0], p.ref[1]) - ) - break - case c.PARENT.BYTE_STRING: - this._push(this.createByteString(p.ref, p.length)) - break - case c.PARENT.UTF8_STRING: - this._push(this.createUtf8String(p.ref, p.length)) - break - case c.PARENT.MAP: - if (p.values % 2 > 0) { - throw new Error('Odd number of elements in the map') - } - this._push(this.createMap(p.ref, p.length)) - break - case c.PARENT.OBJECT: - if (p.values % 2 > 0) { - throw new Error('Odd number of elements in the map') - } - this._push(this.createObject(p.ref, p.length)) - break - case c.PARENT.ARRAY: - this._push(this.createArray(p.ref, p.length)) - break - default: - break - } - - if (this._currentParent && this._currentParent.type === c.PARENT.TAG) { - this._dec() - } - } - - // Reduce the expected length of the current parent by one - _dec () { - const p = this._currentParent - // The current parent does not know the epxected child length - - if (p.length < 0) { - return - } - - p.length -- - - // All children were seen, we can close the current parent - if (p.length === 0) { - this._closeParent() - } - } - - // Push any value to the current parent - _push (val, hasChildren) { - const p = this._currentParent - p.values ++ - - switch (p.type) { - case c.PARENT.ARRAY: - case c.PARENT.BYTE_STRING: - case c.PARENT.UTF8_STRING: - if (p.length > -1) { - this._ref[this._ref.length - p.length] = val - } else { - this._ref.push(val) - } - this._dec() - break - case c.PARENT.OBJECT: - if (p.tmpKey != null) { - this._ref[p.tmpKey] = val - p.tmpKey = null - this._dec() - } else { - p.tmpKey = val - - if (typeof p.tmpKey !== 'string') { - // too bad, convert to a Map - p.type = c.PARENT.MAP - p.ref = utils.buildMap(p.ref) - } - } - break - case c.PARENT.MAP: - if (p.tmpKey != null) { - this._ref.set(p.tmpKey, val) - p.tmpKey = null - this._dec() - } else { - p.tmpKey = val - } - break - case c.PARENT.TAG: - this._ref.push(val) - if (!hasChildren) { - this._dec() - } - break - default: - throw new Error('Unknown parent type') - } - } - - // Create a new parent in the parents list - _createParent (obj, type, len) { - this._parents[this._depth] = { - type: type, - length: len, - ref: obj, - values: 0, - tmpKey: null - } - } - - // Reset all state back to the beginning, also used for initiatlization - _reset () { - this._res = [] - this._parents = [{ - type: c.PARENT.ARRAY, - length: -1, - ref: this._res, - values: 0, - tmpKey: null - }] - } - - // -- Interface to customize deoding behaviour - createTag (tagNumber, value) { - const typ = this._knownTags[tagNumber] - - if (!typ) { - return new Tagged(tagNumber, value) - } - - return typ(value) - } - - createMap (obj, len) { - return obj - } - - createObject (obj, len) { - return obj - } - - createArray (arr, len) { - return arr - } - - createByteString (raw, len) { - return Buffer.concat(raw) - } - - createByteStringFromHeap (start, end) { - if (start === end) { - return new Buffer(0) - } - - return new Buffer(this._heap.slice(start, end)) - } - - createInt (val) { - return val - } - - createInt32 (f, g) { - return utils.buildInt32(f, g) - } - - createInt64 (f1, f2, g1, g2) { - return utils.buildInt64(f1, f2, g1, g2) - } - - createFloat (val) { - return val - } - - createFloatSingle (a, b, c, d) { - return ieee754.read([a, b, c, d], 0, false, 23, 4) - } - - createFloatDouble (a, b, c, d, e, f, g, h) { - return ieee754.read([a, b, c, d, e, f, g, h], 0, false, 52, 8) - } - - createInt32Neg (f, g) { - return -1 - utils.buildInt32(f, g) - } - - createInt64Neg (f1, f2, g1, g2) { - const f = utils.buildInt32(f1, f2) - const g = utils.buildInt32(g1, g2) - - if (f > c.MAX_SAFE_HIGH) { - return c.NEG_ONE.sub(new Bignumber(f).times(c.SHIFT32).plus(g)) - } - - return -1 - ((f * c.SHIFT32) + g) - } - - createTrue () { - return true - } - - createFalse () { - return false - } - - createNull () { - return null - } - - createUndefined () { - return void 0 - } - - createInfinity () { - return Infinity - } - - createInfinityNeg () { - return -Infinity - } - - createNaN () { - return NaN - } - - createNaNNeg () { - return -NaN - } - - createUtf8String (raw, len) { - return raw.join('') - } - - createUtf8StringFromHeap (start, end) { - if (start === end) { - return '' - } - - return ( - new Buffer(this._heap.slice(start, end)) - ).toString('utf8') - } - - createSimpleUnassigned (val) { - return new Simple(val) - } - - // -- Interface for decoder.asm.js - - pushInt (val) { - this._push(this.createInt(val)) - } - - pushInt32 (f, g) { - this._push(this.createInt32(f, g)) - } - - pushInt64 (f1, f2, g1, g2) { - this._push(this.createInt64(f1, f2, g1, g2)) - } - - pushFloat (val) { - this._push(this.createFloat(val)) - } - - pushFloatSingle (a, b, c, d) { - this._push(this.createFloatSingle(a, b, c, d)) - } - - pushFloatDouble (a, b, c, d, e, f, g, h) { - this._push(this.createFloatDouble(a, b, c, d, e, f, g, h)) - } - - pushInt32Neg (f, g) { - this._push(this.createInt32Neg(f, g)) - } - - pushInt64Neg (f1, f2, g1, g2) { - this._push(this.createInt64Neg(f1, f2, g1, g2)) - } - - pushTrue () { - this._push(this.createTrue()) - } - - pushFalse () { - this._push(this.createFalse()) - } - - pushNull () { - this._push(this.createNull()) - } - - pushUndefined () { - this._push(this.createUndefined()) - } - - pushInfinity () { - this._push(this.createInfinity()) - } - - pushInfinityNeg () { - this._push(this.createInfinityNeg()) - } - - pushNaN () { - this._push(this.createNaN()) - } - - pushNaNNeg () { - this._push(this.createNaNNeg()) - } - - pushArrayStart () { - this._createParent([], c.PARENT.ARRAY, -1) - } - - pushArrayStartFixed (len) { - this._createArrayStartFixed(len) - } - - pushArrayStartFixed32 (len1, len2) { - const len = utils.buildInt32(len1, len2) - this._createArrayStartFixed(len) - } - - pushArrayStartFixed64 (len1, len2, len3, len4) { - const len = utils.buildInt64(len1, len2, len3, len4) - this._createArrayStartFixed(len) - } - - pushObjectStart () { - this._createObjectStartFixed(-1) - } - - pushObjectStartFixed (len) { - this._createObjectStartFixed(len) - } - - pushObjectStartFixed32 (len1, len2) { - const len = utils.buildInt32(len1, len2) - this._createObjectStartFixed(len) - } - - pushObjectStartFixed64 (len1, len2, len3, len4) { - const len = utils.buildInt64(len1, len2, len3, len4) - this._createObjectStartFixed(len) - } - - pushByteStringStart () { - this._parents[this._depth] = { - type: c.PARENT.BYTE_STRING, - length: -1, - ref: [], - values: 0, - tmpKey: null - } - } - - pushByteString (start, end) { - this._push(this.createByteStringFromHeap(start, end)) - } - - pushUtf8StringStart () { - this._parents[this._depth] = { - type: c.PARENT.UTF8_STRING, - length: -1, - ref: [], - values: 0, - tmpKey: null - } - } - - pushUtf8String (start, end) { - this._push(this.createUtf8StringFromHeap(start, end)) - } - - pushSimpleUnassigned (val) { - this._push(this.createSimpleUnassigned(val)) - } - - pushTagStart (tag) { - this._parents[this._depth] = { - type: c.PARENT.TAG, - length: 1, - ref: [tag] - } - } - - pushTagStart4 (f, g) { - this.pushTagStart(utils.buildInt32(f, g)) - } - - pushTagStart8 (f1, f2, g1, g2) { - this.pushTagStart(utils.buildInt64(f1, f2, g1, g2)) - } - - pushTagUnassigned (tagNumber) { - this._push(this.createTag(tagNumber)) - } - - pushBreak () { - if (this._currentParent.length > -1) { - throw new Error('Unexpected break') - } - - this._closeParent() - } - - _createObjectStartFixed (len) { - if (len === 0) { - this._push(this.createObject({})) - return - } - - this._createParent({}, c.PARENT.OBJECT, len) - } - - _createArrayStartFixed (len) { - if (len === 0) { - this._push(this.createArray([])) - return - } - - this._createParent(new Array(len), c.PARENT.ARRAY, len) - } - - _decode (input) { - if (input.byteLength === 0) { - throw new Error('Input too short') - } - - this._reset() - this._heap8.set(input) - const code = this.parser.parse(input.byteLength) - - if (this._depth > 1) { - while (this._currentParent.length === 0) { - this._closeParent() - } - if (this._depth > 1) { - throw new Error('Undeterminated nesting') - } - } - - if (code > 0) { - throw new Error('Failed to parse') - } - - if (this._res.length === 0) { - throw new Error('No valid result') - } - } - - // -- Public Interface - - decodeFirst (input) { - this._decode(input) - - return this._res[0] - } - - decodeAll (input) { - this._decode(input) - - return this._res - } - - /** - * Decode the first cbor object. - * - * @param {Buffer|string} input - * @param {string} [enc='hex'] - Encoding used if a string is passed. - * @returns {*} - */ - static decode (input, enc) { - if (typeof input === 'string') { - input = new Buffer(input, enc || 'hex') - } - - const dec = new Decoder({size: input.length}) - return dec.decodeFirst(input) - } - - /** - * Decode all cbor objects. - * - * @param {Buffer|string} input - * @param {string} [enc='hex'] - Encoding used if a string is passed. - * @returns {Array<*>} - */ - static decodeAll (input, enc) { - if (typeof input === 'string') { - input = new Buffer(input, enc || 'hex') - } - - const dec = new Decoder({size: input.length}) - return dec.decodeAll(input) - } -} - -Decoder.decodeFirst = Decoder.decode - -module.exports = Decoder - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer) -},{"./constants":67,"./decoder.asm":68,"./simple":73,"./tagged":74,"./utils":75,"bignumber.js":60,"buffer":987,"ieee754":209,"url":1031}],70:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const Decoder = require('./decoder') -const utils = require('./utils') - -/** - * Output the diagnostic format from a stream of CBOR bytes. - * - */ -class Diagnose extends Decoder { - createTag (tagNumber, value) { - return `${tagNumber}(${value})` - } - - createInt (val) { - return super.createInt(val).toString() - } - - createInt32 (f, g) { - return super.createInt32(f, g).toString() - } - - createInt64 (f1, f2, g1, g2) { - return super.createInt64(f1, f2, g1, g2).toString() - } - - createInt32Neg (f, g) { - return super.createInt32Neg(f, g).toString() - } - - createInt64Neg (f1, f2, g1, g2) { - return super.createInt64Neg(f1, f2, g1, g2).toString() - } - - createTrue () { - return 'true' - } - - createFalse () { - return 'false' - } - - createFloat (val) { - const fl = super.createFloat(val) - if (utils.isNegativeZero(val)) { - return '-0_1' - } - - return `${fl}_1` - } - - createFloatSingle (a, b, c, d) { - const fl = super.createFloatSingle(a, b, c, d) - return `${fl}_2` - } - - createFloatDouble (a, b, c, d, e, f, g, h) { - const fl = super.createFloatDouble(a, b, c, d, e, f, g, h) - return `${fl}_3` - } - - createByteString (raw, len) { - const val = raw.join(', ') - - if (len === -1) { - return `(_ ${val})` - } - return `h'${val}` - } - - createByteStringFromHeap (start, end) { - const val = (new Buffer( - super.createByteStringFromHeap(start, end) - )).toString('hex') - - return `h'${val}'` - } - - createInfinity () { - return 'Infinity_1' - } - - createInfinityNeg () { - return '-Infinity_1' - } - - createNaN () { - return 'NaN_1' - } - - createNaNNeg () { - return '-NaN_1' - } - - createNull () { - return 'null' - } - - createUndefined () { - return 'undefined' - } - - createSimpleUnassigned (val) { - return `simple(${val})` - } - - createArray (arr, len) { - const val = super.createArray(arr, len) - - if (len === -1) { - // indefinite - return `[_ ${val.join(', ')}]` - } - - return `[${val.join(', ')}]` - } - - createMap (map, len) { - const val = super.createMap(map) - const list = Array.from(val.keys()) - .reduce(collectObject(val), '') - - if (len === -1) { - return `{_ ${list}}` - } - - return `{${list}}` - } - - createObject (obj, len) { - const val = super.createObject(obj) - const map = Object.keys(val) - .reduce(collectObject(val), '') - - if (len === -1) { - return `{_ ${map}}` - } - - return `{${map}}` - } - - createUtf8String (raw, len) { - const val = raw.join(', ') - - if (len === -1) { - return `(_ ${val})` - } - - return `"${val}"` - } - - createUtf8StringFromHeap (start, end) { - const val = (new Buffer( - super.createUtf8StringFromHeap(start, end) - )).toString('utf8') - - return `"${val}"` - } - - static diagnose (input, enc) { - if (typeof input === 'string') { - input = new Buffer(input, enc || 'hex') - } - - const dec = new Diagnose() - return dec.decodeFirst(input) - } -} - -module.exports = Diagnose - -function collectObject (val) { - return (acc, key) => { - if (acc) { - return `${acc}, ${key}: ${val[key]}` - } - return `${key}: ${val[key]}` - } -} - -}).call(this,require("buffer").Buffer) -},{"./decoder":69,"./utils":75,"buffer":987}],71:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const url = require('url') -const Bignumber = require('bignumber.js') - -const utils = require('./utils') -const constants = require('./constants') -const MT = constants.MT -const NUMBYTES = constants.NUMBYTES -const SHIFT32 = constants.SHIFT32 -const SYMS = constants.SYMS -const TAG = constants.TAG -const HALF = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.TWO -const FLOAT = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.FOUR -const DOUBLE = (constants.MT.SIMPLE_FLOAT << 5) | constants.NUMBYTES.EIGHT -const TRUE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.TRUE -const FALSE = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.FALSE -const UNDEFINED = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.UNDEFINED -const NULL = (constants.MT.SIMPLE_FLOAT << 5) | constants.SIMPLE.NULL - -const MAXINT_BN = new Bignumber('0x20000000000000') -const BUF_NAN = new Buffer('f97e00', 'hex') -const BUF_INF_NEG = new Buffer('f9fc00', 'hex') -const BUF_INF_POS = new Buffer('f97c00', 'hex') - -function toType (obj) { - // [object Type] - // --------8---1 - return ({}).toString.call(obj).slice(8, -1) -} - -/** - * Transform JavaScript values into CBOR bytes - * - */ -class Encoder { - /** - * @param {Object} [options={}] - * @param {function(Buffer)} options.stream - */ - constructor (options) { - options = options || {} - - this.streaming = typeof options.stream === 'function' - this.onData = options.stream - - this.semanticTypes = [ - [url.Url, this._pushUrl], - [Bignumber, this._pushBigNumber] - ] - - const addTypes = options.genTypes || [] - const len = addTypes.length - for (let i = 0; i < len; i++) { - this.addSemanticType( - addTypes[i][0], - addTypes[i][1] - ) - } - - this._reset() - } - - addSemanticType (type, fun) { - const len = this.semanticTypes.length - for (let i = 0; i < len; i++) { - const typ = this.semanticTypes[i][0] - if (typ === type) { - const old = this.semanticTypes[i][1] - this.semanticTypes[i][1] = fun - return old - } - } - this.semanticTypes.push([type, fun]) - return null - } - - push (val) { - if (!val) { - return true - } - - this.result[this.offset] = val - this.resultMethod[this.offset] = 0 - this.resultLength[this.offset] = val.length - this.offset ++ - - if (this.streaming) { - this.onData(this.finalize()) - } - - return true - } - - pushWrite (val, method, len) { - this.result[this.offset] = val - this.resultMethod[this.offset] = method - this.resultLength[this.offset] = len - this.offset ++ - - if (this.streaming) { - this.onData(this.finalize()) - } - - return true - } - - _pushUInt8 (val) { - return this.pushWrite(val, 1, 1) - } - - _pushUInt16BE (val) { - return this.pushWrite(val, 2, 2) - } - - _pushUInt32BE (val) { - return this.pushWrite(val, 3, 4) - } - - _pushDoubleBE (val) { - return this.pushWrite(val, 4, 8) - } - - _pushNaN () { - return this.push(BUF_NAN) - } - - _pushInfinity (obj) { - const half = (obj < 0) ? BUF_INF_NEG : BUF_INF_POS - return this.push(half) - } - - _pushFloat (obj) { - const b2 = new Buffer(2) - - if (utils.writeHalf(b2, obj)) { - if (utils.parseHalf(b2) === obj) { - return this._pushUInt8(HALF) && this.push(b2) - } - } - - const b4 = new Buffer(4) - b4.writeFloatBE(obj, 0) - if (b4.readFloatBE(0) === obj) { - return this._pushUInt8(FLOAT) && this.push(b4) - } - - return this._pushUInt8(DOUBLE) && this._pushDoubleBE(obj) - } - - _pushInt (obj, mt, orig) { - const m = mt << 5 - if (obj < 24) { - return this._pushUInt8(m | obj) - } - - if (obj <= 0xff) { - return this._pushUInt8(m | NUMBYTES.ONE) && this._pushUInt8(obj) - } - - if (obj <= 0xffff) { - return this._pushUInt8(m | NUMBYTES.TWO) && this._pushUInt16BE(obj) - } - - if (obj <= 0xffffffff) { - return this._pushUInt8(m | NUMBYTES.FOUR) && this._pushUInt32BE(obj) - } - - if (obj <= Number.MAX_SAFE_INTEGER) { - return this._pushUInt8(m | NUMBYTES.EIGHT) && - this._pushUInt32BE(Math.floor(obj / SHIFT32)) && - this._pushUInt32BE(obj % SHIFT32) - } - - if (mt === MT.NEG_INT) { - return this._pushFloat(orig) - } - - return this._pushFloat(obj) - } - - _pushIntNum (obj) { - if (obj < 0) { - return this._pushInt(-obj - 1, MT.NEG_INT, obj) - } else { - return this._pushInt(obj, MT.POS_INT) - } - } - - _pushNumber (obj) { - switch (false) { - case (obj === obj): // eslint-disable-line - return this._pushNaN(obj) - case isFinite(obj): - return this._pushInfinity(obj) - case ((obj % 1) !== 0): - return this._pushIntNum(obj) - default: - return this._pushFloat(obj) - } - } - - _pushString (obj) { - const len = Buffer.byteLength(obj, 'utf8') - return this._pushInt(len, MT.UTF8_STRING) && this.pushWrite(obj, 5, len) - } - - _pushBoolean (obj) { - return this._pushUInt8(obj ? TRUE : FALSE) - } - - _pushUndefined (obj) { - return this._pushUInt8(UNDEFINED) - } - - _pushArray (gen, obj) { - const len = obj.length - if (!gen._pushInt(len, MT.ARRAY)) { - return false - } - for (let j = 0; j < len; j++) { - if (!gen.pushAny(obj[j])) { - return false - } - } - return true - } - - _pushTag (tag) { - return this._pushInt(tag, MT.TAG) - } - - _pushDate (gen, obj) { - return gen._pushTag(TAG.DATE_EPOCH) && gen.pushAny(obj / 1000) - } - - _pushBuffer (gen, obj) { - return gen._pushInt(obj.length, MT.BYTE_STRING) && gen.push(obj) - } - - _pushNoFilter (gen, obj) { - return gen._pushBuffer(gen, obj.slice()) - } - - _pushRegexp (gen, obj) { - return gen._pushTag(TAG.REGEXP) && gen.pushAny(obj.source) - } - - _pushSet (gen, obj) { - if (!gen._pushInt(obj.size, MT.ARRAY)) { - return false - } - for (let x of obj) { - if (!gen.pushAny(x)) { - return false - } - } - return true - } - - _pushUrl (gen, obj) { - return gen._pushTag(TAG.URI) && gen.pushAny(obj.format()) - } - - _pushBigint (obj) { - let tag = TAG.POS_BIGINT - if (obj.isNegative()) { - obj = obj.negated().minus(1) - tag = TAG.NEG_BIGINT - } - let str = obj.toString(16) - if (str.length % 2) { - str = '0' + str - } - const buf = new Buffer(str, 'hex') - return this._pushTag(tag) && this._pushBuffer(this, buf) - } - - _pushBigNumber (gen, obj) { - if (obj.isNaN()) { - return gen._pushNaN() - } - if (!obj.isFinite()) { - return gen._pushInfinity(obj.isNegative() ? -Infinity : Infinity) - } - if (obj.isInteger()) { - return gen._pushBigint(obj) - } - if (!(gen._pushTag(TAG.DECIMAL_FRAC) && - gen._pushInt(2, MT.ARRAY))) { - return false - } - - const dec = obj.decimalPlaces() - const slide = obj.mul(new Bignumber(10).pow(dec)) - if (!gen._pushIntNum(-dec)) { - return false - } - if (slide.abs().lessThan(MAXINT_BN)) { - return gen._pushIntNum(slide.toNumber()) - } else { - return gen._pushBigint(slide) - } - } - - _pushMap (gen, obj) { - if (!gen._pushInt(obj.size, MT.MAP)) { - return false - } - - return this._pushRawMap( - obj.size, - Array.from(obj) - ) - } - - _pushObject (obj) { - if (!obj) { - return this._pushUInt8(NULL) - } - - var len = this.semanticTypes.length - for (var i = 0; i < len; i++) { - if (obj instanceof this.semanticTypes[i][0]) { - return this.semanticTypes[i][1].call(obj, this, obj) - } - } - - var f = obj.encodeCBOR - if (typeof f === 'function') { - return f.call(obj, this) - } - - var keys = Object.keys(obj) - var keyLength = keys.length - if (!this._pushInt(keyLength, MT.MAP)) { - return false - } - - return this._pushRawMap( - keyLength, - keys.map((k) => [k, obj[k]]) - ) - } - - _pushRawMap (len, map) { - // Sort keys for canoncialization - // 1. encode key - // 2. shorter key comes before longer key - // 3. same length keys are sorted with lower - // byte value before higher - - map = map.map(function (a) { - a[0] = Encoder.encode(a[0]) - return a - }).sort(utils.keySorter) - - for (var j = 0; j < len; j++) { - if (!this.push(map[j][0])) { - return false - } - - if (!this.pushAny(map[j][1])) { - return false - } - } - - return true - } - - /** - * Alias for `.pushAny` - * - * @param {*} obj - * @returns {undefind} - */ - write (obj) { - this.pushAny(obj) - } - - /** - * Push any supported type onto the encoded stream - * - * @param {any} obj - * @returns {boolean} true on success - */ - pushAny (obj) { - var typ = toType(obj) - - switch (typ) { - case 'Number': - return this._pushNumber(obj) - case 'String': - return this._pushString(obj) - case 'Boolean': - return this._pushBoolean(obj) - case 'Object': - return this._pushObject(obj) - case 'Array': - return this._pushArray(this, obj) - case 'Uint8Array': - return this._pushBuffer(this, obj) - case 'Null': - return this._pushUInt8(NULL) - case 'Undefined': - return this._pushUndefined(obj) - case 'Map': - return this._pushMap(this, obj) - case 'Set': - return this._pushSet(this, obj) - case 'Date': - return this._pushDate(this, obj) - case 'RegExp': - return this._pushRegexp(this, obj) - case 'Symbol': - switch (obj) { - case SYMS.NULL: - return this._pushObject(null) - case SYMS.UNDEFINED: - return this._pushUndefined(void 0) - // TODO: Add pluggable support for other symbols - default: - throw new Error('Unknown symbol: ' + obj.toString()) - } - default: - throw new Error('Unknown type: ' + typeof obj + ', ' + (obj ? obj.toString() : '')) - } - } - - finalize () { - if (this.offset === 0) { - return null - } - - var result = this.result - var resultLength = this.resultLength - var resultMethod = this.resultMethod - var offset = this.offset - - // Determine the size of the buffer - var size = 0 - var i = 0 - - for (; i < offset; i++) { - size += resultLength[i] - } - - var res = Buffer.allocUnsafe(size) - var index = 0 - var length = 0 - - // Write the content into the result buffer - for (i = 0; i < offset; i++) { - length = resultLength[i] - - switch (resultMethod[i]) { - case 0: - result[i].copy(res, index) - break - case 1: - res.writeUInt8(result[i], index, true) - break - case 2: - res.writeUInt16BE(result[i], index, true) - break - case 3: - res.writeUInt32BE(result[i], index, true) - break - case 4: - res.writeDoubleBE(result[i], index, true) - break - case 5: - res.write(result[i], index, length, 'utf8') - break - default: - throw new Error('unkown method') - } - - index += length - } - - var tmp = res - - this._reset() - - return tmp - } - - _reset () { - this.result = [] - this.resultMethod = [] - this.resultLength = [] - this.offset = 0 - } - - /** - * Encode the given value - * @param {*} o - * @returns {Buffer} - */ - static encode (o) { - const enc = new Encoder() - enc.pushAny(o) - - return enc.finalize() - } -} - -module.exports = Encoder - -}).call(this,require("buffer").Buffer) -},{"./constants":67,"./utils":75,"bignumber.js":60,"buffer":987,"url":1031}],72:[function(require,module,exports){ -'use strict' - -// exports.Commented = require('./commented') -exports.Diagnose = require('./diagnose') -exports.Decoder = require('./decoder') -exports.Encoder = require('./encoder') -exports.Simple = require('./simple') -exports.Tagged = require('./tagged') - -// exports.comment = exports.Commented.comment -exports.decodeAll = exports.Decoder.decodeAll -exports.decodeFirst = exports.Decoder.decodeFirst -exports.diagnose = exports.Diagnose.diagnose -exports.encode = exports.Encoder.encode -exports.decode = exports.Decoder.decode - -exports.leveldb = { - decode: exports.Decoder.decodeAll, - encode: exports.Encoder.encode, - buffer: true, - name: 'cbor' -} - -},{"./decoder":69,"./diagnose":70,"./encoder":71,"./simple":73,"./tagged":74}],73:[function(require,module,exports){ -'use strict' - -const constants = require('./constants') -const MT = constants.MT -const SIMPLE = constants.SIMPLE -const SYMS = constants.SYMS - -/** - * A CBOR Simple Value that does not map onto a known constant. - */ -class Simple { - /** - * Creates an instance of Simple. - * - * @param {integer} value - the simple value's integer value - */ - constructor (value) { - if (typeof value !== 'number') { - throw new Error('Invalid Simple type: ' + (typeof value)) - } - if ((value < 0) || (value > 255) || ((value | 0) !== value)) { - throw new Error('value must be a small positive integer: ' + value) - } - this.value = value - } - - /** - * Debug string for simple value - * - * @returns {string} simple(value) - */ - toString () { - return 'simple(' + this.value + ')' - } - - /** - * Debug string for simple value - * - * @returns {string} simple(value) - */ - inspect () { - return 'simple(' + this.value + ')' - } - - /** - * Push the simple value onto the CBOR stream - * - * @param {cbor.Encoder} gen The generator to push onto - * @returns {number} - */ - encodeCBOR (gen) { - return gen._pushInt(this.value, MT.SIMPLE_FLOAT) - } - - /** - * Is the given object a Simple? - * - * @param {any} obj - object to test - * @returns {bool} - is it Simple? - */ - static isSimple (obj) { - return obj instanceof Simple - } - - /** - * Decode from the CBOR additional information into a JavaScript value. - * If the CBOR item has no parent, return a "safe" symbol instead of - * `null` or `undefined`, so that the value can be passed through a - * stream in object mode. - * - * @param {Number} val - the CBOR additional info to convert - * @param {bool} hasParent - Does the CBOR item have a parent? - * @returns {(null|undefined|Boolean|Symbol)} - the decoded value - */ - static decode (val, hasParent) { - if (hasParent == null) { - hasParent = true - } - switch (val) { - case SIMPLE.FALSE: - return false - case SIMPLE.TRUE: - return true - case SIMPLE.NULL: - if (hasParent) { - return null - } else { - return SYMS.NULL - } - case SIMPLE.UNDEFINED: - if (hasParent) { - return void 0 - } else { - return SYMS.UNDEFINED - } - case -1: - if (!hasParent) { - throw new Error('Invalid BREAK') - } - return SYMS.BREAK - default: - return new Simple(val) - } - } -} - -module.exports = Simple - -},{"./constants":67}],74:[function(require,module,exports){ -'use strict' - -/** - * A CBOR tagged item, where the tag does not have semantics specified at the - * moment, or those semantics threw an error during parsing. Typically this will - * be an extension point you're not yet expecting. - */ -class Tagged { - - /** - * Creates an instance of Tagged. - * - * @param {Number} tag - the number of the tag - * @param {any} value - the value inside the tag - * @param {Error} err - the error that was thrown parsing the tag, or null - */ - constructor (tag, value, err) { - this.tag = tag - this.value = value - this.err = err - if (typeof this.tag !== 'number') { - throw new Error('Invalid tag type (' + (typeof this.tag) + ')') - } - if ((this.tag < 0) || ((this.tag | 0) !== this.tag)) { - throw new Error('Tag must be a positive integer: ' + this.tag) - } - } - - /** - * Convert to a String - * - * @returns {String} string of the form '1(2)' - */ - toString () { - return `${this.tag}(${JSON.stringify(this.value)})` - } - - /** - * Push the simple value onto the CBOR stream - * - * @param {cbor.Encoder} gen The generator to push onto - * @returns {number} - */ - encodeCBOR (gen) { - gen._pushTag(this.tag) - return gen.pushAny(this.value) - } - - /** - * If we have a converter for this type, do the conversion. Some converters - * are built-in. Additional ones can be passed in. If you want to remove - * a built-in converter, pass a converter in whose value is 'null' instead - * of a function. - * - * @param {Object} converters - keys in the object are a tag number, the value - * is a function that takes the decoded CBOR and returns a JavaScript value - * of the appropriate type. Throw an exception in the function on errors. - * @returns {any} - the converted item - */ - convert (converters) { - var er, f - f = converters != null ? converters[this.tag] : void 0 - if (typeof f !== 'function') { - f = Tagged['_tag' + this.tag] - if (typeof f !== 'function') { - return this - } - } - try { - return f.call(Tagged, this.value) - } catch (error) { - er = error - this.err = er - return this - } - } -} - -module.exports = Tagged - -},{}],75:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const Bignumber = require('bignumber.js') - -const constants = require('./constants') -const SHIFT32 = constants.SHIFT32 -const SHIFT16 = constants.SHIFT16 -const MAX_SAFE_HIGH = 0x1fffff - -exports.parseHalf = function parseHalf (buf) { - var exp, mant, sign - sign = buf[0] & 0x80 ? -1 : 1 - exp = (buf[0] & 0x7C) >> 2 - mant = ((buf[0] & 0x03) << 8) | buf[1] - if (!exp) { - return sign * 5.9604644775390625e-8 * mant - } else if (exp === 0x1f) { - return sign * (mant ? 0 / 0 : 2e308) - } else { - return sign * Math.pow(2, exp - 25) * (1024 + mant) - } -} - -function toHex (n) { - if (n < 16) { - return '0' + n.toString(16) - } - - return n.toString(16) -} - -exports.arrayBufferToBignumber = function (buf) { - const len = buf.byteLength - let res = '' - for (let i = 0; i < len; i++) { - res += toHex(buf[i]) - } - - return new Bignumber(res, 16) -} - -// convert an Object into a Map -exports.buildMap = (obj) => { - const res = new Map() - const keys = Object.keys(obj) - const length = keys.length - for (let i = 0; i < length; i++) { - res.set(keys[i], obj[keys[i]]) - } - return res -} - -exports.buildInt32 = (f, g) => { - return f * SHIFT16 + g -} - -exports.buildInt64 = (f1, f2, g1, g2) => { - const f = exports.buildInt32(f1, f2) - const g = exports.buildInt32(g1, g2) - - if (f > MAX_SAFE_HIGH) { - return new Bignumber(f).times(SHIFT32).plus(g) - } else { - return (f * SHIFT32) + g - } -} - -exports.writeHalf = function writeHalf (buf, half) { - // assume 0, -0, NaN, Infinity, and -Infinity have already been caught - - // HACK: everyone settle in. This isn't going to be pretty. - // Translate cn-cbor's C code (from Carsten Borman): - - // uint32_t be32; - // uint16_t be16, u16; - // union { - // float f; - // uint32_t u; - // } u32; - // u32.f = float_val; - - const u32 = new Buffer(4) - u32.writeFloatBE(half, 0) - const u = u32.readUInt32BE(0) - - // if ((u32.u & 0x1FFF) == 0) { /* worth trying half */ - - // hildjj: If the lower 13 bits are 0, we won't lose anything in the conversion - if ((u & 0x1FFF) !== 0) { - return false - } - - // int s16 = (u32.u >> 16) & 0x8000; - // int exp = (u32.u >> 23) & 0xff; - // int mant = u32.u & 0x7fffff; - - var s16 = (u >> 16) & 0x8000 // top bit is sign - const exp = (u >> 23) & 0xff // then 5 bits of exponent - const mant = u & 0x7fffff - - // if (exp == 0 && mant == 0) - // ; /* 0.0, -0.0 */ - - // hildjj: zeros already handled. Assert if you don't believe me. - - // else if (exp >= 113 && exp <= 142) /* normalized */ - // s16 += ((exp - 112) << 10) + (mant >> 13); - if ((exp >= 113) && (exp <= 142)) { - s16 += ((exp - 112) << 10) + (mant >> 13) - - // else if (exp >= 103 && exp < 113) { /* denorm, exp16 = 0 */ - // if (mant & ((1 << (126 - exp)) - 1)) - // goto float32; /* loss of precision */ - // s16 += ((mant + 0x800000) >> (126 - exp)); - } else if ((exp >= 103) && (exp < 113)) { - if (mant & ((1 << (126 - exp)) - 1)) { - return false - } - s16 += ((mant + 0x800000) >> (126 - exp)) - - // } else if (exp == 255 && mant == 0) { /* Inf */ - // s16 += 0x7c00; - - // hildjj: Infinity already handled - - // } else - // goto float32; /* loss of range */ - } else { - return false - } - - // ensure_writable(3); - // u16 = s16; - // be16 = hton16p((const uint8_t*)&u16); - buf.writeUInt16BE(s16, 0) - return true -} - -exports.keySorter = function (a, b) { - var lenA = a[0].byteLength - var lenB = b[0].byteLength - - if (lenA > lenB) { - return 1 - } - - if (lenB > lenA) { - return -1 - } - - return a[0].compare(b[0]) -} - -// Adapted from http://www.2ality.com/2012/03/signedzero.html -exports.isNegativeZero = (x) => { - return x === 0 && (1 / x < 0) -} - -exports.nextPowerOf2 = (n) => { - let count = 0 - // First n in the below condition is for - // the case where n is 0 - if (n && !(n & (n - 1))) { - return n - } - - while (n !== 0) { - n >>= 1 - count += 1 - } - - return 1 << count -} - -}).call(this,require("buffer").Buffer) -},{"./constants":67,"bignumber.js":60,"buffer":987}],76:[function(require,module,exports){ -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 = require('crypto'); - if (typeof crypto.randomBytes !== 'function') - throw new Error('Not supported'); - - Rand.prototype._rand = function _rand(n) { - return crypto.randomBytes(n); - }; - } catch (e) { - } -} - -},{"crypto":984}],77:[function(require,module,exports){ -(function (Buffer){ -// based on the aes implimentation in triple sec -// https://github.com/keybase/triplesec - -// which is in turn based on the one from crypto-js -// https://code.google.com/p/crypto-js/ - -var uint_max = Math.pow(2, 32) -function fixup_uint32 (x) { - var ret, x_pos - ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x - return ret -} -function scrub_vec (v) { - for (var i = 0; i < v.length; v++) { - v[i] = 0 - } - return false -} - -function Global () { - this.SBOX = [] - this.INV_SBOX = [] - this.SUB_MIX = [[], [], [], []] - this.INV_SUB_MIX = [[], [], [], []] - this.init() - this.RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] -} - -Global.prototype.init = function () { - var d, i, sx, t, x, x2, x4, x8, xi, _i - d = (function () { - var _i, _results - _results = [] - for (i = _i = 0; _i < 256; i = ++_i) { - if (i < 128) { - _results.push(i << 1) - } else { - _results.push((i << 1) ^ 0x11b) - } - } - return _results - })() - x = 0 - xi = 0 - for (i = _i = 0; _i < 256; i = ++_i) { - sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) - sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 - this.SBOX[x] = sx - this.INV_SBOX[sx] = x - x2 = d[x] - x4 = d[x2] - x8 = d[x4] - t = (d[sx] * 0x101) ^ (sx * 0x1010100) - this.SUB_MIX[0][x] = (t << 24) | (t >>> 8) - this.SUB_MIX[1][x] = (t << 16) | (t >>> 16) - this.SUB_MIX[2][x] = (t << 8) | (t >>> 24) - this.SUB_MIX[3][x] = t - t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) - this.INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) - this.INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) - this.INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) - this.INV_SUB_MIX[3][sx] = t - if (x === 0) { - x = xi = 1 - } else { - x = x2 ^ d[d[d[x8 ^ x2]]] - xi ^= d[d[xi]] - } - } - return true -} - -var G = new Global() - -AES.blockSize = 4 * 4 - -AES.prototype.blockSize = AES.blockSize - -AES.keySize = 256 / 8 - -AES.prototype.keySize = AES.keySize - -function bufferToArray (buf) { - var len = buf.length / 4 - var out = new Array(len) - var i = -1 - while (++i < len) { - out[i] = buf.readUInt32BE(i * 4) - } - return out -} -function AES (key) { - this._key = bufferToArray(key) - this._doReset() -} - -AES.prototype._doReset = function () { - var invKsRow, keySize, keyWords, ksRow, ksRows, t - keyWords = this._key - keySize = keyWords.length - this._nRounds = keySize + 6 - ksRows = (this._nRounds + 1) * 4 - this._keySchedule = [] - for (ksRow = 0; ksRow < ksRows; ksRow++) { - this._keySchedule[ksRow] = ksRow < keySize ? keyWords[ksRow] : (t = this._keySchedule[ksRow - 1], (ksRow % keySize) === 0 ? (t = (t << 8) | (t >>> 24), t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff], t ^= G.RCON[(ksRow / keySize) | 0] << 24) : keySize > 6 && ksRow % keySize === 4 ? t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | G.SBOX[t & 0xff] : void 0, this._keySchedule[ksRow - keySize] ^ t) - } - this._invKeySchedule = [] - for (invKsRow = 0; invKsRow < ksRows; invKsRow++) { - ksRow = ksRows - invKsRow - t = this._keySchedule[ksRow - (invKsRow % 4 ? 0 : 4)] - this._invKeySchedule[invKsRow] = invKsRow < 4 || ksRow <= 4 ? t : G.INV_SUB_MIX[0][G.SBOX[t >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(t >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(t >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[t & 0xff]] - } - return true -} - -AES.prototype.encryptBlock = function (M) { - M = bufferToArray(new Buffer(M)) - var out = this._doCryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX) - var buf = new Buffer(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[1], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[3], 12) - return buf -} - -AES.prototype.decryptBlock = function (M) { - M = bufferToArray(new Buffer(M)) - var temp = [M[3], M[1]] - M[1] = temp[0] - M[3] = temp[1] - var out = this._doCryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX) - var buf = new Buffer(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[3], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[1], 12) - return buf -} - -AES.prototype.scrub = function () { - scrub_vec(this._keySchedule) - scrub_vec(this._invKeySchedule) - scrub_vec(this._key) -} - -AES.prototype._doCryptBlock = function (M, keySchedule, SUB_MIX, SBOX) { - var ksRow, s0, s1, s2, s3, t0, t1, t2, t3 - - s0 = M[0] ^ keySchedule[0] - s1 = M[1] ^ keySchedule[1] - s2 = M[2] ^ keySchedule[2] - s3 = M[3] ^ keySchedule[3] - ksRow = 4 - for (var round = 1; round < this._nRounds; round++) { - t0 = SUB_MIX[0][s0 >>> 24] ^ SUB_MIX[1][(s1 >>> 16) & 0xff] ^ SUB_MIX[2][(s2 >>> 8) & 0xff] ^ SUB_MIX[3][s3 & 0xff] ^ keySchedule[ksRow++] - t1 = SUB_MIX[0][s1 >>> 24] ^ SUB_MIX[1][(s2 >>> 16) & 0xff] ^ SUB_MIX[2][(s3 >>> 8) & 0xff] ^ SUB_MIX[3][s0 & 0xff] ^ keySchedule[ksRow++] - t2 = SUB_MIX[0][s2 >>> 24] ^ SUB_MIX[1][(s3 >>> 16) & 0xff] ^ SUB_MIX[2][(s0 >>> 8) & 0xff] ^ SUB_MIX[3][s1 & 0xff] ^ keySchedule[ksRow++] - t3 = SUB_MIX[0][s3 >>> 24] ^ SUB_MIX[1][(s0 >>> 16) & 0xff] ^ SUB_MIX[2][(s1 >>> 8) & 0xff] ^ SUB_MIX[3][s2 & 0xff] ^ keySchedule[ksRow++] - s0 = t0 - s1 = t1 - s2 = t2 - s3 = t3 - } - t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] - t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] - t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] - t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] - return [ - fixup_uint32(t0), - fixup_uint32(t1), - fixup_uint32(t2), - fixup_uint32(t3) - ] -} - -exports.AES = AES - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],78:[function(require,module,exports){ -(function (Buffer){ -var aes = require('./aes') -var Transform = require('cipher-base') -var inherits = require('inherits') -var GHASH = require('./ghash') -var xor = require('buffer-xor') -inherits(StreamCipher, Transform) -module.exports = StreamCipher - -function StreamCipher (mode, key, iv, decrypt) { - if (!(this instanceof StreamCipher)) { - return new StreamCipher(mode, key, iv) - } - Transform.call(this) - this._finID = Buffer.concat([iv, new Buffer([0, 0, 0, 1])]) - iv = Buffer.concat([iv, new Buffer([0, 0, 0, 2])]) - this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - this._cache = new Buffer('') - this._secCache = new Buffer('') - this._decrypt = decrypt - this._alen = 0 - this._len = 0 - iv.copy(this._prev) - this._mode = mode - var h = new Buffer(4) - h.fill(0) - this._ghash = new GHASH(this._cipher.encryptBlock(h)) - this._authTag = null - this._called = false -} -StreamCipher.prototype._update = function (chunk) { - if (!this._called && this._alen) { - var rump = 16 - (this._alen % 16) - if (rump < 16) { - rump = new Buffer(rump) - rump.fill(0) - this._ghash.update(rump) - } - } - this._called = true - var out = this._mode.encrypt(this, chunk) - if (this._decrypt) { - this._ghash.update(chunk) - } else { - this._ghash.update(out) - } - this._len += chunk.length - return out -} -StreamCipher.prototype._final = function () { - if (this._decrypt && !this._authTag) { - throw new Error('Unsupported state or unable to authenticate data') - } - var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) - if (this._decrypt) { - if (xorTest(tag, this._authTag)) { - throw new Error('Unsupported state or unable to authenticate data') - } - } else { - this._authTag = tag - } - this._cipher.scrub() -} -StreamCipher.prototype.getAuthTag = function getAuthTag () { - if (!this._decrypt && Buffer.isBuffer(this._authTag)) { - return this._authTag - } else { - throw new Error('Attempting to get auth tag in unsupported state') - } -} -StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { - if (this._decrypt) { - this._authTag = tag - } else { - throw new Error('Attempting to set auth tag in unsupported state') - } -} -StreamCipher.prototype.setAAD = function setAAD (buf) { - if (!this._called) { - this._ghash.update(buf) - this._alen += buf.length - } else { - throw new Error('Attempting to set AAD in unsupported state') - } -} -function xorTest (a, b) { - var out = 0 - if (a.length !== b.length) { - out++ - } - var len = Math.min(a.length, b.length) - var i = -1 - while (++i < len) { - out += (a[i] ^ b[i]) - } - return out -} - -}).call(this,require("buffer").Buffer) -},{"./aes":77,"./ghash":82,"buffer":987,"buffer-xor":96,"cipher-base":98,"inherits":216}],79:[function(require,module,exports){ -var ciphers = require('./encrypter') -exports.createCipher = exports.Cipher = ciphers.createCipher -exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv -var deciphers = require('./decrypter') -exports.createDecipher = exports.Decipher = deciphers.createDecipher -exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv -var modes = require('./modes') -function getCiphers () { - return Object.keys(modes) -} -exports.listCiphers = exports.getCiphers = getCiphers - -},{"./decrypter":80,"./encrypter":81,"./modes":83}],80:[function(require,module,exports){ -(function (Buffer){ -var aes = require('./aes') -var Transform = require('cipher-base') -var inherits = require('inherits') -var modes = require('./modes') -var StreamCipher = require('./streamCipher') -var AuthCipher = require('./authCipher') -var ebtk = require('evp_bytestokey') - -inherits(Decipher, Transform) -function Decipher (mode, key, iv) { - if (!(this instanceof Decipher)) { - return new Decipher(mode, key, iv) - } - Transform.call(this) - this._cache = new Splitter() - this._last = void 0 - this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - iv.copy(this._prev) - this._mode = mode - this._autopadding = true -} -Decipher.prototype._update = function (data) { - this._cache.add(data) - var chunk - var thing - var out = [] - while ((chunk = this._cache.get(this._autopadding))) { - thing = this._mode.decrypt(this, chunk) - out.push(thing) - } - return Buffer.concat(out) -} -Decipher.prototype._final = function () { - var chunk = this._cache.flush() - if (this._autopadding) { - return unpad(this._mode.decrypt(this, chunk)) - } else if (chunk) { - throw new Error('data not multiple of block length') - } -} -Decipher.prototype.setAutoPadding = function (setTo) { - this._autopadding = !!setTo - return this -} -function Splitter () { - if (!(this instanceof Splitter)) { - return new Splitter() - } - this.cache = new Buffer('') -} -Splitter.prototype.add = function (data) { - this.cache = Buffer.concat([this.cache, data]) -} - -Splitter.prototype.get = function (autoPadding) { - var out - if (autoPadding) { - if (this.cache.length > 16) { - out = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - return out - } - } else { - if (this.cache.length >= 16) { - out = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - return out - } - } - return null -} -Splitter.prototype.flush = function () { - if (this.cache.length) { - return this.cache - } -} -function unpad (last) { - var padded = last[15] - var i = -1 - while (++i < padded) { - if (last[(i + (16 - padded))] !== padded) { - throw new Error('unable to decrypt data') - } - } - if (padded === 16) { - return - } - return last.slice(0, 16 - padded) -} - -var modelist = { - ECB: require('./modes/ecb'), - CBC: require('./modes/cbc'), - CFB: require('./modes/cfb'), - CFB8: require('./modes/cfb8'), - CFB1: require('./modes/cfb1'), - OFB: require('./modes/ofb'), - CTR: require('./modes/ctr'), - GCM: require('./modes/ctr') -} - -function createDecipheriv (suite, password, iv) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } - if (typeof iv === 'string') { - iv = new Buffer(iv) - } - if (typeof password === 'string') { - password = new Buffer(password) - } - if (password.length !== config.key / 8) { - throw new TypeError('invalid key length ' + password.length) - } - if (iv.length !== config.iv) { - throw new TypeError('invalid iv length ' + iv.length) - } - if (config.type === 'stream') { - return new StreamCipher(modelist[config.mode], password, iv, true) - } else if (config.type === 'auth') { - return new AuthCipher(modelist[config.mode], password, iv, true) - } - return new Decipher(modelist[config.mode], password, iv) -} - -function createDecipher (suite, password) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } - var keys = ebtk(password, false, config.key, config.iv) - return createDecipheriv(suite, keys.key, keys.iv) -} -exports.createDecipher = createDecipher -exports.createDecipheriv = createDecipheriv - -}).call(this,require("buffer").Buffer) -},{"./aes":77,"./authCipher":78,"./modes":83,"./modes/cbc":84,"./modes/cfb":85,"./modes/cfb1":86,"./modes/cfb8":87,"./modes/ctr":88,"./modes/ecb":89,"./modes/ofb":90,"./streamCipher":91,"buffer":987,"cipher-base":98,"evp_bytestokey":170,"inherits":216}],81:[function(require,module,exports){ -(function (Buffer){ -var aes = require('./aes') -var Transform = require('cipher-base') -var inherits = require('inherits') -var modes = require('./modes') -var ebtk = require('evp_bytestokey') -var StreamCipher = require('./streamCipher') -var AuthCipher = require('./authCipher') -inherits(Cipher, Transform) -function Cipher (mode, key, iv) { - if (!(this instanceof Cipher)) { - return new Cipher(mode, key, iv) - } - Transform.call(this) - this._cache = new Splitter() - this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - iv.copy(this._prev) - this._mode = mode - this._autopadding = true -} -Cipher.prototype._update = function (data) { - this._cache.add(data) - var chunk - var thing - var out = [] - while ((chunk = this._cache.get())) { - thing = this._mode.encrypt(this, chunk) - out.push(thing) - } - return Buffer.concat(out) -} -Cipher.prototype._final = function () { - var chunk = this._cache.flush() - if (this._autopadding) { - chunk = this._mode.encrypt(this, chunk) - this._cipher.scrub() - return chunk - } else if (chunk.toString('hex') !== '10101010101010101010101010101010') { - this._cipher.scrub() - throw new Error('data not multiple of block length') - } -} -Cipher.prototype.setAutoPadding = function (setTo) { - this._autopadding = !!setTo - return this -} - -function Splitter () { - if (!(this instanceof Splitter)) { - return new Splitter() - } - this.cache = new Buffer('') -} -Splitter.prototype.add = function (data) { - this.cache = Buffer.concat([this.cache, data]) -} - -Splitter.prototype.get = function () { - if (this.cache.length > 15) { - var out = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - return out - } - return null -} -Splitter.prototype.flush = function () { - var len = 16 - this.cache.length - var padBuff = new Buffer(len) - - var i = -1 - while (++i < len) { - padBuff.writeUInt8(len, i) - } - var out = Buffer.concat([this.cache, padBuff]) - return out -} -var modelist = { - ECB: require('./modes/ecb'), - CBC: require('./modes/cbc'), - CFB: require('./modes/cfb'), - CFB8: require('./modes/cfb8'), - CFB1: require('./modes/cfb1'), - OFB: require('./modes/ofb'), - CTR: require('./modes/ctr'), - GCM: require('./modes/ctr') -} - -function createCipheriv (suite, password, iv) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } - if (typeof iv === 'string') { - iv = new Buffer(iv) - } - if (typeof password === 'string') { - password = new Buffer(password) - } - if (password.length !== config.key / 8) { - throw new TypeError('invalid key length ' + password.length) - } - if (iv.length !== config.iv) { - throw new TypeError('invalid iv length ' + iv.length) - } - if (config.type === 'stream') { - return new StreamCipher(modelist[config.mode], password, iv) - } else if (config.type === 'auth') { - return new AuthCipher(modelist[config.mode], password, iv) - } - return new Cipher(modelist[config.mode], password, iv) -} -function createCipher (suite, password) { - var config = modes[suite.toLowerCase()] - if (!config) { - throw new TypeError('invalid suite type') - } - var keys = ebtk(password, false, config.key, config.iv) - return createCipheriv(suite, keys.key, keys.iv) -} - -exports.createCipheriv = createCipheriv -exports.createCipher = createCipher - -}).call(this,require("buffer").Buffer) -},{"./aes":77,"./authCipher":78,"./modes":83,"./modes/cbc":84,"./modes/cfb":85,"./modes/cfb1":86,"./modes/cfb8":87,"./modes/ctr":88,"./modes/ecb":89,"./modes/ofb":90,"./streamCipher":91,"buffer":987,"cipher-base":98,"evp_bytestokey":170,"inherits":216}],82:[function(require,module,exports){ -(function (Buffer){ -var zeros = new Buffer(16) -zeros.fill(0) -module.exports = GHASH -function GHASH (key) { - this.h = key - this.state = new Buffer(16) - this.state.fill(0) - this.cache = new Buffer('') -} -// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html -// by Juho Vähä-Herttua -GHASH.prototype.ghash = function (block) { - var i = -1 - while (++i < block.length) { - this.state[i] ^= block[i] - } - this._multiply() -} - -GHASH.prototype._multiply = function () { - var Vi = toArray(this.h) - var Zi = [0, 0, 0, 0] - var j, xi, lsb_Vi - var i = -1 - while (++i < 128) { - xi = (this.state[~~(i / 8)] & (1 << (7 - i % 8))) !== 0 - if (xi) { - // Z_i+1 = Z_i ^ V_i - Zi = xor(Zi, Vi) - } - - // Store the value of LSB(V_i) - lsb_Vi = (Vi[3] & 1) !== 0 - - // V_i+1 = V_i >> 1 - for (j = 3; j > 0; j--) { - Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) - } - Vi[0] = Vi[0] >>> 1 - - // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R - if (lsb_Vi) { - Vi[0] = Vi[0] ^ (0xe1 << 24) - } - } - this.state = fromArray(Zi) -} -GHASH.prototype.update = function (buf) { - this.cache = Buffer.concat([this.cache, buf]) - var chunk - while (this.cache.length >= 16) { - chunk = this.cache.slice(0, 16) - this.cache = this.cache.slice(16) - this.ghash(chunk) - } -} -GHASH.prototype.final = function (abl, bl) { - if (this.cache.length) { - this.ghash(Buffer.concat([this.cache, zeros], 16)) - } - this.ghash(fromArray([ - 0, abl, - 0, bl - ])) - return this.state -} - -function toArray (buf) { - return [ - buf.readUInt32BE(0), - buf.readUInt32BE(4), - buf.readUInt32BE(8), - buf.readUInt32BE(12) - ] -} -function fromArray (out) { - out = out.map(fixup_uint32) - var buf = new Buffer(16) - buf.writeUInt32BE(out[0], 0) - buf.writeUInt32BE(out[1], 4) - buf.writeUInt32BE(out[2], 8) - buf.writeUInt32BE(out[3], 12) - return buf -} -var uint_max = Math.pow(2, 32) -function fixup_uint32 (x) { - var ret, x_pos - ret = x > uint_max || x < 0 ? (x_pos = Math.abs(x) % uint_max, x < 0 ? uint_max - x_pos : x_pos) : x - return ret -} -function xor (a, b) { - return [ - a[0] ^ b[0], - a[1] ^ b[1], - a[2] ^ b[2], - a[3] ^ b[3] - ] -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],83:[function(require,module,exports){ -exports['aes-128-ecb'] = { - cipher: 'AES', - key: 128, - iv: 0, - mode: 'ECB', - type: 'block' -} -exports['aes-192-ecb'] = { - cipher: 'AES', - key: 192, - iv: 0, - mode: 'ECB', - type: 'block' -} -exports['aes-256-ecb'] = { - cipher: 'AES', - key: 256, - iv: 0, - mode: 'ECB', - type: 'block' -} -exports['aes-128-cbc'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CBC', - type: 'block' -} -exports['aes-192-cbc'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CBC', - type: 'block' -} -exports['aes-256-cbc'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CBC', - type: 'block' -} -exports['aes128'] = exports['aes-128-cbc'] -exports['aes192'] = exports['aes-192-cbc'] -exports['aes256'] = exports['aes-256-cbc'] -exports['aes-128-cfb'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CFB', - type: 'stream' -} -exports['aes-192-cfb'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CFB', - type: 'stream' -} -exports['aes-256-cfb'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CFB', - type: 'stream' -} -exports['aes-128-cfb8'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CFB8', - type: 'stream' -} -exports['aes-192-cfb8'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CFB8', - type: 'stream' -} -exports['aes-256-cfb8'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CFB8', - type: 'stream' -} -exports['aes-128-cfb1'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CFB1', - type: 'stream' -} -exports['aes-192-cfb1'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CFB1', - type: 'stream' -} -exports['aes-256-cfb1'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CFB1', - type: 'stream' -} -exports['aes-128-ofb'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'OFB', - type: 'stream' -} -exports['aes-192-ofb'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'OFB', - type: 'stream' -} -exports['aes-256-ofb'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'OFB', - type: 'stream' -} -exports['aes-128-ctr'] = { - cipher: 'AES', - key: 128, - iv: 16, - mode: 'CTR', - type: 'stream' -} -exports['aes-192-ctr'] = { - cipher: 'AES', - key: 192, - iv: 16, - mode: 'CTR', - type: 'stream' -} -exports['aes-256-ctr'] = { - cipher: 'AES', - key: 256, - iv: 16, - mode: 'CTR', - type: 'stream' -} -exports['aes-128-gcm'] = { - cipher: 'AES', - key: 128, - iv: 12, - mode: 'GCM', - type: 'auth' -} -exports['aes-192-gcm'] = { - cipher: 'AES', - key: 192, - iv: 12, - mode: 'GCM', - type: 'auth' -} -exports['aes-256-gcm'] = { - cipher: 'AES', - key: 256, - iv: 12, - mode: 'GCM', - type: 'auth' -} - -},{}],84:[function(require,module,exports){ -var xor = require('buffer-xor') - -exports.encrypt = function (self, block) { - var data = xor(block, self._prev) - - self._prev = self._cipher.encryptBlock(data) - return self._prev -} - -exports.decrypt = function (self, block) { - var pad = self._prev - - self._prev = block - var out = self._cipher.decryptBlock(block) - - return xor(out, pad) -} - -},{"buffer-xor":96}],85:[function(require,module,exports){ -(function (Buffer){ -var xor = require('buffer-xor') - -exports.encrypt = function (self, data, decrypt) { - var out = new Buffer('') - var len - - while (data.length) { - if (self._cache.length === 0) { - self._cache = self._cipher.encryptBlock(self._prev) - self._prev = new Buffer('') - } - - if (self._cache.length <= data.length) { - len = self._cache.length - out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) - data = data.slice(len) - } else { - out = Buffer.concat([out, encryptStart(self, data, decrypt)]) - break - } - } - - return out -} -function encryptStart (self, data, decrypt) { - var len = data.length - var out = xor(data, self._cache) - self._cache = self._cache.slice(len) - self._prev = Buffer.concat([self._prev, decrypt ? data : out]) - return out -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"buffer-xor":96}],86:[function(require,module,exports){ -(function (Buffer){ -function encryptByte (self, byteParam, decrypt) { - var pad - var i = -1 - var len = 8 - var out = 0 - var bit, value - while (++i < len) { - pad = self._cipher.encryptBlock(self._prev) - bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 - value = pad[0] ^ bit - out += ((value & 0x80) >> (i % 8)) - self._prev = shiftIn(self._prev, decrypt ? bit : value) - } - return out -} -exports.encrypt = function (self, chunk, decrypt) { - var len = chunk.length - var out = new Buffer(len) - var i = -1 - while (++i < len) { - out[i] = encryptByte(self, chunk[i], decrypt) - } - return out -} -function shiftIn (buffer, value) { - var len = buffer.length - var i = -1 - var out = new Buffer(buffer.length) - buffer = Buffer.concat([buffer, new Buffer([value])]) - while (++i < len) { - out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) - } - return out -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],87:[function(require,module,exports){ -(function (Buffer){ -function encryptByte (self, byteParam, decrypt) { - var pad = self._cipher.encryptBlock(self._prev) - var out = pad[0] ^ byteParam - self._prev = Buffer.concat([self._prev.slice(1), new Buffer([decrypt ? byteParam : out])]) - return out -} -exports.encrypt = function (self, chunk, decrypt) { - var len = chunk.length - var out = new Buffer(len) - var i = -1 - while (++i < len) { - out[i] = encryptByte(self, chunk[i], decrypt) - } - return out -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],88:[function(require,module,exports){ -(function (Buffer){ -var xor = require('buffer-xor') - -function incr32 (iv) { - var len = iv.length - var item - while (len--) { - item = iv.readUInt8(len) - if (item === 255) { - iv.writeUInt8(0, len) - } else { - item++ - iv.writeUInt8(item, len) - break - } - } -} - -function getBlock (self) { - var out = self._cipher.encryptBlock(self._prev) - incr32(self._prev) - return out -} - -exports.encrypt = function (self, chunk) { - while (self._cache.length < chunk.length) { - self._cache = Buffer.concat([self._cache, getBlock(self)]) - } - var pad = self._cache.slice(0, chunk.length) - self._cache = self._cache.slice(chunk.length) - return xor(chunk, pad) -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"buffer-xor":96}],89:[function(require,module,exports){ -exports.encrypt = function (self, block) { - return self._cipher.encryptBlock(block) -} -exports.decrypt = function (self, block) { - return self._cipher.decryptBlock(block) -} - -},{}],90:[function(require,module,exports){ -(function (Buffer){ -var xor = require('buffer-xor') - -function getBlock (self) { - self._prev = self._cipher.encryptBlock(self._prev) - return self._prev -} - -exports.encrypt = function (self, chunk) { - while (self._cache.length < chunk.length) { - self._cache = Buffer.concat([self._cache, getBlock(self)]) - } - - var pad = self._cache.slice(0, chunk.length) - self._cache = self._cache.slice(chunk.length) - return xor(chunk, pad) -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"buffer-xor":96}],91:[function(require,module,exports){ -(function (Buffer){ -var aes = require('./aes') -var Transform = require('cipher-base') -var inherits = require('inherits') - -inherits(StreamCipher, Transform) -module.exports = StreamCipher -function StreamCipher (mode, key, iv, decrypt) { - if (!(this instanceof StreamCipher)) { - return new StreamCipher(mode, key, iv) - } - Transform.call(this) - this._cipher = new aes.AES(key) - this._prev = new Buffer(iv.length) - this._cache = new Buffer('') - this._secCache = new Buffer('') - this._decrypt = decrypt - iv.copy(this._prev) - this._mode = mode -} -StreamCipher.prototype._update = function (chunk) { - return this._mode.encrypt(this, chunk, this._decrypt) -} -StreamCipher.prototype._final = function () { - this._cipher.scrub() -} - -}).call(this,require("buffer").Buffer) -},{"./aes":77,"buffer":987,"cipher-base":98,"inherits":216}],92:[function(require,module,exports){ -(function (Buffer){ -const Sha3 = require('js-sha3') - -const hashLengths = [ 224, 256, 384, 512 ] - -var hash = function (bitcount) { - if (bitcount !== undefined && hashLengths.indexOf(bitcount) == -1) - throw new Error('Unsupported hash length') - this.content = [] - this.bitcount = bitcount ? 'keccak_' + bitcount : 'keccak_512' -} - -hash.prototype.update = function (i) { - if (Buffer.isBuffer(i)) - this.content.push(i) - else if (typeof i === 'string') - this.content.push(new Buffer(i)) - else - throw new Error('Unsupported argument to update') - return this -} - -hash.prototype.digest = function (encoding) { - var result = Sha3[this.bitcount](Buffer.concat(this.content)) - if (encoding === 'hex') - return result - else if (encoding === 'binary' || encoding === undefined) - return new Buffer(result, 'hex').toString('binary') - else - throw new Error('Unsupported encoding for digest: ' + encoding) -} - -module.exports = { - SHA3Hash: hash -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"js-sha3":93}],93:[function(require,module,exports){ -(function (global){ -/* - * js-sha3 v0.3.1 - * https://github.com/emn178/js-sha3 - * - * Copyright 2015, emn178@gmail.com - * - * Licensed under the MIT license: - * http://www.opensource.org/licenses/MIT - */ -;(function(root, undefined) { - 'use strict'; - - var NODE_JS = typeof(module) != 'undefined'; - if(NODE_JS) { - root = global; - if(root.JS_SHA3_TEST) { - root.navigator = { userAgent: 'Chrome'}; - } - } - var CHROME = (root.JS_SHA3_TEST || !NODE_JS) && navigator.userAgent.indexOf('Chrome') != -1; - var HEX_CHARS = '0123456789abcdef'.split(''); - var KECCAK_PADDING = [1, 256, 65536, 16777216]; - var PADDING = [6, 1536, 393216, 100663296]; - var SHIFT = [0, 8, 16, 24]; - var RC = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, - 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, - 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, - 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, - 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]; - - var blocks = [], s = []; - - var keccak_224 = function(message) { - return keccak(message, 224, KECCAK_PADDING); - }; - - var keccak_256 = function(message) { - return keccak(message, 256, KECCAK_PADDING); - }; - - var keccak_384 = function(message) { - return keccak(message, 384, KECCAK_PADDING); - }; - - var sha3_224 = function(message) { - return keccak(message, 224, PADDING); - }; - - var sha3_256 = function(message) { - return keccak(message, 256, PADDING); - }; - - var sha3_384 = function(message) { - return keccak(message, 384, PADDING); - }; - - var sha3_512 = function(message) { - return keccak(message, 512, PADDING); - }; - - var keccak = function(message, bits, padding) { - var notString = typeof(message) != 'string'; - if(notString && message.constructor == root.ArrayBuffer) { - message = new Uint8Array(message); - } - - if(bits === undefined) { - bits = 512; - padding = KECCAK_PADDING; - } - - var block, code, end = false, index = 0, start = 0, length = message.length, - n, i, h, l, c0, c1, c2, c3, c4, c5, c6, c7, c8, c9, - b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16, b17, - b18, b19, b20, b21, b22, b23, b24, b25, b26, b27, b28, b29, b30, b31, b32, b33, - b34, b35, b36, b37, b38, b39, b40, b41, b42, b43, b44, b45, b46, b47, b48, b49; - var blockCount = (1600 - bits * 2) / 32; - var byteCount = blockCount * 4; - - for(i = 0;i < 50;++i) { - s[i] = 0; - } - - block = 0; - do { - blocks[0] = block; - for(i = 1;i < blockCount + 1;++i) { - blocks[i] = 0; - } - if(notString) { - for (i = start;index < length && i < byteCount; ++index) { - blocks[i >> 2] |= message[index] << SHIFT[i++ & 3]; - } - } else { - for (i = start;index < length && i < byteCount; ++index) { - code = message.charCodeAt(index); - if (code < 0x80) { - blocks[i >> 2] |= code << SHIFT[i++ & 3]; - } else if (code < 0x800) { - blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else if (code < 0xd800 || code >= 0xe000) { - blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } else { - code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff)); - blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3]; - blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3]; - } - } - } - start = i - byteCount; - if(index == length) { - blocks[i >> 2] |= padding[i & 3]; - ++index; - } - block = blocks[blockCount]; - if(index > length && i < byteCount) { - blocks[blockCount - 1] |= 0x80000000; - end = true; - } - - for(i = 0;i < blockCount;++i) { - s[i] ^= blocks[i]; - } - - for(n = 0; n < 48; n += 2) { - c0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]; - c1 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]; - c2 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]; - c3 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]; - c4 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]; - c5 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]; - c6 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]; - c7 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]; - c8 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]; - c9 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]; - - h = c8 ^ ((c2 << 1) | (c3 >>> 31)); - l = c9 ^ ((c3 << 1) | (c2 >>> 31)); - s[0] ^= h; - s[1] ^= l; - s[10] ^= h; - s[11] ^= l; - s[20] ^= h; - s[21] ^= l; - s[30] ^= h; - s[31] ^= l; - s[40] ^= h; - s[41] ^= l; - h = c0 ^ ((c4 << 1) | (c5 >>> 31)); - l = c1 ^ ((c5 << 1) | (c4 >>> 31)); - s[2] ^= h; - s[3] ^= l; - s[12] ^= h; - s[13] ^= l; - s[22] ^= h; - s[23] ^= l; - s[32] ^= h; - s[33] ^= l; - s[42] ^= h; - s[43] ^= l; - h = c2 ^ ((c6 << 1) | (c7 >>> 31)); - l = c3 ^ ((c7 << 1) | (c6 >>> 31)); - s[4] ^= h; - s[5] ^= l; - s[14] ^= h; - s[15] ^= l; - s[24] ^= h; - s[25] ^= l; - s[34] ^= h; - s[35] ^= l; - s[44] ^= h; - s[45] ^= l; - h = c4 ^ ((c8 << 1) | (c9 >>> 31)); - l = c5 ^ ((c9 << 1) | (c8 >>> 31)); - s[6] ^= h; - s[7] ^= l; - s[16] ^= h; - s[17] ^= l; - s[26] ^= h; - s[27] ^= l; - s[36] ^= h; - s[37] ^= l; - s[46] ^= h; - s[47] ^= l; - h = c6 ^ ((c0 << 1) | (c1 >>> 31)); - l = c7 ^ ((c1 << 1) | (c0 >>> 31)); - s[8] ^= h; - s[9] ^= l; - s[18] ^= h; - s[19] ^= l; - s[28] ^= h; - s[29] ^= l; - s[38] ^= h; - s[39] ^= l; - s[48] ^= h; - s[49] ^= l; - - b0 = s[0]; - b1 = s[1]; - b32 = (s[11] << 4) | (s[10] >>> 28); - b33 = (s[10] << 4) | (s[11] >>> 28); - b14 = (s[20] << 3) | (s[21] >>> 29); - b15 = (s[21] << 3) | (s[20] >>> 29); - b46 = (s[31] << 9) | (s[30] >>> 23); - b47 = (s[30] << 9) | (s[31] >>> 23); - b28 = (s[40] << 18) | (s[41] >>> 14); - b29 = (s[41] << 18) | (s[40] >>> 14); - b20 = (s[2] << 1) | (s[3] >>> 31); - b21 = (s[3] << 1) | (s[2] >>> 31); - b2 = (s[13] << 12) | (s[12] >>> 20); - b3 = (s[12] << 12) | (s[13] >>> 20); - b34 = (s[22] << 10) | (s[23] >>> 22); - b35 = (s[23] << 10) | (s[22] >>> 22); - b16 = (s[33] << 13) | (s[32] >>> 19); - b17 = (s[32] << 13) | (s[33] >>> 19); - b48 = (s[42] << 2) | (s[43] >>> 30); - b49 = (s[43] << 2) | (s[42] >>> 30); - b40 = (s[5] << 30) | (s[4] >>> 2); - b41 = (s[4] << 30) | (s[5] >>> 2); - b22 = (s[14] << 6) | (s[15] >>> 26); - b23 = (s[15] << 6) | (s[14] >>> 26); - b4 = (s[25] << 11) | (s[24] >>> 21); - b5 = (s[24] << 11) | (s[25] >>> 21); - b36 = (s[34] << 15) | (s[35] >>> 17); - b37 = (s[35] << 15) | (s[34] >>> 17); - b18 = (s[45] << 29) | (s[44] >>> 3); - b19 = (s[44] << 29) | (s[45] >>> 3); - b10 = (s[6] << 28) | (s[7] >>> 4); - b11 = (s[7] << 28) | (s[6] >>> 4); - b42 = (s[17] << 23) | (s[16] >>> 9); - b43 = (s[16] << 23) | (s[17] >>> 9); - b24 = (s[26] << 25) | (s[27] >>> 7); - b25 = (s[27] << 25) | (s[26] >>> 7); - b6 = (s[36] << 21) | (s[37] >>> 11); - b7 = (s[37] << 21) | (s[36] >>> 11); - b38 = (s[47] << 24) | (s[46] >>> 8); - b39 = (s[46] << 24) | (s[47] >>> 8); - b30 = (s[8] << 27) | (s[9] >>> 5); - b31 = (s[9] << 27) | (s[8] >>> 5); - b12 = (s[18] << 20) | (s[19] >>> 12); - b13 = (s[19] << 20) | (s[18] >>> 12); - b44 = (s[29] << 7) | (s[28] >>> 25); - b45 = (s[28] << 7) | (s[29] >>> 25); - b26 = (s[38] << 8) | (s[39] >>> 24); - b27 = (s[39] << 8) | (s[38] >>> 24); - b8 = (s[48] << 14) | (s[49] >>> 18); - b9 = (s[49] << 14) | (s[48] >>> 18); - - s[0] = b0 ^ (~b2 & b4); - s[1] = b1 ^ (~b3 & b5); - s[10] = b10 ^ (~b12 & b14); - s[11] = b11 ^ (~b13 & b15); - s[20] = b20 ^ (~b22 & b24); - s[21] = b21 ^ (~b23 & b25); - s[30] = b30 ^ (~b32 & b34); - s[31] = b31 ^ (~b33 & b35); - s[40] = b40 ^ (~b42 & b44); - s[41] = b41 ^ (~b43 & b45); - s[2] = b2 ^ (~b4 & b6); - s[3] = b3 ^ (~b5 & b7); - s[12] = b12 ^ (~b14 & b16); - s[13] = b13 ^ (~b15 & b17); - s[22] = b22 ^ (~b24 & b26); - s[23] = b23 ^ (~b25 & b27); - s[32] = b32 ^ (~b34 & b36); - s[33] = b33 ^ (~b35 & b37); - s[42] = b42 ^ (~b44 & b46); - s[43] = b43 ^ (~b45 & b47); - s[4] = b4 ^ (~b6 & b8); - s[5] = b5 ^ (~b7 & b9); - s[14] = b14 ^ (~b16 & b18); - s[15] = b15 ^ (~b17 & b19); - s[24] = b24 ^ (~b26 & b28); - s[25] = b25 ^ (~b27 & b29); - s[34] = b34 ^ (~b36 & b38); - s[35] = b35 ^ (~b37 & b39); - s[44] = b44 ^ (~b46 & b48); - s[45] = b45 ^ (~b47 & b49); - s[6] = b6 ^ (~b8 & b0); - s[7] = b7 ^ (~b9 & b1); - s[16] = b16 ^ (~b18 & b10); - s[17] = b17 ^ (~b19 & b11); - s[26] = b26 ^ (~b28 & b20); - s[27] = b27 ^ (~b29 & b21); - s[36] = b36 ^ (~b38 & b30); - s[37] = b37 ^ (~b39 & b31); - s[46] = b46 ^ (~b48 & b40); - s[47] = b47 ^ (~b49 & b41); - s[8] = b8 ^ (~b0 & b2); - s[9] = b9 ^ (~b1 & b3); - s[18] = b18 ^ (~b10 & b12); - s[19] = b19 ^ (~b11 & b13); - s[28] = b28 ^ (~b20 & b22); - s[29] = b29 ^ (~b21 & b23); - s[38] = b38 ^ (~b30 & b32); - s[39] = b39 ^ (~b31 & b33); - s[48] = b48 ^ (~b40 & b42); - s[49] = b49 ^ (~b41 & b43); - - s[0] ^= RC[n]; - s[1] ^= RC[n + 1]; - } - } while(!end); - - var hex = ''; - if(CHROME) { - b0 = s[0]; - b1 = s[1]; - b2 = s[2]; - b3 = s[3]; - b4 = s[4]; - b5 = s[5]; - b6 = s[6]; - b7 = s[7]; - b8 = s[8]; - b9 = s[9]; - b10 = s[10]; - b11 = s[11]; - b12 = s[12]; - b13 = s[13]; - b14 = s[14]; - b15 = s[15]; - hex += HEX_CHARS[(b0 >> 4) & 0x0F] + HEX_CHARS[b0 & 0x0F] + - HEX_CHARS[(b0 >> 12) & 0x0F] + HEX_CHARS[(b0 >> 8) & 0x0F] + - HEX_CHARS[(b0 >> 20) & 0x0F] + HEX_CHARS[(b0 >> 16) & 0x0F] + - HEX_CHARS[(b0 >> 28) & 0x0F] + HEX_CHARS[(b0 >> 24) & 0x0F] + - HEX_CHARS[(b1 >> 4) & 0x0F] + HEX_CHARS[b1 & 0x0F] + - HEX_CHARS[(b1 >> 12) & 0x0F] + HEX_CHARS[(b1 >> 8) & 0x0F] + - HEX_CHARS[(b1 >> 20) & 0x0F] + HEX_CHARS[(b1 >> 16) & 0x0F] + - HEX_CHARS[(b1 >> 28) & 0x0F] + HEX_CHARS[(b1 >> 24) & 0x0F] + - HEX_CHARS[(b2 >> 4) & 0x0F] + HEX_CHARS[b2 & 0x0F] + - HEX_CHARS[(b2 >> 12) & 0x0F] + HEX_CHARS[(b2 >> 8) & 0x0F] + - HEX_CHARS[(b2 >> 20) & 0x0F] + HEX_CHARS[(b2 >> 16) & 0x0F] + - HEX_CHARS[(b2 >> 28) & 0x0F] + HEX_CHARS[(b2 >> 24) & 0x0F] + - HEX_CHARS[(b3 >> 4) & 0x0F] + HEX_CHARS[b3 & 0x0F] + - HEX_CHARS[(b3 >> 12) & 0x0F] + HEX_CHARS[(b3 >> 8) & 0x0F] + - HEX_CHARS[(b3 >> 20) & 0x0F] + HEX_CHARS[(b3 >> 16) & 0x0F] + - HEX_CHARS[(b3 >> 28) & 0x0F] + HEX_CHARS[(b3 >> 24) & 0x0F] + - HEX_CHARS[(b4 >> 4) & 0x0F] + HEX_CHARS[b4 & 0x0F] + - HEX_CHARS[(b4 >> 12) & 0x0F] + HEX_CHARS[(b4 >> 8) & 0x0F] + - HEX_CHARS[(b4 >> 20) & 0x0F] + HEX_CHARS[(b4 >> 16) & 0x0F] + - HEX_CHARS[(b4 >> 28) & 0x0F] + HEX_CHARS[(b4 >> 24) & 0x0F] + - HEX_CHARS[(b5 >> 4) & 0x0F] + HEX_CHARS[b5 & 0x0F] + - HEX_CHARS[(b5 >> 12) & 0x0F] + HEX_CHARS[(b5 >> 8) & 0x0F] + - HEX_CHARS[(b5 >> 20) & 0x0F] + HEX_CHARS[(b5 >> 16) & 0x0F] + - HEX_CHARS[(b5 >> 28) & 0x0F] + HEX_CHARS[(b5 >> 24) & 0x0F] + - HEX_CHARS[(b6 >> 4) & 0x0F] + HEX_CHARS[b6 & 0x0F] + - HEX_CHARS[(b6 >> 12) & 0x0F] + HEX_CHARS[(b6 >> 8) & 0x0F] + - HEX_CHARS[(b6 >> 20) & 0x0F] + HEX_CHARS[(b6 >> 16) & 0x0F] + - HEX_CHARS[(b6 >> 28) & 0x0F] + HEX_CHARS[(b6 >> 24) & 0x0F]; - - if(bits >= 256) { - hex += HEX_CHARS[(b7 >> 4) & 0x0F] + HEX_CHARS[b7 & 0x0F] + - HEX_CHARS[(b7 >> 12) & 0x0F] + HEX_CHARS[(b7 >> 8) & 0x0F] + - HEX_CHARS[(b7 >> 20) & 0x0F] + HEX_CHARS[(b7 >> 16) & 0x0F] + - HEX_CHARS[(b7 >> 28) & 0x0F] + HEX_CHARS[(b7 >> 24) & 0x0F]; - } - if(bits >= 384) { - hex += HEX_CHARS[(b8 >> 4) & 0x0F] + HEX_CHARS[b8 & 0x0F] + - HEX_CHARS[(b8 >> 12) & 0x0F] + HEX_CHARS[(b8 >> 8) & 0x0F] + - HEX_CHARS[(b8 >> 20) & 0x0F] + HEX_CHARS[(b8 >> 16) & 0x0F] + - HEX_CHARS[(b8 >> 28) & 0x0F] + HEX_CHARS[(b8 >> 24) & 0x0F] + - HEX_CHARS[(b9 >> 4) & 0x0F] + HEX_CHARS[b9 & 0x0F] + - HEX_CHARS[(b9 >> 12) & 0x0F] + HEX_CHARS[(b9 >> 8) & 0x0F] + - HEX_CHARS[(b9 >> 20) & 0x0F] + HEX_CHARS[(b9 >> 16) & 0x0F] + - HEX_CHARS[(b9 >> 28) & 0x0F] + HEX_CHARS[(b9 >> 24) & 0x0F] + - HEX_CHARS[(b10 >> 4) & 0x0F] + HEX_CHARS[b10 & 0x0F] + - HEX_CHARS[(b10 >> 12) & 0x0F] + HEX_CHARS[(b10 >> 8) & 0x0F] + - HEX_CHARS[(b10 >> 20) & 0x0F] + HEX_CHARS[(b10 >> 16) & 0x0F] + - HEX_CHARS[(b10 >> 28) & 0x0F] + HEX_CHARS[(b10 >> 24) & 0x0F] + - HEX_CHARS[(b11 >> 4) & 0x0F] + HEX_CHARS[b11 & 0x0F] + - HEX_CHARS[(b11 >> 12) & 0x0F] + HEX_CHARS[(b11 >> 8) & 0x0F] + - HEX_CHARS[(b11 >> 20) & 0x0F] + HEX_CHARS[(b11 >> 16) & 0x0F] + - HEX_CHARS[(b11 >> 28) & 0x0F] + HEX_CHARS[(b11 >> 24) & 0x0F]; - } - if(bits == 512) { - hex += HEX_CHARS[(b12 >> 4) & 0x0F] + HEX_CHARS[b12 & 0x0F] + - HEX_CHARS[(b12 >> 12) & 0x0F] + HEX_CHARS[(b12 >> 8) & 0x0F] + - HEX_CHARS[(b12 >> 20) & 0x0F] + HEX_CHARS[(b12 >> 16) & 0x0F] + - HEX_CHARS[(b12 >> 28) & 0x0F] + HEX_CHARS[(b12 >> 24) & 0x0F] + - HEX_CHARS[(b13 >> 4) & 0x0F] + HEX_CHARS[b13 & 0x0F] + - HEX_CHARS[(b13 >> 12) & 0x0F] + HEX_CHARS[(b13 >> 8) & 0x0F] + - HEX_CHARS[(b13 >> 20) & 0x0F] + HEX_CHARS[(b13 >> 16) & 0x0F] + - HEX_CHARS[(b13 >> 28) & 0x0F] + HEX_CHARS[(b13 >> 24) & 0x0F] + - HEX_CHARS[(b14 >> 4) & 0x0F] + HEX_CHARS[b14 & 0x0F] + - HEX_CHARS[(b14 >> 12) & 0x0F] + HEX_CHARS[(b14 >> 8) & 0x0F] + - HEX_CHARS[(b14 >> 20) & 0x0F] + HEX_CHARS[(b14 >> 16) & 0x0F] + - HEX_CHARS[(b14 >> 28) & 0x0F] + HEX_CHARS[(b14 >> 24) & 0x0F] + - HEX_CHARS[(b15 >> 4) & 0x0F] + HEX_CHARS[b15 & 0x0F] + - HEX_CHARS[(b15 >> 12) & 0x0F] + HEX_CHARS[(b15 >> 8) & 0x0F] + - HEX_CHARS[(b15 >> 20) & 0x0F] + HEX_CHARS[(b15 >> 16) & 0x0F] + - HEX_CHARS[(b15 >> 28) & 0x0F] + HEX_CHARS[(b15 >> 24) & 0x0F]; - } - } else { - for(i = 0, n = bits / 32;i < n;++i) { - h = s[i]; - hex += HEX_CHARS[(h >> 4) & 0x0F] + HEX_CHARS[h & 0x0F] + - HEX_CHARS[(h >> 12) & 0x0F] + HEX_CHARS[(h >> 8) & 0x0F] + - HEX_CHARS[(h >> 20) & 0x0F] + HEX_CHARS[(h >> 16) & 0x0F] + - HEX_CHARS[(h >> 28) & 0x0F] + HEX_CHARS[(h >> 24) & 0x0F]; - } - } - return hex; - }; - - if(!root.JS_SHA3_TEST && NODE_JS) { - module.exports = { - sha3_512: sha3_512, - sha3_384: sha3_384, - sha3_256: sha3_256, - sha3_224: sha3_224, - keccak_512: keccak, - keccak_384: keccak_384, - keccak_256: keccak_256, - keccak_224: keccak_224 - }; - } else if(root) { - root.sha3_512 = sha3_512; - root.sha3_384 = sha3_384; - root.sha3_256 = sha3_256; - root.sha3_224 = sha3_224; - root.keccak_512 = keccak; - root.keccak_384 = keccak_384; - root.keccak_256 = keccak_256; - root.keccak_224 = keccak_224; - } -}(this)); - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],94:[function(require,module,exports){ -var basex = require('base-x') -var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' - -module.exports = basex(ALPHABET) - -},{"base-x":95}],95:[function(require,module,exports){ -// base-x encoding -// Forked from https://github.com/cryptocoinjs/bs58 -// Originally written by Mike Hearn for BitcoinJ -// Copyright (c) 2011 Google Inc -// Ported to JavaScript by Stefan Thomas -// Merged Buffer refactorings from base58-native by Stephen Pair -// Copyright (c) 2013 BitPay Inc - -var Buffer = require('safe-buffer').Buffer - -module.exports = function base (ALPHABET) { - var ALPHABET_MAP = {} - var BASE = ALPHABET.length - var LEADER = ALPHABET.charAt(0) - - // pre-compute lookup table - for (var z = 0; z < ALPHABET.length; z++) { - var x = ALPHABET.charAt(z) - - if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') - ALPHABET_MAP[x] = z - } - - function encode (source) { - if (source.length === 0) return '' - - var digits = [0] - for (var i = 0; i < source.length; ++i) { - for (var j = 0, carry = source[i]; j < digits.length; ++j) { - carry += digits[j] << 8 - digits[j] = carry % BASE - carry = (carry / BASE) | 0 - } - - while (carry > 0) { - digits.push(carry % BASE) - carry = (carry / BASE) | 0 - } - } - - var string = '' - - // deal with leading zeros - for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += ALPHABET[0] - // convert digits to a string - for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]] - - return string - } - - function decodeUnsafe (string) { - if (string.length === 0) return Buffer.allocUnsafe(0) - - var bytes = [0] - for (var i = 0; i < string.length; i++) { - var value = ALPHABET_MAP[string[i]] - if (value === undefined) return - - for (var j = 0, carry = value; j < bytes.length; ++j) { - carry += bytes[j] * BASE - bytes[j] = carry & 0xff - carry >>= 8 - } - - while (carry > 0) { - bytes.push(carry & 0xff) - carry >>= 8 - } - } - - // deal with leading zeros - for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) { - bytes.push(0) - } - - return Buffer.from(bytes.reverse()) - } - - function decode (string) { - var buffer = decodeUnsafe(string) - if (buffer) return buffer - - throw new Error('Non-base' + BASE + ' character') - } - - return { - encode: encode, - decodeUnsafe: decodeUnsafe, - decode: decode - } -} - -},{"safe-buffer":656}],96:[function(require,module,exports){ -(function (Buffer){ -module.exports = function xor (a, b) { - var length = Math.min(a.length, b.length) - var buffer = new Buffer(length) - - for (var i = 0; i < length; ++i) { - buffer[i] = a[i] ^ b[i] - } - - return buffer -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],97:[function(require,module,exports){ -(function (Buffer){ -'use strict' - -const mh = require('multihashes') -const multibase = require('multibase') -const multicodec = require('multicodec') -const codecs = require('multicodec/src/base-table') -const codecVarints = require('multicodec/src/varint-table') -const multihash = require('multihashes') - -/** - * @typedef {Object} SerializedCID - * @param {string} codec - * @param {number} version - * @param {Buffer} multihash - * - */ - -/** - * Class representing a CID `` - * , as defined in [ipld/cid](https://github.com/ipld/cid). - * @class CID - */ -class CID { - /** - * Create a new CID. - * - * The algorithm for argument input is roughly: - * ``` - * if (str) - * if (1st char is on multibase table) -> CID String - * else -> bs58 encoded multihash - * else if (Buffer) - * if (0 or 1) -> CID - * else -> multihash - * else if (Number) - * -> construct CID by parts - * - * ..if only JS had traits.. - * ``` - * - * @param {string|Buffer} version - * @param {string} [codec] - * @param {Buffer} [multihash] - * - * @example - * - * new CID(, , ) - * new CID() - * new CID() - * new CID() - * new CID() - * - */ - constructor (version, codec, multihash) { - if (typeof version === 'string') { - if (multibase.isEncoded(version)) { // CID String (encoded with multibase) - const cid = multibase.decode(version) - version = parseInt(cid.slice(0, 1).toString('hex'), 16) - codec = multicodec.getCodec(cid.slice(1)) - multihash = multicodec.rmPrefix(cid.slice(1)) - } else { // bs58 string encoded multihash - codec = 'dag-pb' - multihash = mh.fromB58String(version) - version = 0 - } - } else if (Buffer.isBuffer(version)) { - const firstByte = version.slice(0, 1) - const v = parseInt(firstByte.toString('hex'), 16) - if (v === 0 || v === 1) { // CID - const cid = version - version = v - codec = multicodec.getCodec(cid.slice(1)) - multihash = multicodec.rmPrefix(cid.slice(1)) - } else { // multihash - codec = 'dag-pb' - multihash = version - version = 0 - } - } - - /** - * @type {string} - */ - this.codec = codec - - /** - * @type {number} - */ - this.version = version - - /** - * @type {Buffer} - */ - this.multihash = multihash - - CID.validateCID(this) - } - - /** - * The CID as a `Buffer` - * - * @return {Buffer} - * @readonly - * - * @memberOf CID - */ - get buffer () { - switch (this.version) { - case 0: - return this.multihash - case 1: - return Buffer.concat([ - Buffer('01', 'hex'), - Buffer(codecVarints[this.codec]), - this.multihash - ]) - default: - throw new Error('unsupported version') - } - } - - /** - * Get the prefix of the CID. - * - * @returns {Buffer} - * @readonly - */ - get prefix () { - return Buffer.concat([ - new Buffer(`0${this.version}`, 'hex'), - codecVarints[this.codec], - multihash.prefix(this.multihash) - ]) - } - - /** - * Convert to a CID of version `0`. - * - * @returns {CID} - */ - toV0 () { - if (this.codec !== 'dag-pb') { - throw new Error('Cannot convert a non dag-pb CID to CIDv0') - } - - return new CID(0, this.codec, this.multihash) - } - - /** - * Convert to a CID of version `1`. - * - * @returns {CID} - */ - toV1 () { - return new CID(1, this.codec, this.multihash) - } - - /** - * Encode the CID into a string. - * - * @param {string} [base='base58btc'] - Base encoding to use. - * @returns {string} - */ - toBaseEncodedString (base) { - base = base || 'base58btc' - - switch (this.version) { - case 0: { - if (base !== 'base58btc') { - throw new Error('not supported with CIDv0, to support different bases, please migrate the instance do CIDv1, you can do that through cid.toV1()') - } - return mh.toB58String(this.multihash) - } - case 1: - return multibase.encode(base, this.buffer).toString() - default: - throw new Error('Unsupported version') - } - } - - /** - * Serialize to a plain object. - * - * @returns {SerializedCID} - */ - toJSON () { - return { - codec: this.codec, - version: this.version, - hash: this.multihash - } - } - - /** - * Compare equality with another CID. - * - * @param {CID} other - * @returns {bool} - */ - equals (other) { - return this.codec === other.codec && - this.version === other.version && - this.multihash.equals(other.multihash) - } - - /** - * Test if the given input is a CID. - * - * @param {any} other - * @returns {bool} - */ - static isCID (other) { - try { - CID.validateCID(other) - } catch (err) { - return false - } - - return true - } - - /** - * Test if the given input is a valid CID object. - * Throws if it is not. - * - * @param {any} other - * @returns {void} - */ - static validateCID (other) { - if (other == null) { - throw new Error('null values are not valid CIDs') - } - - if (!(other.version === 0 || other.version === 1)) { - throw new Error('Invalid version, must be a number equal to 1 or 0') - } - - if (typeof other.codec !== 'string') { - throw new Error('codec must be string') - } - - if (!Buffer.isBuffer(other.multihash)) { - throw new Error('multihash must be a Buffer') - } - - mh.validate(other.multihash) - } -} - -CID.codecs = codecs - -module.exports = CID - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"multibase":519,"multicodec":521,"multicodec/src/base-table":520,"multicodec/src/varint-table":524,"multihashes":526}],98:[function(require,module,exports){ -(function (Buffer){ -var Transform = require('stream').Transform -var inherits = require('inherits') -var StringDecoder = require('string_decoder').StringDecoder -module.exports = CipherBase -inherits(CipherBase, Transform) -function CipherBase (hashMode) { - Transform.call(this) - this.hashMode = typeof hashMode === 'string' - if (this.hashMode) { - this[hashMode] = this._finalOrDigest - } else { - this.final = this._finalOrDigest - } - this._decoder = null - this._encoding = null -} -CipherBase.prototype.update = function (data, inputEnc, outputEnc) { - if (typeof data === 'string') { - data = new Buffer(data, inputEnc) - } - var outData = this._update(data) - if (this.hashMode) { - return this - } - if (outputEnc) { - outData = this._toString(outData, outputEnc) - } - return outData -} - -CipherBase.prototype.setAutoPadding = function () {} - -CipherBase.prototype.getAuthTag = function () { - throw new Error('trying to get auth tag in unsupported state') -} - -CipherBase.prototype.setAuthTag = function () { - throw new Error('trying to set auth tag in unsupported state') -} - -CipherBase.prototype.setAAD = function () { - throw new Error('trying to set aad in unsupported state') -} - -CipherBase.prototype._transform = function (data, _, next) { - var err - try { - if (this.hashMode) { - this._update(data) - } else { - this.push(this._update(data)) - } - } catch (e) { - err = e - } finally { - next(err) - } -} -CipherBase.prototype._flush = function (done) { - var err - try { - this.push(this._final()) - } catch (e) { - err = e - } finally { - done(err) - } -} -CipherBase.prototype._finalOrDigest = function (outputEnc) { - var outData = this._final() || new Buffer('') - if (outputEnc) { - outData = this._toString(outData, outputEnc, true) - } - return outData -} - -CipherBase.prototype._toString = function (value, enc, fin) { - if (!this._decoder) { - this._decoder = new StringDecoder(enc) - this._encoding = enc - } - if (this._encoding !== enc) { - throw new Error('can\'t switch encodings') - } - var out = this._decoder.write(value) - if (fin) { - out += this._decoder.end() - } - return out -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"inherits":216,"stream":1028,"string_decoder":1029}],99:[function(require,module,exports){ -(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); -} - -}).call(this,{"isBuffer":require("../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js")}) -},{"../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js":993}],100:[function(require,module,exports){ -(function (Buffer){ -'use strict' -var inherits = require('inherits') -var md5 = require('./md5') -var RIPEMD160 = require('ripemd160') -var sha = require('sha.js') - -var Base = require('cipher-base') - -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)) -} - -}).call(this,require("buffer").Buffer) -},{"./md5":102,"buffer":987,"cipher-base":98,"inherits":216,"ripemd160":654,"sha.js":671}],101:[function(require,module,exports){ -(function (Buffer){ -'use strict' -var intSize = 4 -var zeroBuffer = new Buffer(intSize) -zeroBuffer.fill(0) - -var charSize = 8 -var hashSize = 16 - -function toArray (buf) { - if ((buf.length % intSize) !== 0) { - var len = buf.length + (intSize - (buf.length % intSize)) - buf = Buffer.concat([buf, zeroBuffer], len) - } - - var arr = new Array(buf.length >>> 2) - for (var i = 0, j = 0; i < buf.length; i += intSize, j++) { - arr[j] = buf.readInt32LE(i) - } - - return arr -} - -module.exports = function hash (buf, fn) { - var arr = fn(toArray(buf), buf.length * charSize) - buf = new Buffer(hashSize) - for (var i = 0; i < arr.length; i++) { - buf.writeInt32LE(arr[i], i << 2, true) - } - return buf -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],102:[function(require,module,exports){ -'use strict' -/* - * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message - * Digest Algorithm, as defined in RFC 1321. - * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. - * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet - * Distributed under the BSD License - * See http://pajhome.org.uk/crypt/md5 for more info. - */ - -var makeHash = require('./make-hash') - -/* - * Calculate the MD5 of an array of little-endian words, and a bit length - */ -function core_md5 (x, len) { - /* append padding */ - x[len >> 5] |= 0x80 << ((len) % 32) - x[(((len + 64) >>> 9) << 4) + 14] = len - - var a = 1732584193 - var b = -271733879 - var c = -1732584194 - var d = 271733878 - - for (var i = 0; i < x.length; i += 16) { - var olda = a - var oldb = b - var oldc = c - var oldd = d - - a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936) - d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586) - c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819) - b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330) - a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897) - d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426) - c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341) - b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983) - a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416) - d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417) - c = md5_ff(c, d, a, b, x[i + 10], 17, -42063) - b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162) - a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682) - d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101) - c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290) - b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329) - - a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510) - d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632) - c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713) - b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302) - a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691) - d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083) - c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335) - b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848) - a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438) - d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690) - c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961) - b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501) - a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467) - d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784) - c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473) - b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734) - - a = md5_hh(a, b, c, d, x[i + 5], 4, -378558) - d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463) - c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562) - b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556) - a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060) - d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353) - c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632) - b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640) - a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174) - d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222) - c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979) - b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189) - a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487) - d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835) - c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520) - b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651) - - a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844) - d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415) - c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905) - b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055) - a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571) - d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606) - c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523) - b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799) - a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359) - d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744) - c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380) - b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649) - a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070) - d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379) - c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259) - b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551) - - a = safe_add(a, olda) - b = safe_add(b, oldb) - c = safe_add(c, oldc) - d = safe_add(d, oldd) - } - - return [a, b, c, d] -} - -/* - * These functions implement the four basic operations the algorithm uses. - */ -function md5_cmn (q, a, b, x, s, t) { - return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) -} - -function md5_ff (a, b, c, d, x, s, t) { - return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) -} - -function md5_gg (a, b, c, d, x, s, t) { - return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) -} - -function md5_hh (a, b, c, d, x, s, t) { - return md5_cmn(b ^ c ^ d, a, b, x, s, t) -} - -function md5_ii (a, b, c, d, x, s, t) { - return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) -} - -/* - * Add integers, wrapping at 2^32. This uses 16-bit operations internally - * to work around bugs in some JS interpreters. - */ -function safe_add (x, y) { - var lsw = (x & 0xFFFF) + (y & 0xFFFF) - var msw = (x >> 16) + (y >> 16) + (lsw >> 16) - return (msw << 16) | (lsw & 0xFFFF) -} - -/* - * Bitwise rotate a 32-bit number to the left. - */ -function bit_rol (num, cnt) { - return (num << cnt) | (num >>> (32 - cnt)) -} - -module.exports = function md5 (buf) { - return makeHash(buf, core_md5) -} - -},{"./make-hash":101}],103:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var Legacy = require('./legacy') -var Base = require('cipher-base') -var Buffer = require('safe-buffer').Buffer -var md5 = require('create-hash/md5') -var RIPEMD160 = require('ripemd160') - -var sha = require('sha.js') - -var ZEROS = Buffer.alloc(128) - -function Hmac (alg, key) { - Base.call(this, 'digest') - if (typeof key === 'string') { - key = Buffer.from(key) - } - - var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 - - this._alg = alg - this._key = key - if (key.length > blocksize) { - var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) - key = hash.update(key).digest() - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } - - var ipad = this._ipad = Buffer.allocUnsafe(blocksize) - var opad = this._opad = Buffer.allocUnsafe(blocksize) - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } - this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) - this._hash.update(ipad) -} - -inherits(Hmac, Base) - -Hmac.prototype._update = function (data) { - this._hash.update(data) -} - -Hmac.prototype._final = function () { - var h = this._hash.digest() - var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) - return hash.update(this._opad).update(h).digest() -} - -module.exports = function createHmac (alg, key) { - alg = alg.toLowerCase() - if (alg === 'rmd160' || alg === 'ripemd160') { - return new Hmac('rmd160', key) - } - if (alg === 'md5') { - return new Legacy(md5, key) - } - return new Hmac(alg, key) -} - -},{"./legacy":104,"cipher-base":98,"create-hash/md5":102,"inherits":216,"ripemd160":654,"safe-buffer":656,"sha.js":671}],104:[function(require,module,exports){ -'use strict' -var inherits = require('inherits') -var Buffer = require('safe-buffer').Buffer - -var Base = require('cipher-base') - -var ZEROS = Buffer.alloc(128) -var blocksize = 64 - -function Hmac (alg, key) { - Base.call(this, 'digest') - if (typeof key === 'string') { - key = Buffer.from(key) - } - - this._alg = alg - this._key = key - - if (key.length > blocksize) { - key = alg(key) - } else if (key.length < blocksize) { - key = Buffer.concat([key, ZEROS], blocksize) - } - - var ipad = this._ipad = Buffer.allocUnsafe(blocksize) - var opad = this._opad = Buffer.allocUnsafe(blocksize) - - for (var i = 0; i < blocksize; i++) { - ipad[i] = key[i] ^ 0x36 - opad[i] = key[i] ^ 0x5C - } - - this._hash = [ipad] -} - -inherits(Hmac, Base) - -Hmac.prototype._update = function (data) { - this._hash.push(data) -} - -Hmac.prototype._final = function () { - var h = this._alg(Buffer.concat(this._hash)) - return this._alg(Buffer.concat([this._opad, h])) -} -module.exports = Hmac - -},{"cipher-base":98,"inherits":216,"safe-buffer":656}],105:[function(require,module,exports){ -/* @flow */ -'use strict' - -const Key = require('./key') -const MemoryDatastore = require('./memory') -const utils = require('./utils') - -exports.Key = Key -exports.MemoryDatastore = MemoryDatastore -exports.utils = utils - -/* :: -// -- Basics - -export type Callback = (err: ?Error, ?Value) => void - -// eslint-disable-next-line -export interface Datastore { - // eslint-disable-next-line - put(Key, Value, Callback): void; - // eslint-disable-next-line - get(Key, Callback): void; - has(Key, Callback): void; - delete(Key, Callback): void; - // eslint-disable-next-line - query(Query): QueryResult; - - // eslint-disable-next-line - batch(): Batch; - close(Callback): void; -} - -// -- Batch -export type Batch = { - put(Key, Value): void, - delete(Key): void, - commit(Callback): void -} - -// -- Query - -export type Query = { - prefix?: string, - filters?: Array>, - orders?: Array>, - limit?: number, - offset?: number, - keysOnly?: bool -} - -export type PullEnd = bool | Error -export type PullSource = (end: ?PullEnd, (end: ?PullEnd, Val) => void) => void - -export type QueryResult = PullSource> - -export type QueryEntry = { - key: Key, - value?: Value -} - -export type Filter = (QueryEntry, Callback) => void - -export type Order = (QueryResult, Callback>) => void - -*/ - -},{"./key":106,"./memory":107,"./utils":108}],106:[function(require,module,exports){ -(function (Buffer){ -/* @flow */ -'use strict' - -const path = require('path') -const uuid = require('uuid/v4') - -/** - * A Key represents the unique identifier of an object. - * Our Key scheme is inspired by file systems and Google App Engine key model. - * Keys are meant to be unique across a system. Keys are hierarchical, - * incorporating more and more specific namespaces. Thus keys can be deemed - * 'children' or 'ancestors' of other keys: - * - `new Key('/Comedy')` - * - `new Key('/Comedy/MontyPython')` - * Also, every namespace can be parametrized to embed relevant object - * information. For example, the Key `name` (most specific namespace) could - * include the object type: - * - `new Key('/Comedy/MontyPython/Actor:JohnCleese')` - * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop')` - * - `new Key('/Comedy/MontyPython/Sketch:CheeseShop/Character:Mousebender')` - * - */ -class Key { - /* :: _buf: Buffer */ - - constructor (s /* : string|Buffer */, clean /* : ?bool */) { - if (typeof s === 'string') { - this._buf = new Buffer(s) - } else if (Buffer.isBuffer(s)) { - this._buf = s - } - - if (clean == null) { - clean = true - } - - if (clean) { - this.clean() - } - - if (this._buf.length === 0 || this._buf[0] !== 47) { - throw new Error(`Invalid key: ${this.toString()}`) - } - } - - /** - * Convert to the string representation - * - * @param {string} [encoding='utf8'] - * @returns {string} - */ - toString (encoding/* : ?buffer$Encoding */)/* : string */ { - return this._buf.toString(encoding || 'utf8') - } - - /** - * Return the buffer representation of the key - * - * @returns {Buffer} - */ - toBuffer () /* : Buffer */ { - return this._buf - } - - // waiting on https://github.com/facebook/flow/issues/2286 - // $FlowFixMe - get [Symbol.toStringTag] () /* : string */ { - return `[Key ${this.toString()}]` - } - - /** - * Constructs a key out of a namespace array. - * - * @param {Array} list - * @returns {Key} - * - * @example - * Key.withNamespaces(['one', 'two']) - * // => Key('/one/two') - * - */ - static withNamespaces (list /* : Array */) /* : Key */ { - return new Key(list.join('/')) - } - - /** - * Returns a randomly (uuid) generated key. - * - * @returns {Key} - * - * @example - * Key.random() - * // => Key('/f98719ea086343f7b71f32ea9d9d521d') - * - */ - static random () /* : Key */ { - return new Key(uuid().replace(/-/g, '')) - } - - /** - * Cleanup the current key - * - * @returns {void} - */ - clean () { - if (!this._buf || this._buf.length === 0) { - this._buf = new Buffer('/') - } - - if (this._buf[0] !== 47 /* / is 47 */) { - this._buf = Buffer.concat([new Buffer('/'), this._buf]) - } - - this._buf = new Buffer(path.normalize(this.toString())) - - // normalize does not remove trailing slashes - if (this.toString().length > 1) { - this._buf = new Buffer(this.toString().replace(/\/$/, '')) - } - } - - /** - * Check if the given key is sorted lower than ourself. - * - * @param {Key} key - * @returns {bool} - */ - less (key /* : Key */) /* : bool */ { - const list1 = this.list() - const list2 = key.list() - - for (let i = 0; i < list1.length; i++) { - if (list2.length < i + 1) { - return false - } - - const c1 = list1[i] - const c2 = list2[i] - - if (c1 < c2) { - return true - } else if (c1 > c2) { - return false - } - } - - return list1.length < list2.length - } - - /** - * Returns the key with all parts in reversed order. - * - * @returns {Key} - * - * @example - * new Key('/Comedy/MontyPython/Actor:JohnCleese').reverse() - * // => Key('/Actor:JohnCleese/MontyPython/Comedy') - */ - reverse () /* : Key */ { - return Key.withNamespaces(this.list().slice().reverse()) - } - - /** - * Returns the `namespaces` making up this Key. - * - * @returns {Array} - */ - namespaces () /* : Array */ { - return this.list() - } - - /** Returns the "base" namespace of this key. - * - * @returns {string} - * - * @example - * new Key('/Comedy/MontyPython/Actor:JohnCleese').baseNamespace() - * // => 'Actor:JohnCleese' - * - */ - baseNamespace () /* : string */ { - const ns = this.namespaces() - return ns[ns.length - 1] - } - - /** - * Returns the `list` representation of this key. - * - * @returns {Array} - * - * @example - * new Key('/Comedy/MontyPython/Actor:JohnCleese').list() - * // => ['Comedy', 'MontyPythong', 'Actor:JohnCleese'] - * - */ - list () /* : Array */ { - return this.toString().split('/').slice(1) - } - - /** - * Returns the "type" of this key (value of last namespace). - * - * @returns {string} - * - * @example - * new Key('/Comedy/MontyPython/Actor:JohnCleese').type() - * // => 'Actor' - * - */ - type () /* : string */ { - return namespaceType(this.baseNamespace()) - } - - /** - * Returns the "name" of this key (field of last namespace). - * - * @returns {string} - * - * @example - * new Key('/Comedy/MontyPython/Actor:JohnCleese').name() - * // => 'JohnCleese' - */ - name () /* : string */ { - return namespaceValue(this.baseNamespace()) - } - - /** - * Returns an "instance" of this type key (appends value to namespace). - * - * @param {string} s - * @returns {Key} - * - * @example - * new Key('/Comedy/MontyPython/Actor').instance('JohnClesse') - * // => Key('/Comedy/MontyPython/Actor:JohnCleese') - */ - instance (s /* : string */) /* : Key */ { - return new Key(this.toString() + ':' + s) - } - - /** - * Returns the "path" of this key (parent + type). - * - * @returns {Key} - * - * @example - * new Key('/Comedy/MontyPython/Actor:JohnCleese').path() - * // => Key('/Comedy/MontyPython/Actor') - * - */ - path () /* : Key */ { - return new Key(this.parent().toString() + '/' + this.type()) - } - - /** - * Returns the `parent` Key of this Key. - * - * @returns {Key} - * - * @example - * new Key("/Comedy/MontyPython/Actor:JohnCleese").parent() - * // => Key("/Comedy/MontyPython") - * - */ - parent () /* : Key */ { - const list = this.list() - if (list.length === 1) { - return new Key('/', false) - } - - return new Key(list.slice(0, -1).join('/')) - } - - /** - * Returns the `child` Key of this Key. - * - * @param {Key} key - * @returns {Key} - * - * @example - * new Key('/Comedy/MontyPython').child(new Key('Actor:JohnCleese')) - * // => Key('/Comedy/MontyPython/Actor:JohnCleese') - * - */ - child (key /* : Key */) /* : Key */ { - if (this.toString() === '/') { - return key - } else if (key.toString() === '/') { - return this - } - - return new Key(this.toString() + key.toString(), false) - } - - /** - * Returns whether this key is a prefix of `other` - * - * @param {Key} other - * @returns {bool} - * - * @example - * new Key('/Comedy').isAncestorOf('/Comedy/MontyPython') - * // => true - * - */ - isAncestorOf (other /* : Key */) /* : bool */ { - if (other.toString() === this.toString()) { - return false - } - - return other.toString().startsWith(this.toString()) - } - - /** - * Returns whether this key is a contains another as prefix. - * - * @param {Key} other - * @returns {bool} - * - * @example - * new Key('/Comedy/MontyPython').isDecendantOf('/Comedy') - * // => true - * - */ - isDecendantOf (other /* : Key */) /* : bool */ { - if (other.toString() === this.toString()) { - return false - } - - return this.toString().startsWith(other.toString()) - } - - /** - * Returns wether this key has only one namespace. - * - * @returns {bool} - * - */ - isTopLevel () /* : bool */ { - return this.list().length === 1 - } -} - -/** - * The first component of a namespace. `foo` in `foo:bar` - * - * @param {string} ns - * @returns {string} - */ -function namespaceType (ns /* : string */) /* : string */ { - const parts = ns.split(':') - if (parts.length < 2) { - return '' - } - return parts.slice(0, -1).join(':') -} - -/** - * The last component of a namespace, `baz` in `foo:bar:baz`. - * - * @param {string} ns - * @returns {string} - */ -function namespaceValue (ns /* : string */) /* : string */ { - const parts = ns.split(':') - return parts[parts.length - 1] -} - -module.exports = Key - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"path":1007,"uuid/v4":723}],107:[function(require,module,exports){ -/* @flow */ -'use strict' - -/* :: import type {Batch, Query, QueryResult, Callback} from './' */ - -const pull = require('pull-stream') -const setImmediate = require('async/setImmediate') - -const asyncFilter = require('./utils').asyncFilter -const asyncSort = require('./utils').asyncSort -const Key = require('./key') - -class MemoryDatastore { - /* :: data: {[key: string]: Buffer} */ - - constructor () { - this.data = {} - } - - put (key /* : Key */, val /* : Buffer */, callback /* : Callback */) /* : void */ { - this.data[key.toString()] = val - - setImmediate(callback) - } - - get (key /* : Key */, callback /* : Callback */) /* : void */ { - this.has(key, (err, exists) => { - if (err) { - return callback(err) - } - - if (!exists) { - return callback(new Error('No value')) - } - - callback(null, this.data[key.toString()]) - }) - } - - has (key /* : Key */, callback /* : Callback */) /* : void */ { - setImmediate(() => { - callback(null, this.data[key.toString()] !== undefined) - }) - } - - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - delete this.data[key.toString()] - - setImmediate(() => { - callback() - }) - } - - batch () /* : Batch */ { - let puts = [] - let dels = [] - - return { - put (key /* : Key */, value /* : Buffer */) /* : void */ { - puts.push([key, value]) - }, - delete (key /* : Key */) /* : void */ { - dels.push(key) - }, - commit: (callback /* : Callback */) /* : void */ => { - puts.forEach(v => { - this.data[v[0].toString()] = v[1] - }) - - puts = [] - dels.forEach(key => { - delete this.data[key.toString()] - }) - dels = [] - - setImmediate(callback) - } - } - } - - query (q /* : Query */) /* : QueryResult */ { - let tasks = [pull.keys(this.data), pull.map(k => ({ - key: new Key(k), - value: this.data[k] - }))] - - let filters = [] - - if (q.prefix != null) { - const prefix = q.prefix - filters.push((e, cb) => cb(null, e.key.toString().startsWith(prefix))) - } - - if (q.filters != null) { - filters = filters.concat(q.filters) - } - - tasks = tasks.concat(filters.map(f => asyncFilter(f))) - - if (q.orders != null) { - tasks = tasks.concat(q.orders.map(o => asyncSort(o))) - } - - if (q.offset != null) { - let i = 0 - // $FlowFixMe - tasks.push(pull.filter(() => i++ >= q.offset)) - } - - if (q.limit != null) { - tasks.push(pull.take(q.limit)) - } - - if (q.keysOnly === true) { - tasks.push(pull.map(e => ({ key: e.key }))) - } - - return pull.apply(null, tasks) - } - - close (callback /* : Callback */) /* : void */ { - setImmediate(callback) - } -} - -module.exports = MemoryDatastore - -},{"./key":106,"./utils":108,"async/setImmediate":53,"pull-stream":602}],108:[function(require,module,exports){ -'use strict' - -const pull = require('pull-stream') -const Source = require('pull-defer/source') -const path = require('path') -const os = require('os') -const uuid = require('uuid/v4') - -exports.asyncFilter = function (test) { - let busy = false - let abortCb - let aborted - - return function (read) { - return function next (abort, cb) { - if (aborted) return cb(aborted) - if (abort) { - aborted = abort - if (!busy) { - read(abort, cb) - } else { - read(abort, () => { - // if we are still busy, wait for the test to complete. - if (busy) abortCb = cb; else cb(abort) - }) - } - } else { - read(null, (end, data) => { - if (end) cb(end); else if (aborted) cb(aborted); else { - busy = true - test(data, (err, valid) => { - busy = false - if (aborted) { - cb(aborted) - abortCb(aborted) - } else if (err) { - next(err, cb) - } else if (valid) { - cb(null, data) - } else { - next(null, cb) - } - }) - } - }) - } - } - } -} - -exports.asyncSort = function (sorter) { - const source = Source() - - const sink = pull.collect((err, ary) => { - if (err) { - return source.abort(err) - } - sorter(ary, (err, res) => { - if (err) { - return source.abort(err) - } - source.resolve(pull.values(ary)) - }) - }) - - return function (read) { - sink(read) - return source - } -} - -exports.replaceStartWith = function (s, r) { - const matcher = new RegExp('^' + r) - return s.replace(matcher, '') -} - -exports.tmpdir = () => { - return path.join(os.tmpdir(), uuid()) -} - -},{"os":995,"path":1007,"pull-defer/source":586,"pull-stream":602,"uuid/v4":723}],109:[function(require,module,exports){ -/* @flow */ -'use strict' - -const KeytransformDatastore = require('./keytransform') -const ShardingDatastore = require('./sharding') -const MountDatastore = require('./mount') -const TieredDatastore = require('./tiered') -const NamespaceDatastore = require('./namespace') -const shard = require('./shard') - -exports.KeytransformDatastore = KeytransformDatastore -exports.ShardingDatastore = ShardingDatastore -exports.MountDatastore = MountDatastore -exports.TieredDatastore = TieredDatastore -exports.NamespaceDatastore = NamespaceDatastore -exports.shard = shard - -},{"./keytransform":110,"./mount":111,"./namespace":112,"./shard":114,"./sharding":115,"./tiered":116}],110:[function(require,module,exports){ -/* @flow */ -'use strict' - -const pull = require('pull-stream') - -/* :: -import type {Key, Datastore, Batch, Query, QueryResult, Callback} from 'interface-datastore' -*/ - -/** - * An object with a pair of functions for (invertibly) transforming keys - */ -/* :: -type KeyTransform = { - convert: KeyMapping, - invert: KeyMapping -} -*/ - -/** - * Map one key onto another key. - */ -/* :: -type KeyMapping = (Key) => Key -*/ - -/** - * A datastore shim, that wraps around a given datastore, changing - * the way keys look to the user, for example namespacing - * keys, reversing them, etc. - */ -class KeyTransformDatastore /* :: */ { - /* :: child: Datastore */ - /* :: transform: KeyTransform */ - - constructor (child /* : Datastore */, transform /* : KeyTransform */) { - this.child = child - this.transform = transform - } - - open (callback /* : Callback */) /* : void */ { - this.child.open(callback) - } - - put (key /* : Key */, val /* : Value */, callback /* : Callback */) /* : void */ { - this.child.put(this.transform.convert(key), val, callback) - } - - get (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.get(this.transform.convert(key), callback) - } - - has (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.has(this.transform.convert(key), callback) - } - - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.delete(this.transform.convert(key), callback) - } - - batch () /* : Batch */ { - const b = this.child.batch() - return { - put: (key /* : Key */, value /* : Value */) /* : void */ => { - b.put(this.transform.convert(key), value) - }, - delete: (key /* : Key */) /* : void */ => { - b.delete(this.transform.convert(key)) - }, - commit: (callback /* : Callback */) /* : void */ => { - b.commit(callback) - } - } - } - - query (q /* : Query */) /* : QueryResult */ { - return pull( - this.child.query(q), - pull.map(e => { - e.key = this.transform.invert(e.key) - return e - }) - ) - } - - close (callback /* : Callback */) /* : void */ { - this.child.close(callback) - } -} - -module.exports = KeyTransformDatastore - -},{"pull-stream":602}],111:[function(require,module,exports){ -/* @flow */ -'use strict' - -const each = require('async/each') -const many = require('pull-many') -const pull = require('pull-stream') - -const Key = require('interface-datastore').Key -const utils = require('interface-datastore').utils -const asyncFilter = utils.asyncFilter -const asyncSort = utils.asyncSort -const replaceStartWith = utils.replaceStartWith - -const Keytransform = require('./keytransform') - -/* :: -import type {Datastore, Callback, Batch, Query, QueryResult} from 'interface-datastore' - -type Mount = { - prefix: Key, - datastore: Datastore -} -*/ - -/** - * A datastore that can combine multiple stores inside various - * key prefixs. - */ -class MountDatastore /* :: */ { - /* :: mounts: Array> */ - - constructor (mounts /* : Array> */) { - this.mounts = mounts.slice() - } - - open (callback /* : Callback */) /* : void */ { - each(this.mounts, (m, cb) => { - m.datastore.open(cb) - }, callback) - } - - /** - * Lookup the matching datastore for the given key. - * - * @private - * @param {Key} key - * @returns {{Datastore, Key, Key}} - */ - _lookup (key /* : Key */) /* : ?{datastore: Datastore, mountpoint: Key, rest: Key} */ { - for (let mount of this.mounts) { - if (mount.prefix.toString() === key.toString() || mount.prefix.isAncestorOf(key)) { - const s = replaceStartWith(key.toString(), mount.prefix.toString()) - return { - datastore: mount.datastore, - mountpoint: mount.prefix, - rest: new Key(s) - } - } - } - } - - put (key /* : Key */, value /* : Value */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(new Error('No datastore mounted for this key')) - return - } - - match.datastore.put(match.rest, value, callback) - } - - get (key /* : Key */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(new Error('No datastore mounted for this key')) - return - } - - match.datastore.get(match.rest, callback) - } - - has (key /* : Key */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(null, false) - return - } - - match.datastore.has(match.rest, callback) - } - - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - const match = this._lookup(key) - if (match == null) { - callback(new Error('No datastore mounted for this key')) - return - } - - match.datastore.delete(match.rest, callback) - } - - close (callback /* : Callback */) /* : void */ { - each(this.mounts, (m, cb) => { - m.datastore.close(cb) - }, callback) - } - - batch () /* : Batch */ { - const batchMounts = {} - const lookup = (key /* : Key */) /* : {batch: Batch, rest: Key} */ => { - const match = this._lookup(key) - if (match == null) { - throw new Error('No datastore mounted for this key') - } - - const m = match.mountpoint.toString() - if (batchMounts[m] == null) { - batchMounts[m] = match.datastore.batch() - } - - return { - batch: batchMounts[m], - rest: match.rest - } - } - - return { - put: (key /* : Key */, value /* : Value */) /* : void */ => { - const match = lookup(key) - match.batch.put(match.rest, value) - }, - delete: (key /* : Key */) /* : void */ => { - const match = lookup(key) - match.batch.delete(match.rest) - }, - commit: (callback /* : Callback */) /* : void */ => { - each(Object.keys(batchMounts), (p, cb) => { - batchMounts[p].commit(cb) - }, callback) - } - } - } - - query (q /* : Query */) /* : QueryResult */ { - const qs = this.mounts.map(m => { - const ks = new Keytransform(m.datastore, { - convert: (key /* : Key */) /* : Key */ => { - throw new Error('should never be called') - }, - invert: (key /* : Key */) /* : Key */ => { - return m.prefix.child(key) - } - }) - - let prefix - if (q.prefix != null) { - prefix = replaceStartWith(q.prefix, m.prefix.toString()) - } - - return ks.query({ - prefix: prefix, - filters: q.filters, - keysOnly: q.keysOnly - }) - }) - - let tasks = [many(qs)] - - if (q.filters != null) { - tasks = tasks.concat(q.filters.map(f => asyncFilter(f))) - } - - if (q.orders != null) { - tasks = tasks.concat(q.orders.map(o => asyncSort(o))) - } - - if (q.offset != null) { - let i = 0 - // $FlowFixMe - tasks.push(pull.filter(() => i++ >= q.offset)) - } - - if (q.limit != null) { - tasks.push(pull.take(q.limit)) - } - - return pull.apply(null, tasks) - } -} - -module.exports = MountDatastore - -},{"./keytransform":110,"async/each":20,"interface-datastore":105,"pull-many":592,"pull-stream":602}],112:[function(require,module,exports){ -/* @flow */ -'use strict' - -const Key = require('interface-datastore').Key -const KeytransformDatastore = require('./keytransform') - -/* :: -import type {Callback, Datastore, Query, QueryResult} from 'interface-datastore' -*/ - -/** - * Wraps a given datastore into a keytransform which - * makes a given prefix transparent. - * - * For example, if the prefix is `new Key(/hello)` a call - * to `store.put(new Key('/world'), mydata)` would store the data under - * `/hello/world`. - * - */ -class NamespaceDatastore/* :: */ extends KeytransformDatastore /* :: */ { - /* :: prefix: Key */ - - constructor (child/* : Datastore */, prefix/* : Key */) { - super(child, { - convert (key/* : Key */)/* : Key */ { - return prefix.child(key) - }, - invert (key/* : Key */)/* : Key */ { - if (prefix.toString() === '/') { - return key - } - - if (!prefix.isAncestorOf(key)) { - throw new Error(`Expected prefix: (${prefix.toString()}) in key: ${key.toString()}`) - } - - return new Key(key.toString().slice(prefix.toString().length), false) - } - }) - - this.prefix = prefix - } - - query (q /* : Query */)/* : QueryResult */ { - if (q.prefix && this.prefix.toString() !== '/') { - return super.query(Object.assign({}, q, { - prefix: this.prefix.child(new Key(q.prefix)).toString() - })) - } - return super.query(q) - } -} - -module.exports = NamespaceDatastore - -},{"./keytransform":110,"interface-datastore":105}],113:[function(require,module,exports){ -/* @flow */ -'use strict' - -module.exports = `This is a repository of IPLD objects. Each IPLD object is in a single file, -named .data. Where is the -"base32" encoding of the CID (as specified in -https://github.com/multiformats/multibase) without the 'B' prefix. -All the object files are placed in a tree of directories, based on a -function of the CID. This is a form of sharding similar to -the objects directory in git repositories. Previously, we used -prefixes, we now use the next-to-last two charters. - func NextToLast(base32cid string) { - nextToLastLen := 2 - offset := len(base32cid) - nextToLastLen - 1 - return str[offset : offset+nextToLastLen] - } -For example, an object with a base58 CIDv1 of - zb2rhYSxw4ZjuzgCnWSt19Q94ERaeFhu9uSqRgjSdx9bsgM6f -has a base32 CIDv1 of - BAFKREIA22FLID5AJ2KU7URG47MDLROZIH6YF2KALU2PWEFPVI37YLKRSCA -and will be placed at - SC/AFKREIA22FLID5AJ2KU7URG47MDLROZIH6YF2KALU2PWEFPVI37YLKRSCA.data -with 'SC' being the last-to-next two characters and the 'B' at the -beginning of the CIDv1 string is the multibase prefix that is not -stored in the filename. -` - -},{}],114:[function(require,module,exports){ -/* @flow */ -'use strict' - -const leftPad = require('left-pad') -const Key = require('interface-datastore').Key - -const readme = require('./shard-readme') - -// eslint-disable-next-line -/*:: import type {Datastore, Callback} from 'interface-datastore' - -export interface ShardV1 { - name: string; - param: number; - fun(string): string; - toString(): string; -} -*/ - -const PREFIX = exports.PREFIX = '/repo/flatfs/shard/' -const SHARDING_FN = exports.SHARDING_FN = 'SHARDING' -exports.README_FN = '_README' - -class Shard { - /* :: name: string */ - /* :: param: number */ - /* :: _padding: string */ - - constructor (param /* : number */) { - this.param = param - } - - fun (str /* : string */) /* : string */ { - throw new Error('implement me') - } - - toString () /* : string */ { - return `${PREFIX}v1/${this.name}/${this.param}` - } -} - -class Prefix extends Shard { - constructor (prefixLen /* : number */) { - super(prefixLen) - this._padding = leftPad('', prefixLen, '_') - this.name = 'prefix' - } - - fun (noslash /* : string */) /* : string */ { - return (noslash + this._padding).slice(0, this.param) - } -} - -class Suffix extends Shard { - constructor (suffixLen /* : number */) { - super(suffixLen) - this._padding = leftPad('', suffixLen, '_') - this.name = 'suffix' - } - - fun (noslash /* : string */) /* : string */ { - const s = this._padding + noslash - return s.slice(s.length - this.param) - } -} - -class NextToLast extends Shard { - constructor (suffixLen /* : number */) { - super(suffixLen) - this._padding = leftPad('', suffixLen + 1, '_') - this.name = 'next-to-last' - } - - fun (noslash /* : string */) /* : string */ { - const s = this._padding + noslash - const offset = s.length - this.param - 1 - return s.slice(offset, offset + this.param) - } -} - -/** - * Convert a given string to the matching sharding function. - * - * @param {string} str - * @returns {ShardV1} - */ -function parseShardFun (str /* : string */) /* : ShardV1 */ { - str = str.trim() - - if (str.length === 0) { - throw new Error('empty shard string') - } - - if (!str.startsWith(PREFIX)) { - throw new Error(`invalid or no path prefix: ${str}`) - } - - const parts = str.slice(PREFIX.length).split('/') - const version = parts[0] - - if (version !== 'v1') { - throw new Error(`expect 'v1' version, got '${version}'`) - } - - const name = parts[1] - - if (!parts[2]) { - throw new Error('missing param') - } - - const param = parseInt(parts[2], 10) - - switch (name) { - case 'prefix': - return new Prefix(param) - case 'suffix': - return new Suffix(param) - case 'next-to-last': - return new NextToLast(param) - default: - throw new Error(`unkown sharding function: ${name}`) - } -} - -exports.readShardFun = (path /* : string */, store /* : Datastore */, callback /* : Callback */) /* : void */ => { - const key = new Key(path).child(new Key(SHARDING_FN)) - const get = typeof store.getRaw === 'function' ? store.getRaw.bind(store) : store.get.bind(store) - - get(key, (err, res) => { - if (err) { - return callback(err) - } - - let shard - try { - shard = parseShardFun((res || '').toString().trim()) - } catch (err) { - return callback(err) - } - - callback(null, shard) - }) -} - -exports.readme = readme -exports.parseShardFun = parseShardFun -exports.Prefix = Prefix -exports.Suffix = Suffix -exports.NextToLast = NextToLast - -},{"./shard-readme":113,"interface-datastore":105,"left-pad":352}],115:[function(require,module,exports){ -(function (Buffer){ -/* @flow */ -'use strict' - -const waterfall = require('async/waterfall') -const parallel = require('async/parallel') -const pull = require('pull-stream') -const Key = require('interface-datastore').Key - -const sh = require('./shard') -const KeytransformStore = require('./keytransform') - -const shardKey = new Key(sh.SHARDING_FN) -const shardReadmeKey = new Key(sh.README_FN) - -/* :: -import type {Datastore, Batch, Query, QueryResult, Callback} from 'interface-datastore' - -import type {ShardV1} from './shard' -*/ - -/** - * Backend independent abstraction of go-ds-flatfs. - * - * Wraps another datastore such that all values are stored - * sharded according to the given sharding function. - */ -class ShardingDatastore { - /* :: shard: ShardV1 */ - /* :: child: Datastore */ - - constructor (store /* : Datastore */, shard /* : ShardV1 */) { - this.child = new KeytransformStore(store, { - convert: this._convertKey.bind(this), - invert: this._invertKey.bind(this) - }) - this.shard = shard - } - - open (callback /* : Callback */) /* : void */ { - this.child.open(callback) - } - - _convertKey (key/* : Key */)/* : Key */ { - const s = key.toString() - if (s === shardKey.toString() || s === shardReadmeKey.toString()) { - return key - } - - const parent = new Key(this.shard.fun(s)) - return parent.child(key) - } - - _invertKey (key/* : Key */)/* : Key */ { - const s = key.toString() - if (s === shardKey.toString() || s === shardReadmeKey.toString()) { - return key - } - return Key.withNamespaces(key.list().slice(1)) - } - - static createOrOpen (store /* : Datastore */, shard /* : ShardV1 */, callback /* : Callback */) /* : void */ { - ShardingDatastore.create(store, shard, err => { - if (err && err.message !== 'datastore exists') { - return callback(err) - } - - ShardingDatastore.open(store, callback) - }) - } - - static open (store /* : Datastore */, callback /* : Callback */) /* : void */ { - waterfall([ - (cb) => sh.readShardFun('/', store, cb), - (shard, cb) => { - cb(null, new ShardingDatastore(store, shard)) - } - ], callback) - } - - static create (store /* : Datastore */, shard /* : ShardV1 */, callback /* : Callback */) /* : void */ { - store.has(shardKey, (err, exists) => { - if (err) { - return callback(err) - } - - if (!exists) { - const put = typeof store.putRaw === 'function' ? store.putRaw.bind(store) : store.put.bind(store) - return parallel([ - (cb) => put(shardKey, new Buffer(shard.toString() + '\n'), cb), - (cb) => put(shardReadmeKey, new Buffer(sh.readme), cb) - ], err => callback(err)) - } - - sh.readShardFun('/', store, (err, diskShard) => { - if (err) { - return callback(err) - } - - const a = (diskShard || '').toString() - const b = shard.toString() - if (a !== b) { - return callback(new Error(`specified fun ${b} does not match repo shard fun ${a}`)) - } - - callback(new Error('datastore exists')) - }) - }) - } - - put (key /* : Key */, val /* : Buffer */, callback /* : Callback */) /* : void */ { - this.child.put(key, val, callback) - } - - get (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.get(key, callback) - } - - has (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.has(key, callback) - } - - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - this.child.delete(key, callback) - } - - batch () /* : Batch */ { - return this.child.batch() - } - - query (q /* : Query */) /* : QueryResult */ { - const tq/* : Query */ = { - keysOnly: q.keysOnly - } - - if (q.prefix != null) { - // TODO: transform - tq.prefix = q.prefix - } - - if (q.filters != null) { - tq.filters = q.filters.map((f) => (e, cb) => { - f(Object.assign({}, e, { - key: this._invertKey(e.key) - }), cb) - }) - } - - if (q.orders != null) { - tq.orders = q.orders.map((o) => (res, cb) => { - const m = res.map((e) => { - return Object.assign({}, e, { - key: this._invertKey(e.key) - }) - }) - o(m, cb) - }) - } - - if (q.offset != null) { - tq.offset = q.offset + 2 - } - - if (q.limit != null) { - tq.limit = q.limit + 2 - } - - return pull( - this.child.query(tq), - pull.filter((e) => { - if (e.key.toString() === shardKey.toString() || - e.key.toString() === shardReadmeKey.toString()) { - return false - } - return true - }) - ) - } - - close (callback /* : Callback */) /* : void */ { - this.child.close(callback) - } -} - -module.exports = ShardingDatastore - -}).call(this,require("buffer").Buffer) -},{"./keytransform":110,"./shard":114,"async/parallel":49,"async/waterfall":56,"buffer":987,"interface-datastore":105,"pull-stream":602}],116:[function(require,module,exports){ -/* @flow */ -'use strict' - -const each = require('async/each') -const whilst = require('async/whilst') - -/* :: -import type {Key, Datastore, Callback, Batch, Query, QueryResult} from 'interface-datastore' -*/ - -/** - * A datastore that can combine multiple stores. Puts and deletes - * will write through to all datastores. Has and get will - * try each store sequentially. Query will always try the - * last one first. - * - */ -class TieredDatastore /* :: */ { - /* :: stores: Array> */ - - constructor (stores /* : Array> */) { - this.stores = stores.slice() - } - - open (callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.open(cb) - }, callback) - } - - put (key /* : Key */, value /* : Value */, callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.put(key, value, cb) - }, callback) - } - - get (key /* : Key */, callback /* : Callback */) /* : void */ { - const storeLength = this.stores.length - let done = false - let i = 0 - whilst(() => !done && i < storeLength, cb => { - const store = this.stores[i++] - store.get(key, (err, res) => { - if (err == null) { - done = true - return cb(null, res) - } - cb() - }) - }, callback) - } - - has (key /* : Key */, callback /* : Callback */) /* : void */ { - const storeLength = this.stores.length - let done = false - let i = 0 - whilst(() => !done && i < storeLength, cb => { - const store = this.stores[i++] - store.has(key, (err, exists) => { - if (err == null) { - done = true - return cb(null, exists) - } - cb() - }) - }, callback) - } - - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.delete(key, cb) - }, callback) - } - - close (callback /* : Callback */) /* : void */ { - each(this.stores, (store, cb) => { - store.close(cb) - }, callback) - } - - batch () /* : Batch */ { - const batches = this.stores.map(store => store.batch()) - - return { - put: (key /* : Key */, value /* : Value */) /* : void */ => { - batches.forEach(b => b.put(key, value)) - }, - delete: (key /* : Key */) /* : void */ => { - batches.forEach(b => b.delete(key)) - }, - commit: (callback /* : Callback */) /* : void */ => { - each(batches, (b, cb) => { - b.commit(cb) - }, callback) - } - } - } - - query (q /* : Query */) /* : QueryResult */ { - return this.stores[this.stores.length - 1].query(q) - } -} - -module.exports = TieredDatastore - -},{"async/each":20,"async/whilst":57}],117:[function(require,module,exports){ -(function (Buffer){ -/* @flow */ -'use strict' - -/* :: import type {Callback, Batch, Query, QueryResult, QueryEntry} from 'interface-datastore' */ - -const pull = require('pull-stream') -const levelup = require('levelup') - -const asyncFilter = require('interface-datastore').utils.asyncFilter -const asyncSort = require('interface-datastore').utils.asyncSort -const Key = require('interface-datastore').Key - -/** - * A datastore backed by leveldb. - */ -/* :: export type LevelOptions = { - createIfMissing?: bool, - errorIfExists?: bool, - compression?: bool, - cacheSize?: number, - db?: Object -} */ -class LevelDatastore { - /* :: db: levelup */ - - constructor (path /* : string */, opts /* : ?LevelOptions */) { - this.db = levelup(path, Object.assign(opts || {}, { - compression: false, // same default as go - valueEncoding: 'binary' - })) - } - - open (callback /* : Callback */) /* : void */ { - this.db.open(callback) - } - - put (key /* : Key */, value /* : Buffer */, callback /* : Callback */) /* : void */ { - this.db.put(key.toString(), value, callback) - } - - get (key /* : Key */, callback /* : Callback */) /* : void */ { - this.db.get(key.toString(), callback) - } - - has (key /* : Key */, callback /* : Callback */) /* : void */ { - this.db.get(key.toString(), (err, res) => { - if (err) { - if (err.notFound) { - callback(null, false) - return - } - callback(err) - return - } - - callback(null, true) - }) - } - - delete (key /* : Key */, callback /* : Callback */) /* : void */ { - this.db.del(key.toString(), callback) - } - - close (callback /* : Callback */) /* : void */ { - this.db.close(callback) - } - - batch () /* : Batch */ { - const ops = [] - return { - put: (key /* : Key */, value /* : Buffer */) /* : void */ => { - ops.push({ - type: 'put', - key: key.toString(), - value: value - }) - }, - delete: (key /* : Key */) /* : void */ => { - ops.push({ - type: 'del', - key: key.toString() - }) - }, - commit: (callback /* : Callback */) /* : void */ => { - this.db.batch(ops, callback) - } - } - } - - query (q /* : Query */) /* : QueryResult */ { - let values = true - if (q.keysOnly != null) { - values = !q.keysOnly - } - - const iter = this.db.db.iterator({ - keys: true, - values: values, - keyAsBuffer: true - }) - - const rawStream = (end, cb) => { - if (end) { - return iter.end((err) => { - cb(err || end) - }) - } - - iter.next((err, key, value) => { - if (err) { - return cb(err) - } - - if (err == null && key == null && value == null) { - return iter.end((err) => { - cb(err || true) - }) - } - - const res /* : QueryEntry */ = { - key: new Key(key, false) - } - - if (values) { - res.value = new Buffer(value) - } - - cb(null, res) - }) - } - - let tasks = [rawStream] - let filters = [] - - if (q.prefix != null) { - const prefix = q.prefix - filters.push((e, cb) => cb(null, e.key.toString().startsWith(prefix))) - } - - if (q.filters != null) { - filters = filters.concat(q.filters) - } - - tasks = tasks.concat(filters.map(f => asyncFilter(f))) - - if (q.orders != null) { - tasks = tasks.concat(q.orders.map(o => asyncSort(o))) - } - - if (q.offset != null) { - let i = 0 - // $FlowFixMe - tasks.push(pull.filter(() => i++ >= q.offset)) - } - - if (q.limit != null) { - tasks.push(pull.take(q.limit)) - } - - return pull.apply(null, tasks) - } -} - -module.exports = LevelDatastore - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"interface-datastore":219,"levelup":365,"pull-stream":602}],118:[function(require,module,exports){ -(function (process){ -/** - * This is the web browser implementation of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = require('./debug'); -exports.log = log; -exports.formatArgs = formatArgs; -exports.save = save; -exports.load = load; -exports.useColors = useColors; -exports.storage = 'undefined' != typeof chrome - && 'undefined' != typeof chrome.storage - ? chrome.storage.local - : localstorage(); - -/** - * Colors. - */ - -exports.colors = [ - 'lightseagreen', - 'forestgreen', - 'goldenrod', - 'dodgerblue', - 'darkorchid', - 'crimson' -]; - -/** - * Currently only WebKit-based Web Inspectors, Firefox >= v31, - * and the Firebug extension (any Firefox version) are known - * to support "%c" CSS customizations. - * - * TODO: add a `localStorage` variable to explicitly enable/disable colors - */ - -function useColors() { - // NB: In an Electron preload script, document will be defined but not fully - // initialized. Since we know we're in Chrome, we'll just detect this case - // explicitly - if (typeof window !== 'undefined' && window.process && window.process.type === 'renderer') { - return true; - } - - // is webkit? http://stackoverflow.com/a/16459606/376773 - // document is undefined in react-native: https://github.com/facebook/react-native/pull/1632 - return (typeof document !== 'undefined' && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance) || - // is firebug? http://stackoverflow.com/a/398120/376773 - (typeof window !== 'undefined' && window.console && (window.console.firebug || (window.console.exception && window.console.table))) || - // is firefox >= v31? - // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/) && parseInt(RegExp.$1, 10) >= 31) || - // double check webkit in userAgent just in case we are in a worker - (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)); -} - -/** - * Map %j to `JSON.stringify()`, since no Web Inspectors do that by default. - */ - -exports.formatters.j = function(v) { - try { - return JSON.stringify(v); - } catch (err) { - return '[UnexpectedJSONParseError]: ' + err.message; - } -}; - - -/** - * Colorize log arguments if enabled. - * - * @api public - */ - -function formatArgs(args) { - var useColors = this.useColors; - - args[0] = (useColors ? '%c' : '') - + this.namespace - + (useColors ? ' %c' : ' ') - + args[0] - + (useColors ? '%c ' : ' ') - + '+' + exports.humanize(this.diff); - - if (!useColors) return; - - var c = 'color: ' + this.color; - args.splice(1, 0, c, 'color: inherit') - - // the final "%c" is somewhat tricky, because there could be other - // arguments passed either before or after the %c, so we need to - // figure out the correct index to insert the CSS into - var index = 0; - var lastC = 0; - args[0].replace(/%[a-zA-Z%]/g, function(match) { - if ('%%' === match) return; - index++; - if ('%c' === match) { - // we only are interested in the *last* %c - // (the user may have provided their own) - lastC = index; - } - }); - - args.splice(lastC, 0, c); -} - -/** - * Invokes `console.log()` when available. - * No-op when `console.log` is not a "function". - * - * @api public - */ - -function log() { - // this hackery is required for IE8/9, where - // the `console.log` function doesn't have 'apply' - return 'object' === typeof console - && console.log - && Function.prototype.apply.call(console.log, console, arguments); -} - -/** - * Save `namespaces`. - * - * @param {String} namespaces - * @api private - */ - -function save(namespaces) { - try { - if (null == namespaces) { - exports.storage.removeItem('debug'); - } else { - exports.storage.debug = namespaces; - } - } catch(e) {} -} - -/** - * Load `namespaces`. - * - * @return {String} returns the previously persisted debug modes - * @api private - */ - -function load() { - var r; - try { - r = exports.storage.debug; - } catch(e) {} - - // If debug isn't set in LS, and we're in Electron, try to load $DEBUG - if (!r && typeof process !== 'undefined' && 'env' in process) { - r = process.env.DEBUG; - } - - return r; -} - -/** - * Enable namespaces listed in `localStorage.debug` initially. - */ - -exports.enable(load()); - -/** - * Localstorage attempts to return the localstorage. - * - * This is necessary because safari throws - * when a user disables cookies/localstorage - * and you attempt to access it. - * - * @return {LocalStorage} - * @api private - */ - -function localstorage() { - try { - return window.localStorage; - } catch (e) {} -} - -}).call(this,require('_process')) -},{"./debug":119,"_process":1009}],119:[function(require,module,exports){ - -/** - * This is the common logic for both the Node.js and web browser - * implementations of `debug()`. - * - * Expose `debug()` as the module. - */ - -exports = module.exports = createDebug.debug = createDebug['default'] = createDebug; -exports.coerce = coerce; -exports.disable = disable; -exports.enable = enable; -exports.enabled = enabled; -exports.humanize = require('ms'); - -/** - * The currently active debug mode names, and names to skip. - */ - -exports.names = []; -exports.skips = []; - -/** - * Map of special "%n" handling functions, for the debug "format" argument. - * - * Valid key names are a single, lower or upper-case letter, i.e. "n" and "N". - */ - -exports.formatters = {}; - -/** - * Previous log timestamp. - */ - -var prevTime; - -/** - * Select a color. - * @param {String} namespace - * @return {Number} - * @api private - */ - -function selectColor(namespace) { - var hash = 0, i; - - for (i in namespace) { - hash = ((hash << 5) - hash) + namespace.charCodeAt(i); - hash |= 0; // Convert to 32bit integer - } - - return exports.colors[Math.abs(hash) % exports.colors.length]; -} - -/** - * Create a debugger with the given `namespace`. - * - * @param {String} namespace - * @return {Function} - * @api public - */ - -function createDebug(namespace) { - - function debug() { - // disabled? - if (!debug.enabled) return; - - var self = debug; - - // set `diff` timestamp - var curr = +new Date(); - var ms = curr - (prevTime || curr); - self.diff = ms; - self.prev = prevTime; - self.curr = curr; - prevTime = curr; - - // turn the `arguments` into a proper Array - var args = new Array(arguments.length); - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i]; - } - - args[0] = exports.coerce(args[0]); - - if ('string' !== typeof args[0]) { - // anything else let's inspect with %O - args.unshift('%O'); - } - - // apply any `formatters` transformations - var index = 0; - args[0] = args[0].replace(/%([a-zA-Z%])/g, function(match, format) { - // if we encounter an escaped % then don't increase the array index - if (match === '%%') return match; - index++; - var formatter = exports.formatters[format]; - if ('function' === typeof formatter) { - var val = args[index]; - match = formatter.call(self, val); - - // now we need to remove `args[index]` since it's inlined in the `format` - args.splice(index, 1); - index--; - } - return match; - }); - - // apply env-specific formatting (colors, etc.) - exports.formatArgs.call(self, args); - - var logFn = debug.log || exports.log || console.log.bind(console); - logFn.apply(self, args); - } - - debug.namespace = namespace; - debug.enabled = exports.enabled(namespace); - debug.useColors = exports.useColors(); - debug.color = selectColor(namespace); - - // env-specific initialization logic for debug instances - if ('function' === typeof exports.init) { - exports.init(debug); - } - - return debug; -} - -/** - * Enables a debug mode by namespaces. This can include modes - * separated by a colon and wildcards. - * - * @param {String} namespaces - * @api public - */ - -function enable(namespaces) { - exports.save(namespaces); - - exports.names = []; - exports.skips = []; - - var split = (typeof namespaces === 'string' ? namespaces : '').split(/[\s,]+/); - var len = split.length; - - for (var i = 0; i < len; i++) { - if (!split[i]) continue; // ignore empty strings - namespaces = split[i].replace(/\*/g, '.*?'); - if (namespaces[0] === '-') { - exports.skips.push(new RegExp('^' + namespaces.substr(1) + '$')); - } else { - exports.names.push(new RegExp('^' + namespaces + '$')); - } - } -} - -/** - * Disable debug output. - * - * @api public - */ - -function disable() { - exports.enable(''); -} - -/** - * Returns true if the given mode name is enabled, false otherwise. - * - * @param {String} name - * @return {Boolean} - * @api public - */ - -function enabled(name) { - var i, len; - for (i = 0, len = exports.skips.length; i < len; i++) { - if (exports.skips[i].test(name)) { - return false; - } - } - for (i = 0, len = exports.names.length; i < len; i++) { - if (exports.names[i].test(name)) { - return true; - } - } - return false; -} - -/** - * Coerce `val`. - * - * @param {Mixed} val - * @return {Mixed} - * @api private - */ - -function coerce(val) { - if (val instanceof Error) return val.stack || val.message; - return val; -} - -},{"ms":511}],120:[function(require,module,exports){ -(function (Buffer){ -/*! - * @description Recursive object extending - * @author Viacheslav Lotsmanov - * @license MIT - * - * The MIT License (MIT) - * - * Copyright (c) 2013-2015 Viacheslav Lotsmanov - * - * 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. - */ - -'use strict'; - -function isSpecificValue(val) { - return ( - val instanceof Buffer - || val instanceof Date - || val instanceof RegExp - ) ? true : false; -} - -function cloneSpecificValue(val) { - if (val instanceof Buffer) { - var x = new Buffer(val.length); - val.copy(x); - return x; - } else if (val instanceof Date) { - return new Date(val.getTime()); - } else if (val instanceof RegExp) { - return new RegExp(val); - } else { - throw new Error('Unexpected situation'); - } -} - -/** - * Recursive cloning array. - */ -function deepCloneArray(arr) { - var clone = []; - arr.forEach(function (item, index) { - if (typeof item === 'object' && item !== null) { - if (Array.isArray(item)) { - clone[index] = deepCloneArray(item); - } else if (isSpecificValue(item)) { - clone[index] = cloneSpecificValue(item); - } else { - clone[index] = deepExtend({}, item); - } - } else { - clone[index] = item; - } - }); - return clone; -} - -/** - * Extening object that entered in first argument. - * - * Returns extended object or false if have no target object or incorrect type. - * - * If you wish to clone source object (without modify it), just use empty new - * object as first argument, like this: - * deepExtend({}, yourObj_1, [yourObj_N]); - */ -var deepExtend = module.exports = function (/*obj_1, [obj_2], [obj_N]*/) { - if (arguments.length < 1 || typeof arguments[0] !== 'object') { - return false; - } - - if (arguments.length < 2) { - return arguments[0]; - } - - var target = arguments[0]; - - // convert arguments to array and cut off target object - var args = Array.prototype.slice.call(arguments, 1); - - var val, src, clone; - - args.forEach(function (obj) { - // skip argument if isn't an object, is null, or is an array - if (typeof obj !== 'object' || obj === null || Array.isArray(obj)) { - return; - } - - Object.keys(obj).forEach(function (key) { - src = target[key]; // source value - val = obj[key]; // new value - - // recursion prevention - if (val === target) { - return; - - /** - * if new value isn't object then just overwrite by new value - * instead of extending. - */ - } else if (typeof val !== 'object' || val === null) { - target[key] = val; - return; - - // just clone arrays (and recursive clone objects inside) - } else if (Array.isArray(val)) { - target[key] = deepCloneArray(val); - return; - - // custom cloning and overwrite for specific objects - } else if (isSpecificValue(val)) { - target[key] = cloneSpecificValue(val); - return; - - // overwrite by new value if source isn't object or array - } else if (typeof src !== 'object' || src === null || Array.isArray(src)) { - target[key] = deepExtend({}, val); - return; - - // source value and new value is objects both, extending... - } else { - target[key] = deepExtend(src, val); - return; - } - }); - }); - - return target; -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987}],121:[function(require,module,exports){ -var util = require('util') - , AbstractIterator = require('abstract-leveldown').AbstractIterator - - -function DeferredIterator (options) { - AbstractIterator.call(this, options) - - this._options = options - this._iterator = null - this._operations = [] -} - -util.inherits(DeferredIterator, AbstractIterator) - -DeferredIterator.prototype.setDb = function (db) { - var it = this._iterator = db.iterator(this._options) - this._operations.forEach(function (op) { - it[op.method].apply(it, op.args) - }) -} - -DeferredIterator.prototype._operation = function (method, args) { - if (this._iterator) - return this._iterator[method].apply(this._iterator, args) - this._operations.push({ method: method, args: args }) -} - -'next end'.split(' ').forEach(function (m) { - DeferredIterator.prototype['_' + m] = function () { - this._operation(m, arguments) - } -}) - -module.exports = DeferredIterator; - -},{"abstract-leveldown":126,"util":1036}],122:[function(require,module,exports){ -(function (Buffer,process){ -var util = require('util') - , AbstractLevelDOWN = require('abstract-leveldown').AbstractLevelDOWN - , DeferredIterator = require('./deferred-iterator') - -function DeferredLevelDOWN (location) { - AbstractLevelDOWN.call(this, typeof location == 'string' ? location : '') // optional location, who cares? - this._db = undefined - this._operations = [] - this._iterators = [] -} - -util.inherits(DeferredLevelDOWN, AbstractLevelDOWN) - -// called by LevelUP when we have a real DB to take its place -DeferredLevelDOWN.prototype.setDb = function (db) { - this._db = db - this._operations.forEach(function (op) { - db[op.method].apply(db, op.args) - }) - this._iterators.forEach(function (it) { - it.setDb(db) - }) -} - -DeferredLevelDOWN.prototype._open = function (options, callback) { - return process.nextTick(callback) -} - -// queue a new deferred operation -DeferredLevelDOWN.prototype._operation = function (method, args) { - if (this._db) - return this._db[method].apply(this._db, args) - this._operations.push({ method: method, args: args }) -} - -// deferrables -'put get del batch approximateSize'.split(' ').forEach(function (m) { - DeferredLevelDOWN.prototype['_' + m] = function () { - this._operation(m, arguments) - } -}) - -DeferredLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) -} - -DeferredLevelDOWN.prototype._iterator = function (options) { - if (this._db) - return this._db.iterator.apply(this._db, arguments) - var it = new DeferredIterator(options) - this._iterators.push(it) - return it -} - -module.exports = DeferredLevelDOWN -module.exports.DeferredIterator = DeferredIterator - -}).call(this,{"isBuffer":require("../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js")},require('_process')) -},{"../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js":993,"./deferred-iterator":121,"_process":1009,"abstract-leveldown":126,"util":1036}],123:[function(require,module,exports){ -(function (process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -function AbstractChainedBatch (db) { - this._db = db - this._operations = [] - this._written = false -} - -AbstractChainedBatch.prototype._checkWritten = function () { - if (this._written) - throw new Error('write() already called on this batch') -} - -AbstractChainedBatch.prototype.put = function (key, value) { - this._checkWritten() - - var err = this._db._checkKey(key, 'key', this._db._isBuffer) - if (err) - throw err - - if (!this._db._isBuffer(key)) key = String(key) - if (!this._db._isBuffer(value)) value = String(value) - - if (typeof this._put == 'function' ) - this._put(key, value) - else - this._operations.push({ type: 'put', key: key, value: value }) - - return this -} - -AbstractChainedBatch.prototype.del = function (key) { - this._checkWritten() - - var err = this._db._checkKey(key, 'key', this._db._isBuffer) - if (err) throw err - - if (!this._db._isBuffer(key)) key = String(key) - - if (typeof this._del == 'function' ) - this._del(key) - else - this._operations.push({ type: 'del', key: key }) - - return this -} - -AbstractChainedBatch.prototype.clear = function () { - this._checkWritten() - - this._operations = [] - - if (typeof this._clear == 'function' ) - this._clear() - - return this -} - -AbstractChainedBatch.prototype.write = function (options, callback) { - this._checkWritten() - - if (typeof options == 'function') - callback = options - if (typeof callback != 'function') - throw new Error('write() requires a callback argument') - if (typeof options != 'object') - options = {} - - this._written = true - - if (typeof this._write == 'function' ) - return this._write(callback) - - if (typeof this._db._batch == 'function') - return this._db._batch(this._operations, options, callback) - - process.nextTick(callback) -} - -module.exports = AbstractChainedBatch -}).call(this,require('_process')) -},{"_process":1009}],124:[function(require,module,exports){ -(function (process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -function AbstractIterator (db) { - this.db = db - this._ended = false - this._nexting = false -} - -AbstractIterator.prototype.next = function (callback) { - var self = this - - if (typeof callback != 'function') - throw new Error('next() requires a callback argument') - - if (self._ended) - return callback(new Error('cannot call next() after end()')) - if (self._nexting) - return callback(new Error('cannot call next() before previous next() has completed')) - - self._nexting = true - if (typeof self._next == 'function') { - return self._next(function () { - self._nexting = false - callback.apply(null, arguments) - }) - } - - process.nextTick(function () { - self._nexting = false - callback() - }) -} - -AbstractIterator.prototype.end = function (callback) { - if (typeof callback != 'function') - throw new Error('end() requires a callback argument') - - if (this._ended) - return callback(new Error('end() already called on iterator')) - - this._ended = true - - if (typeof this._end == 'function') - return this._end(callback) - - process.nextTick(callback) -} - -module.exports = AbstractIterator - -}).call(this,require('_process')) -},{"_process":1009}],125:[function(require,module,exports){ -(function (Buffer,process){ -/* Copyright (c) 2013 Rod Vagg, MIT License */ - -var xtend = require('xtend') - , AbstractIterator = require('./abstract-iterator') - , AbstractChainedBatch = require('./abstract-chained-batch') - -function AbstractLevelDOWN (location) { - if (!arguments.length || location === undefined) - throw new Error('constructor requires at least a location argument') - - if (typeof location != 'string') - throw new Error('constructor requires a location string argument') - - this.location = location - this.status = 'new' -} - -AbstractLevelDOWN.prototype.open = function (options, callback) { - var self = this - , oldStatus = this.status - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('open() requires a callback argument') - - if (typeof options != 'object') - options = {} - - options.createIfMissing = options.createIfMissing != false - options.errorIfExists = !!options.errorIfExists - - if (typeof this._open == 'function') { - this.status = 'opening' - this._open(options, function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'open' - callback() - }) - } else { - this.status = 'open' - process.nextTick(callback) - } -} - -AbstractLevelDOWN.prototype.close = function (callback) { - var self = this - , oldStatus = this.status - - if (typeof callback != 'function') - throw new Error('close() requires a callback argument') - - if (typeof this._close == 'function') { - this.status = 'closing' - this._close(function (err) { - if (err) { - self.status = oldStatus - return callback(err) - } - self.status = 'closed' - callback() - }) - } else { - this.status = 'closed' - process.nextTick(callback) - } -} - -AbstractLevelDOWN.prototype.get = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('get() requires a callback argument') - - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) - - if (!this._isBuffer(key)) - key = String(key) - - if (typeof options != 'object') - options = {} - - options.asBuffer = options.asBuffer != false - - if (typeof this._get == 'function') - return this._get(key, options, callback) - - process.nextTick(function () { callback(new Error('NotFound')) }) -} - -AbstractLevelDOWN.prototype.put = function (key, value, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('put() requires a callback argument') - - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) - - if (!this._isBuffer(key)) - key = String(key) - - // coerce value to string in node, don't touch it in browser - // (indexeddb can store any JS type) - if (value != null && !this._isBuffer(value) && !process.browser) - value = String(value) - - if (typeof options != 'object') - options = {} - - if (typeof this._put == 'function') - return this._put(key, value, options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.del = function (key, options, callback) { - var err - - if (typeof options == 'function') - callback = options - - if (typeof callback != 'function') - throw new Error('del() requires a callback argument') - - if (err = this._checkKey(key, 'key', this._isBuffer)) - return callback(err) - - if (!this._isBuffer(key)) - key = String(key) - - if (typeof options != 'object') - options = {} - - if (typeof this._del == 'function') - return this._del(key, options, callback) - - process.nextTick(callback) -} - -AbstractLevelDOWN.prototype.batch = function (array, options, callback) { - if (!arguments.length) - return this._chainedBatch() - - if (typeof options == 'function') - callback = options - - if (typeof array == 'function') - callback = array - - if (typeof callback != 'function') - throw new Error('batch(array) requires a callback argument') - - if (!Array.isArray(array)) - return callback(new Error('batch(array) requires an array argument')) - - if (!options || typeof options != 'object') - options = {} - - var i = 0 - , l = array.length - , e - , err - - for (; i < l; i++) { - e = array[i] - if (typeof e != 'object') - continue - - if (err = this._checkKey(e.type, 'type', this._isBuffer)) - return callback(err) - - if (err = this._checkKey(e.key, 'key', this._isBuffer)) - return callback(err) - } - - if (typeof this._batch == 'function') - return this._batch(array, options, callback) - - process.nextTick(callback) -} - -//TODO: remove from here, not a necessary primitive -AbstractLevelDOWN.prototype.approximateSize = function (start, end, callback) { - if ( start == null - || end == null - || typeof start == 'function' - || typeof end == 'function') { - throw new Error('approximateSize() requires valid `start`, `end` and `callback` arguments') - } - - if (typeof callback != 'function') - throw new Error('approximateSize() requires a callback argument') - - if (!this._isBuffer(start)) - start = String(start) - - if (!this._isBuffer(end)) - end = String(end) - - if (typeof this._approximateSize == 'function') - return this._approximateSize(start, end, callback) - - process.nextTick(function () { - callback(null, 0) - }) -} - -AbstractLevelDOWN.prototype._setupIteratorOptions = function (options) { - var self = this - - options = xtend(options) - - ;[ 'start', 'end', 'gt', 'gte', 'lt', 'lte' ].forEach(function (o) { - if (options[o] && self._isBuffer(options[o]) && options[o].length === 0) - delete options[o] - }) - - options.reverse = !!options.reverse - options.keys = options.keys != false - options.values = options.values != false - options.limit = 'limit' in options ? options.limit : -1 - options.keyAsBuffer = options.keyAsBuffer != false - options.valueAsBuffer = options.valueAsBuffer != false - - return options -} - -AbstractLevelDOWN.prototype.iterator = function (options) { - if (typeof options != 'object') - options = {} - - options = this._setupIteratorOptions(options) - - if (typeof this._iterator == 'function') - return this._iterator(options) - - return new AbstractIterator(this) -} - -AbstractLevelDOWN.prototype._chainedBatch = function () { - return new AbstractChainedBatch(this) -} - -AbstractLevelDOWN.prototype._isBuffer = function (obj) { - return Buffer.isBuffer(obj) -} - -AbstractLevelDOWN.prototype._checkKey = function (obj, type) { - - if (obj === null || obj === undefined) - return new Error(type + ' cannot be `null` or `undefined`') - - if (this._isBuffer(obj)) { - if (obj.length === 0) - return new Error(type + ' cannot be an empty Buffer') - } else if (String(obj) === '') - return new Error(type + ' cannot be an empty String') -} - -module.exports = AbstractLevelDOWN - -}).call(this,{"isBuffer":require("../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js")},require('_process')) -},{"../../../../../../../../usr/local/lib/node_modules/browserify/node_modules/is-buffer/index.js":993,"./abstract-chained-batch":123,"./abstract-iterator":124,"_process":1009,"xtend":732}],126:[function(require,module,exports){ -exports.AbstractLevelDOWN = require('./abstract-leveldown') -exports.AbstractIterator = require('./abstract-iterator') -exports.AbstractChainedBatch = require('./abstract-chained-batch') -exports.isLevelDOWN = require('./is-leveldown') - -},{"./abstract-chained-batch":123,"./abstract-iterator":124,"./abstract-leveldown":125,"./is-leveldown":127}],127:[function(require,module,exports){ -var AbstractLevelDOWN = require('./abstract-leveldown') - -function isLevelDOWN (db) { - if (!db || typeof db !== 'object') - return false - return Object.keys(AbstractLevelDOWN.prototype).filter(function (name) { - // TODO remove approximateSize check when method is gone - return name[0] != '_' && name != 'approximateSize' - }).every(function (name) { - return typeof db[name] == 'function' - }) -} - -module.exports = isLevelDOWN - -},{"./abstract-leveldown":125}],128:[function(require,module,exports){ -(function (global){ -module.exports = false; - -// Only Node.JS has a process variable that is of [[Class]] process -try { - module.exports = Object.prototype.toString.call(global.process) === '[object process]' -} catch(e) {} - -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],129:[function(require,module,exports){ -(function (Buffer){ -'use strict' -var createHmac = require('create-hmac') -var hashInfo = require('./lib/hash-info.json') - -var ebuf = new Buffer(0) -var b0x00 = new Buffer([ 0x00 ]) -var b0x01 = new Buffer([ 0x01 ]) - -function HmacDRBG (algo, entropy, nonce, pers) { - var info = hashInfo[algo] - if (info === undefined) throw new Error('hash ' + algo + ' is not supported') - - this._algo = algo - this._securityStrength = info.securityStrength / 8 - this._outlen = info.outlen / 8 - this._reseedInterval = 0x1000000000000 // 2**48 - - this._init(entropy, nonce, pers) -} - -HmacDRBG.prototype._update = function (seed) { - var kmac = createHmac(this._algo, this._K).update(this._V).update(b0x00) - if (seed) kmac.update(seed) - - this._K = kmac.digest() - this._V = createHmac(this._algo, this._K).update(this._V).digest() - if (!seed) return - - this._K = createHmac(this._algo, this._K).update(this._V).update(b0x01).update(seed).digest() - this._V = createHmac(this._algo, this._K).update(this._V).digest() -} - -HmacDRBG.prototype._init = function (entropy, nonce, pers) { - if (entropy.length < this._securityStrength) throw new Error('Not enough entropy') - - this._K = new Buffer(this._outlen) - this._V = new Buffer(this._outlen) - for (var i = 0; i < this._K.length; ++i) { - this._K[i] = 0x00 - this._V[i] = 0x01 - } - - this._update(Buffer.concat([ entropy, nonce, pers || ebuf ])) - this._reseed = 1 -} - -HmacDRBG.prototype.reseed = function (entropy, add) { - if (entropy.length < this._securityStrength) throw new Error('Not enough entropy') - - this._update(Buffer.concat([ entropy, add || ebuf ])) - this._reseed = 1 -} - -HmacDRBG.prototype.generate = function (len, add) { - if (this._reseed > this._reseedInterval) throw new Error('Reseed is required') - - if (add && add.length === 0) add = undefined - if (add) this._update(add) - - var temp = new Buffer(0) - while (temp.length < len) { - this._V = createHmac(this._algo, this._K).update(this._V).digest() - temp = Buffer.concat([ temp, this._V ]) - } - - this._update(add) - this._reseed += 1 - return temp.slice(0, len) -} - -module.exports = HmacDRBG - -}).call(this,require("buffer").Buffer) -},{"./lib/hash-info.json":130,"buffer":987,"create-hmac":103}],130:[function(require,module,exports){ -module.exports={ - "sha1": { - "securityStrength": 128, - "outlen": 160, - "seedlen": 440 - }, - "sha224": { - "securityStrength": 192, - "outlen": 224, - "seedlen": 440 - }, - "sha256": { - "securityStrength": 256, - "outlen": 256, - "seedlen": 440 - }, - "sha384": { - "securityStrength": 256, - "outlen": 384, - "seedlen": 888 - }, - "sha512": { - "securityStrength": 256, - "outlen": 512, - "seedlen": 888 - } -} - -},{}],131:[function(require,module,exports){ -(function (process,Buffer){ -var stream = require('readable-stream') -var eos = require('end-of-stream') -var inherits = require('inherits') -var shift = require('stream-shift') - -var SIGNAL_FLUSH = new Buffer([0]) - -var onuncork = function(self, fn) { - if (self._corked) self.once('uncork', fn) - else fn() -} - -var destroyer = function(self, end) { - return function(err) { - if (err) self.destroy(err.message === 'premature close' ? null : err) - else if (end && !self._ended) self.end() - } -} - -var end = function(ws, fn) { - if (!ws) return fn() - if (ws._writableState && ws._writableState.finished) return fn() - if (ws._writableState) return ws.end(fn) - ws.end() - fn() -} - -var toStreams2 = function(rs) { - return new (stream.Readable)({objectMode:true, highWaterMark:16}).wrap(rs) -} - -var Duplexify = function(writable, readable, opts) { - if (!(this instanceof Duplexify)) return new Duplexify(writable, readable, opts) - stream.Duplex.call(this, opts) - - this._writable = null - this._readable = null - this._readable2 = null - - this._forwardDestroy = !opts || opts.destroy !== false - this._forwardEnd = !opts || opts.end !== false - this._corked = 1 // start corked - this._ondrain = null - this._drained = false - this._forwarding = false - this._unwrite = null - this._unread = null - this._ended = false - - this.destroyed = false - - if (writable) this.setWritable(writable) - if (readable) this.setReadable(readable) -} - -inherits(Duplexify, stream.Duplex) - -Duplexify.obj = function(writable, readable, opts) { - if (!opts) opts = {} - opts.objectMode = true - opts.highWaterMark = 16 - return new Duplexify(writable, readable, opts) -} - -Duplexify.prototype.cork = function() { - if (++this._corked === 1) this.emit('cork') -} - -Duplexify.prototype.uncork = function() { - if (this._corked && --this._corked === 0) this.emit('uncork') -} - -Duplexify.prototype.setWritable = function(writable) { - if (this._unwrite) this._unwrite() - - if (this.destroyed) { - if (writable && writable.destroy) writable.destroy() - return - } - - if (writable === null || writable === false) { - this.end() - return - } - - var self = this - var unend = eos(writable, {writable:true, readable:false}, destroyer(this, this._forwardEnd)) - - var ondrain = function() { - var ondrain = self._ondrain - self._ondrain = null - if (ondrain) ondrain() - } - - var clear = function() { - self._writable.removeListener('drain', ondrain) - unend() - } - - if (this._unwrite) process.nextTick(ondrain) // force a drain on stream reset to avoid livelocks - - this._writable = writable - this._writable.on('drain', ondrain) - this._unwrite = clear - - this.uncork() // always uncork setWritable -} - -Duplexify.prototype.setReadable = function(readable) { - if (this._unread) this._unread() - - if (this.destroyed) { - if (readable && readable.destroy) readable.destroy() - return - } - - if (readable === null || readable === false) { - this.push(null) - this.resume() - return - } - - var self = this - var unend = eos(readable, {writable:false, readable:true}, destroyer(this)) - - var onreadable = function() { - self._forward() - } - - var onend = function() { - self.push(null) - } - - var clear = function() { - self._readable2.removeListener('readable', onreadable) - self._readable2.removeListener('end', onend) - unend() - } - - this._drained = true - this._readable = readable - this._readable2 = readable._readableState ? readable : toStreams2(readable) - this._readable2.on('readable', onreadable) - this._readable2.on('end', onend) - this._unread = clear - - this._forward() -} - -Duplexify.prototype._read = function() { - this._drained = true - this._forward() -} - -Duplexify.prototype._forward = function() { - if (this._forwarding || !this._readable2 || !this._drained) return - this._forwarding = true - - var data - - while (this._drained && (data = shift(this._readable2)) !== null) { - if (this.destroyed) continue - this._drained = this.push(data) - } - - this._forwarding = false -} - -Duplexify.prototype.destroy = function(err) { - if (this.destroyed) return - this.destroyed = true - - var self = this - process.nextTick(function() { - self._destroy(err) - }) -} - -Duplexify.prototype._destroy = function(err) { - if (err) { - var ondrain = this._ondrain - this._ondrain = null - if (ondrain) ondrain(err) - else this.emit('error', err) - } - - if (this._forwardDestroy) { - if (this._readable && this._readable.destroy) this._readable.destroy() - if (this._writable && this._writable.destroy) this._writable.destroy() - } - - this.emit('close') -} - -Duplexify.prototype._write = function(data, enc, cb) { - if (this.destroyed) return cb() - if (this._corked) return onuncork(this, this._write.bind(this, data, enc, cb)) - if (data === SIGNAL_FLUSH) return this._finish(cb) - if (!this._writable) return cb() - - if (this._writable.write(data) === false) this._ondrain = cb - else cb() -} - - -Duplexify.prototype._finish = function(cb) { - var self = this - this.emit('preend') - onuncork(this, function() { - end(self._forwardEnd && self._writable, function() { - // haxx to not emit prefinish twice - if (self._writableState.prefinished === false) self._writableState.prefinished = true - self.emit('prefinish') - onuncork(self, cb) - }) - }) -} - -Duplexify.prototype.end = function(data, enc, cb) { - if (typeof data === 'function') return this.end(null, null, data) - if (typeof enc === 'function') return this.end(data, null, enc) - this._ended = true - if (data) this.write(data) - if (!this._writableState.ending) this.write(SIGNAL_FLUSH) - return stream.Writable.prototype.end.call(this, cb) -} - -module.exports = Duplexify - -}).call(this,require('_process'),require("buffer").Buffer) -},{"_process":1009,"buffer":987,"end-of-stream":132,"inherits":216,"readable-stream":142,"stream-shift":713}],132:[function(require,module,exports){ -var once = require('once'); - -var noop = function() {}; - -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; - -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; - - var onfinish = function() { - writable = false; - if (!readable) callback(); - }; - - var onend = function() { - readable = false; - if (!writable) callback(); - }; - - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback(new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback(new Error('premature close')); - }; - - var onrequest = function() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', callback); - stream.on('close', onclose); - - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('end', onend); - stream.removeListener('error', callback); - stream.removeListener('close', onclose); - }; -}; - -module.exports = eos; -},{"once":133}],133:[function(require,module,exports){ -var wrappy = require('wrappy') -module.exports = wrappy(once) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -},{"wrappy":731}],134:[function(require,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. - -// 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. - -'use strict'; - -/**/ - -var processNextTick = require('process-nextick-args'); -/**/ - -/**/ -var objectKeys = Object.keys || function (obj) { - var keys = []; - for (var key in obj) { - keys.push(key); - }return keys; -}; -/**/ - -module.exports = Duplex; - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -var Readable = require('./_stream_readable'); -var Writable = require('./_stream_writable'); - -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); - } -} -},{"./_stream_readable":136,"./_stream_writable":138,"core-util-is":99,"inherits":216,"process-nextick-args":568}],135:[function(require,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. - -// a passthrough stream. -// basically just the most minimal sort of Transform stream. -// Every written chunk gets output as-is. - -'use strict'; - -module.exports = PassThrough; - -var Transform = require('./_stream_transform'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -util.inherits(PassThrough, Transform); - -function PassThrough(options) { - if (!(this instanceof PassThrough)) return new PassThrough(options); - - Transform.call(this, options); -} - -PassThrough.prototype._transform = function (chunk, encoding, cb) { - cb(null, chunk); -}; -},{"./_stream_transform":137,"core-util-is":99,"inherits":216}],136:[function(require,module,exports){ -(function (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. - -'use strict'; - -/**/ - -var processNextTick = require('process-nextick-args'); -/**/ - -module.exports = Readable; - -/**/ -var isArray = require('isarray'); -/**/ - -/**/ -var Duplex; -/**/ - -Readable.ReadableState = ReadableState; - -/**/ -var EE = require('events').EventEmitter; - -var EElistenerCount = function (emitter, type) { - return emitter.listeners(type).length; -}; -/**/ - -/**/ -var Stream = require('./internal/streams/stream'); -/**/ - -// TODO(bmeurer): Change this back to const once hole checks are -// properly optimized away early in Ignition+TurboFan. -/**/ -var Buffer = require('safe-buffer').Buffer; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]' || Buffer.isBuffer(obj); -} -/**/ - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -/**/ -var debugUtil = require('util'); -var debug = void 0; -if (debugUtil && debugUtil.debuglog) { - debug = debugUtil.debuglog('stream'); -} else { - debug = function () {}; -} -/**/ - -var BufferList = require('./internal/streams/BufferList'); -var destroyImpl = require('./internal/streams/destroy'); -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 || require('./_stream_duplex'); - - 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 = require('string_decoder/').StringDecoder; - this.decoder = new StringDecoder(options.encoding); - this.encoding = options.encoding; - } -} - -function Readable(options) { - Duplex = Duplex || require('./_stream_duplex'); - - 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' && Object.getPrototypeOf(chunk) !== Buffer.prototype && !state.objectMode) { - 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 = require('string_decoder/').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; -} -}).call(this,require('_process')) -},{"./_stream_duplex":134,"./internal/streams/BufferList":139,"./internal/streams/destroy":140,"./internal/streams/stream":141,"_process":1009,"core-util-is":99,"events":989,"inherits":216,"isarray":342,"process-nextick-args":568,"safe-buffer":656,"string_decoder/":715,"util":984}],137:[function(require,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. - -// 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. - -'use strict'; - -module.exports = Transform; - -var Duplex = require('./_stream_duplex'); - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -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); -} -},{"./_stream_duplex":134,"core-util-is":99,"inherits":216}],138:[function(require,module,exports){ -(function (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. - -// A bit simpler than readable streams. -// Implement an async ._write(chunk, encoding, cb), and it'll handle all -// the drain event emission and buffering. - -'use strict'; - -/**/ - -var processNextTick = require('process-nextick-args'); -/**/ - -module.exports = Writable; - -/* */ -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); - }; -} -/* */ - -/**/ -var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; -/**/ - -/**/ -var Duplex; -/**/ - -Writable.WritableState = WritableState; - -/**/ -var util = require('core-util-is'); -util.inherits = require('inherits'); -/**/ - -/**/ -var internalUtil = { - deprecate: require('util-deprecate') -}; -/**/ - -/**/ -var Stream = require('./internal/streams/stream'); -/**/ - -/**/ -var Buffer = require('safe-buffer').Buffer; -function _uint8ArrayToBuffer(chunk) { - return Buffer.from(chunk); -} -function _isUint8Array(obj) { - return Object.prototype.toString.call(obj) === '[object Uint8Array]' || Buffer.isBuffer(obj); -} -/**/ - -var destroyImpl = require('./internal/streams/destroy'); - -util.inherits(Writable, Stream); - -function nop() {} - -function WritableState(options, stream) { - Duplex = Duplex || require('./_stream_duplex'); - - 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 || require('./_stream_duplex'); - - // 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) { - /**/ - asyncWrite(afterWrite, stream, state, finished, cb); - /**/ - } 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); -}; - -}).call(this,require('_process')) -},{"./_stream_duplex":134,"./internal/streams/destroy":140,"./internal/streams/stream":141,"_process":1009,"core-util-is":99,"inherits":216,"process-nextick-args":568,"safe-buffer":656,"util-deprecate":720}],139:[function(require,module,exports){ -'use strict'; - -/**/ - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var Buffer = require('safe-buffer').Buffer; -/**/ - -function copyBuffer(src, target, offset) { - src.copy(target, offset); -} - -module.exports = function () { - function BufferList() { - _classCallCheck(this, BufferList); - - this.head = null; - this.tail = null; - this.length = 0; - } - - BufferList.prototype.push = function push(v) { - var entry = { data: v, next: null }; - if (this.length > 0) this.tail.next = entry;else this.head = entry; - this.tail = entry; - ++this.length; - }; - - BufferList.prototype.unshift = function unshift(v) { - var entry = { data: v, next: this.head }; - if (this.length === 0) this.tail = entry; - this.head = entry; - ++this.length; - }; - - BufferList.prototype.shift = function shift() { - if (this.length === 0) return; - var ret = this.head.data; - if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; - --this.length; - return ret; - }; - - BufferList.prototype.clear = function clear() { - this.head = this.tail = null; - this.length = 0; - }; - - BufferList.prototype.join = function join(s) { - if (this.length === 0) return ''; - var p = this.head; - var ret = '' + p.data; - while (p = p.next) { - ret += s + p.data; - }return ret; - }; - - BufferList.prototype.concat = function concat(n) { - if (this.length === 0) return Buffer.alloc(0); - if (this.length === 1) return this.head.data; - var ret = Buffer.allocUnsafe(n >>> 0); - var p = this.head; - var i = 0; - while (p) { - copyBuffer(p.data, ret, i); - i += p.data.length; - p = p.next; - } - return ret; - }; - - return BufferList; -}(); -},{"safe-buffer":656}],140:[function(require,module,exports){ -'use strict'; - -/**/ - -var processNextTick = require('process-nextick-args'); -/**/ - -// 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 -}; -},{"process-nextick-args":568}],141:[function(require,module,exports){ -module.exports = require('events').EventEmitter; - -},{"events":989}],142:[function(require,module,exports){ -exports = module.exports = require('./lib/_stream_readable.js'); -exports.Stream = exports; -exports.Readable = exports; -exports.Writable = require('./lib/_stream_writable.js'); -exports.Duplex = require('./lib/_stream_duplex.js'); -exports.Transform = require('./lib/_stream_transform.js'); -exports.PassThrough = require('./lib/_stream_passthrough.js'); - -},{"./lib/_stream_duplex.js":134,"./lib/_stream_passthrough.js":135,"./lib/_stream_readable.js":136,"./lib/_stream_transform.js":137,"./lib/_stream_writable.js":138}],143:[function(require,module,exports){ -'use strict'; - -var elliptic = exports; - -elliptic.version = require('../package.json').version; -elliptic.utils = require('./elliptic/utils'); -elliptic.rand = require('brorand'); -elliptic.curve = require('./elliptic/curve'); -elliptic.curves = require('./elliptic/curves'); - -// Protocols -elliptic.ec = require('./elliptic/ec'); -elliptic.eddsa = require('./elliptic/eddsa'); - -},{"../package.json":158,"./elliptic/curve":146,"./elliptic/curves":149,"./elliptic/ec":150,"./elliptic/eddsa":153,"./elliptic/utils":157,"brorand":76}],144:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var getNAF = utils.getNAF; -var getJSF = utils.getJSF; -var assert = utils.assert; - -function BaseCurve(type, conf) { - this.type = type; - this.p = new BN(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); - - // Useful for many curves - this.zero = new BN(0).toRed(this.red); - this.one = new BN(1).toRed(this.red); - this.two = new BN(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new BN(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); - - // Generalized Greg Maxwell's trick - var adjustCount = this.n && this.p.div(this.n); - if (!adjustCount || adjustCount.cmpn(100) > 0) { - this.redN = null; - } else { - this._maxwellTrick = true; - this.redN = this.n.toRed(this.red); - } -} -module.exports = BaseCurve; - -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype.validate = function validate() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - assert(p.precomputed); - var doubles = p._getDoubles(); - - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } - - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; - -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - - // Get NAF form - var naf = getNAF(k, w); - - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); - - if (i < 0) - break; - var z = naf[i]; - assert(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; - -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len, - jacobianResult) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; - } - - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; - - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } - - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; - - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); - - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - - if (jacobianResult) - return acc; - else - return acc.toP(); -}; - -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; -} -BaseCurve.BasePoint = BasePoint; - -BasePoint.prototype.eq = function eq(/*other*/) { - throw new Error('Not implemented'); -}; - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - bytes = utils.toArray(bytes, enc); - - var len = this.p.byteLength(); - - // uncompressed, hybrid-odd, hybrid-even - if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && - bytes.length - 1 === 2 * len) { - if (bytes[0] === 0x06) - assert(bytes[bytes.length - 1] % 2 === 0); - else if (bytes[0] === 0x07) - assert(bytes[bytes.length - 1] % 2 === 1); - - var res = this.point(bytes.slice(1, 1 + len), - bytes.slice(1 + len, 1 + 2 * len)); - - return res; - } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && - bytes.length - 1 === len) { - return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); - } - throw new Error('Unknown point format'); -}; - -BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { - return this.encode(enc, true); -}; - -BasePoint.prototype._encode = function _encode(compact) { - var len = this.curve.p.byteLength(); - var x = this.getX().toArray('be', len); - - if (compact) - return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); - - return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; -}; - -BasePoint.prototype.encode = function encode(enc, compact) { - return utils.encode(this._encode(compact), enc); -}; - -BasePoint.prototype.precompute = function precompute(power) { - if (this.precomputed) - return this; - - var precomputed = { - doubles: null, - naf: null, - beta: null - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._hasDoubles = function _hasDoubles(k) { - if (!this.precomputed) - return false; - - var doubles = this.precomputed.doubles; - if (!doubles) - return false; - - return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; - -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; - -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; - -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; - -},{"../../elliptic":143,"bn.js":66}],145:[function(require,module,exports){ -'use strict'; - -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var assert = elliptic.utils.assert; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = (conf.a | 0) !== 1; - this.mOneA = this.twisted && (conf.a | 0) === -1; - this.extended = this.mOneA; - - Base.call(this, 'edwards', conf); - - this.a = new BN(conf.a, 16).umod(this.red.m); - this.a = this.a.toRed(this.red); - this.c = new BN(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new BN(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = (conf.c | 0) === 1; -} -inherits(EdwardsCurve, Base); -module.exports = EdwardsCurve; - -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; - -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); -}; - -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; - -EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); - - var y2 = rhs.redMul(lhs.redInvm()); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { - y = new BN(y, 16); - if (!y.red) - y = y.toRed(this.red); - - // x^2 = (y^2 - 1) / (d y^2 + 1) - var y2 = y.redSqr(); - var lhs = y2.redSub(this.one); - var rhs = y2.redMul(this.d).redAdd(this.one); - var x2 = lhs.redMul(rhs.redInvm()); - - if (x2.cmp(this.zero) === 0) { - if (odd) - throw new Error('invalid point'); - else - return this.point(this.zero, y); - } - - var x = x2.redSqrt(); - if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - if (x.isOdd() !== odd) - x = x.redNeg(); - - return this.point(x, y); -}; - -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; - -function Point(curve, x, y, z, t) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = z ? new BN(z, 16) : this.curve.one; - this.t = t && new BN(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits(Point, Base.BasePoint); - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; - -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); -}; - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - this.y.cmp(this.z) === 0; -}; - -Point.prototype._extDbl = function _extDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projDbl = function _projDbl() { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #doubling-dbl-2008-bbjlp - // #doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - var nx; - var ny; - var nz; - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - ny = f.redMul(e.redSub(d)); - // Z3 = F * J - nz = f.redMul(j); - } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point.prototype._extAdd = function _extAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html - // #addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projAdd = function _projAdd(p) { - // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html - // #addition-add-2008-bbjlp - // #addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - var ny; - var nz; - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - nz = this.curve._mulC(f).redMul(g); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; - -Point.prototype.mul = function mul(k) { - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); -}; - -Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; - -Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; - -Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; - -Point.prototype.eq = function eq(other) { - return this === other || - this.getX().cmp(other.getX()) === 0 && - this.getY().cmp(other.getY()) === 0; -}; - -Point.prototype.eqXToP = function eqXToP(x) { - var rx = x.toRed(this.curve.red).redMul(this.z); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(this.z); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - return false; -}; - -// Compatibility with BaseCurve -Point.prototype.toP = Point.prototype.normalize; -Point.prototype.mixedAdd = Point.prototype.add; - -},{"../../elliptic":143,"../curve":146,"bn.js":66,"inherits":216}],146:[function(require,module,exports){ -'use strict'; - -var curve = exports; - -curve.base = require('./base'); -curve.short = require('./short'); -curve.mont = require('./mont'); -curve.edwards = require('./edwards'); - -},{"./base":144,"./edwards":145,"./mont":147,"./short":148}],147:[function(require,module,exports){ -'use strict'; - -var curve = require('../curve'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; - -function MontCurve(conf) { - Base.call(this, 'mont', conf); - - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.i4 = new BN(4).toRed(this.red).redInvm(); - this.two = new BN(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); -} -inherits(MontCurve, Base); -module.exports = MontCurve; - -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); - - return y.redSqr().cmp(rhs) === 0; -}; - -function Point(curve, x, z) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new BN(x, 16); - this.z = new BN(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } -} -inherits(Point, Base.BasePoint); - -MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { - return this.point(utils.toArray(bytes, enc), 1); -}; - -MontCurve.prototype.point = function point(x, z) { - return new Point(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; - -Point.prototype.precompute = function precompute() { - // No-op -}; - -Point.prototype._encode = function _encode() { - return this.getX().toArray('be', this.curve.p.byteLength()); -}; - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1] || curve.one); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -Point.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; - -Point.prototype.add = function add() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; - -Point.prototype.mul = function mul(k) { - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q - - for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) - bits.push(t.andln(1)); - - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } - } - return b; -}; - -Point.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.jumlAdd = function jumlAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.eq = function eq(other) { - return this.getX().cmp(other.getX()) === 0; -}; - -Point.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); -}; - -},{"../../elliptic":143,"../curve":146,"bn.js":66,"inherits":216}],148:[function(require,module,exports){ -'use strict'; - -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var BN = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var assert = elliptic.utils.assert; - -function ShortCurve(conf) { - Base.call(this, 'short', conf); - - this.a = new BN(conf.a, 16).toRed(this.red); - this.b = new BN(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits(ShortCurve, Base); -module.exports = ShortCurve; - -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; - - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new BN(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new BN(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new BN(vec.a, 16), - b: new BN(vec.b, 16) - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis - }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : BN.mont(num); - var tinv = new BN(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - - var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; - -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new BN(1); - var y1 = new BN(0); - var x2 = new BN(0); - var y2 = new BN(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - var r; - var x; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - r = v.sub(q.mul(u)); - x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.negative) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.negative) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { - x = new BN(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) - throw new Error('invalid point'); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; - - var x = point.x; - var y = point.y; - - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; - -ShortCurve.prototype._endoWnafMulAdd = - function _endoWnafMulAdd(points, coeffs, jacobianResult) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); - - if (split.k1.negative) { - split.k1.ineg(); - p = p.neg(true); - } - if (split.k2.negative) { - split.k2.ineg(); - beta = beta.neg(true); - } - - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); - - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; - -function Point(curve, x, y, isRed) { - Base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits(Point, Base.BasePoint); - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; - -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; - - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; - - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - var endoMul = function(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - }; - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; -}; - -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; - - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - } ]; -}; - -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; - - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } - - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) - } - }; - return res; -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; - -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; - - // P + O = P - if (p.inf) - return this; - - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); - - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); - - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; - - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - - var a = this.curve.a; - - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; - -Point.prototype.mul = function mul(k) { - k = new BN(k, 16); - - if (this._hasDoubles(k)) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; - -Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs, true); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2, true); -}; - -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; - -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; - - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - var negate = function(p) { - return p.neg(); - }; - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) - } - }; - } - return res; -}; - -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); - - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; - -function JPoint(curve, x, y, z) { - Base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new BN(0); - } else { - this.x = new BN(x, 16); - this.y = new BN(y, 16); - this.z = new BN(z, 16); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits(JPoint, Base.BasePoint); - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; - -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; - - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); - - // P + O = P - if (p.isInfinity()) - return this; - - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); - - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } - - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); - - jx = nx; - jz = nz; - jyd = dny; - } - - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; - -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; - -JPoint.prototype._zeroDbl = function _zeroDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html - // #doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._threeDbl = function _threeDbl() { - var nx; - var ny; - var nz; - // Z = 1 - if (this.zOne) { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html - // #doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - nz = this.y.redAdd(this.y); - } else { - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; - - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); - - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mul = function mul(k, kbase) { - k = new BN(k, kbase); - - return this.curve._wnafMul(this, k); -}; - -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); - - if (this === p) - return true; - - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; - - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; - -JPoint.prototype.eqXToP = function eqXToP(x) { - var zs = this.z.redSqr(); - var rx = x.toRed(this.curve.red).redMul(zs); - if (this.x.cmp(rx) === 0) - return true; - - var xc = x.clone(); - var t = this.curve.redN.redMul(zs); - for (;;) { - xc.iadd(this.curve.n); - if (xc.cmp(this.curve.p) >= 0) - return false; - - rx.redIAdd(t); - if (this.x.cmp(rx) === 0) - return true; - } - return false; -}; - -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -},{"../../elliptic":143,"../curve":146,"bn.js":66,"inherits":216}],149:[function(require,module,exports){ -'use strict'; - -var curves = exports; - -var hash = require('hash.js'); -var elliptic = require('../elliptic'); - -var assert = elliptic.utils.assert; - -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new elliptic.curve.short(options); - else if (options.type === 'edwards') - this.curve = new elliptic.curve.edwards(options); - else - this.curve = new elliptic.curve.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; - - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); -} -curves.PresetCurve = PresetCurve; - -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); -} - -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ] -}); - -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ] -}); - -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ] -}); - -defineCurve('p384', { - type: 'short', - prime: null, - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 ffffffff', - a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'fffffffe ffffffff 00000000 00000000 fffffffc', - b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + - '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', - n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + - 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', - hash: hash.sha384, - gRed: false, - g: [ - 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + - '5502f25d bf55296c 3a545e38 72760ab7', - '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + - '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' - ] -}); - -defineCurve('p521', { - type: 'short', - prime: null, - p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff', - a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff ffffffff ffffffff fffffffc', - b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + - '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + - '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', - n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + - 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + - 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', - hash: hash.sha512, - gRed: false, - g: [ - '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + - '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + - 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', - '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + - '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + - '3fad0761 353c7086 a272c240 88be9476 9fd16650' - ] -}); - -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '1', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '9' - ] -}); - -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); - -var pre; -try { - pre = require('./precomputed/secp256k1'); -} catch (e) { - pre = undefined; -} - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], - - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - pre - ] -}); - -},{"../elliptic":143,"./precomputed/secp256k1":156,"hash.js":177}],150:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var HmacDRBG = require('hmac-drbg'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; - -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); - - options = elliptic.curves[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof elliptic.curves.PresetCurve) - options = { curve: options }; - - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.ushrn(1); - this.g = this.curve.g; - - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; -} -module.exports = EC; - -EC.prototype.keyPair = function keyPair(options) { - return new KeyPair(this, options); -}; - -EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { - return KeyPair.fromPrivate(this, priv, enc); -}; - -EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { - return KeyPair.fromPublic(this, pub, enc); -}; - -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - pers: options.pers, - persEnc: options.persEnc || 'utf8', - entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), - entropyEnc: options.entropy && options.entropyEnc || 'utf8', - nonce: this.n.toArray() - }); - - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new BN(2)); - do { - var priv = new BN(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyFromPrivate(priv); - } while (true); -}; - -EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { - var delta = msg.byteLength() * 8 - this.n.bitLength(); - if (delta > 0) - msg = msg.ushrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; - -EC.prototype.sign = function sign(msg, key, enc, options) { - if (typeof enc === 'object') { - options = enc; - enc = null; - } - if (!options) - options = {}; - - key = this.keyFromPrivate(key, enc); - msg = this._truncateToN(new BN(msg, 16)); - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray('be', bytes); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray('be', bytes); - - // Instantiate Hmac_DRBG - var drbg = new HmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce: nonce, - pers: options.pers, - persEnc: options.persEnc || 'utf8' - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new BN(1)); - - for (var iter = 0; true; iter++) { - var k = options.k ? - options.k(iter) : - new BN(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; - - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; - - var kpX = kp.getX(); - var r = kpX.umod(this.n); - if (r.cmpn(0) === 0) - continue; - - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); - s = s.umod(this.n); - if (s.cmpn(0) === 0) - continue; - - var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | - (kpX.cmp(r) !== 0 ? 2 : 0); - - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) { - s = this.n.sub(s); - recoveryParam ^= 1; - } - - return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); - } -}; - -EC.prototype.verify = function verify(msg, signature, key, enc) { - msg = this._truncateToN(new BN(msg, 16)); - key = this.keyFromPublic(key, enc); - signature = new Signature(signature, 'hex'); - - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; - - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).umod(this.n); - var u2 = sinv.mul(r).umod(this.n); - - if (!this.curve._maxwellTrick) { - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - return p.getX().umod(this.n).cmp(r) === 0; - } - - // NOTE: Greg Maxwell's trick, inspired by: - // https://git.io/vad3K - - var p = this.g.jmulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - // Compare `p.x` of Jacobian point with `r`, - // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the - // inverse of `p.z^2` - return p.eqXToP(r); -}; - -EC.prototype.recoverPubKey = function(msg, signature, j, enc) { - assert((3 & j) === j, 'The recovery param is more than two bits'); - signature = new Signature(signature, enc); - - var n = this.n; - var e = new BN(msg); - var r = signature.r; - var s = signature.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = j & 1; - var isSecondKey = j >> 1; - if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) - throw new Error('Unable to find sencond key candinate'); - - // 1.1. Let x = r + jn. - if (isSecondKey) - r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); - else - r = this.curve.pointFromX(r, isYOdd); - - var rInv = signature.r.invm(n); - var s1 = n.sub(e).mul(rInv).umod(n); - var s2 = s.mul(rInv).umod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - return this.g.mulAdd(s1, r, s2); -}; - -EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { - signature = new Signature(signature, enc); - if (signature.recoveryParam !== null) - return signature.recoveryParam; - - for (var i = 0; i < 4; i++) { - var Qprime; - try { - Qprime = this.recoverPubKey(e, signature, i); - } catch (e) { - continue; - } - - if (Qprime.eq(Q)) - return i; - } - throw new Error('Unable to find valid recovery factor'); -}; - -},{"../../elliptic":143,"./key":151,"./signature":152,"bn.js":66,"hmac-drbg":189}],151:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; - -function KeyPair(ec, options) { - this.ec = ec; - this.priv = null; - this.pub = null; - - // KeyPair(ec, { priv: ..., pub: ... }) - if (options.priv) - this._importPrivate(options.priv, options.privEnc); - if (options.pub) - this._importPublic(options.pub, options.pubEnc); -} -module.exports = KeyPair; - -KeyPair.fromPublic = function fromPublic(ec, pub, enc) { - if (pub instanceof KeyPair) - return pub; - - return new KeyPair(ec, { - pub: pub, - pubEnc: enc - }); -}; - -KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { - if (priv instanceof KeyPair) - return priv; - - return new KeyPair(ec, { - priv: priv, - privEnc: enc - }); -}; - -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); - - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; - - return { result: true, reason: null }; -}; - -KeyPair.prototype.getPublic = function getPublic(compact, enc) { - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } - - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); - - if (!enc) - return this.pub; - - return this.pub.encode(enc, compact); -}; - -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; - -KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { - this.priv = new BN(key, enc || 16); - - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.umod(this.ec.curve.n); -}; - -KeyPair.prototype._importPublic = function _importPublic(key, enc) { - if (key.x || key.y) { - // Montgomery points only have an `x` coordinate. - // Weierstrass/Edwards points on the other hand have both `x` and - // `y` coordinates. - if (this.ec.curve.type === 'mont') { - assert(key.x, 'Need x coordinate'); - } else if (this.ec.curve.type === 'short' || - this.ec.curve.type === 'edwards') { - assert(key.x && key.y, 'Need both x and y coordinate'); - } - this.pub = this.ec.curve.point(key.x, key.y); - return; - } - this.pub = this.ec.curve.decodePoint(key, enc); -}; - -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); -}; - -// ECDSA -KeyPair.prototype.sign = function sign(msg, enc, options) { - return this.ec.sign(msg, this, enc, options); -}; - -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; - -KeyPair.prototype.inspect = function inspect() { - return ''; -}; - -},{"../../elliptic":143,"bn.js":66}],152:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; - -function Signature(options, enc) { - if (options instanceof Signature) - return options; - - if (this._importDER(options, enc)) - return; - - assert(options.r && options.s, 'Signature without r or s'); - this.r = new BN(options.r, 16); - this.s = new BN(options.s, 16); - if (options.recoveryParam === undefined) - this.recoveryParam = null; - else - this.recoveryParam = options.recoveryParam; -} -module.exports = Signature; - -function Position() { - this.place = 0; -} - -function getLength(buf, p) { - var initial = buf[p.place++]; - if (!(initial & 0x80)) { - return initial; - } - var octetLen = initial & 0xf; - var val = 0; - for (var i = 0, off = p.place; i < octetLen; i++, off++) { - val <<= 8; - val |= buf[off]; - } - p.place = off; - return val; -} - -function rmPadding(buf) { - var i = 0; - var len = buf.length - 1; - while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { - i++; - } - if (i === 0) { - return buf; - } - return buf.slice(i); -} - -Signature.prototype._importDER = function _importDER(data, enc) { - data = utils.toArray(data, enc); - var p = new Position(); - if (data[p.place++] !== 0x30) { - return false; - } - var len = getLength(data, p); - if ((len + p.place) !== data.length) { - return false; - } - if (data[p.place++] !== 0x02) { - return false; - } - var rlen = getLength(data, p); - var r = data.slice(p.place, rlen + p.place); - p.place += rlen; - if (data[p.place++] !== 0x02) { - return false; - } - var slen = getLength(data, p); - if (data.length !== slen + p.place) { - return false; - } - var s = data.slice(p.place, slen + p.place); - if (r[0] === 0 && (r[1] & 0x80)) { - r = r.slice(1); - } - if (s[0] === 0 && (s[1] & 0x80)) { - s = s.slice(1); - } - - this.r = new BN(r); - this.s = new BN(s); - this.recoveryParam = null; - - return true; -}; - -function constructLength(arr, len) { - if (len < 0x80) { - arr.push(len); - return; - } - var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); - arr.push(octets | 0x80); - while (--octets) { - arr.push((len >>> (octets << 3)) & 0xff); - } - arr.push(len); -} - -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - r = rmPadding(r); - s = rmPadding(s); - - while (!s[0] && !(s[1] & 0x80)) { - s = s.slice(1); - } - var arr = [ 0x02 ]; - constructLength(arr, r.length); - arr = arr.concat(r); - arr.push(0x02); - constructLength(arr, s.length); - var backHalf = arr.concat(s); - var res = [ 0x30 ]; - constructLength(res, backHalf.length); - res = res.concat(backHalf); - return utils.encode(res, enc); -}; - -},{"../../elliptic":143,"bn.js":66}],153:[function(require,module,exports){ -'use strict'; - -var hash = require('hash.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EDDSA(curve) { - assert(curve === 'ed25519', 'only tested with ed25519 so far'); - - if (!(this instanceof EDDSA)) - return new EDDSA(curve); - - var curve = elliptic.curves[curve].curve; - this.curve = curve; - this.g = curve.g; - this.g.precompute(curve.n.bitLength() + 1); - - this.pointClass = curve.point().constructor; - this.encodingLength = Math.ceil(curve.n.bitLength() / 8); - this.hash = hash.sha512; -} - -module.exports = EDDSA; - -/** -* @param {Array|String} message - message bytes -* @param {Array|String|KeyPair} secret - secret bytes or a keypair -* @returns {Signature} - signature -*/ -EDDSA.prototype.sign = function sign(message, secret) { - message = parseBytes(message); - var key = this.keyFromSecret(secret); - var r = this.hashInt(key.messagePrefix(), message); - var R = this.g.mul(r); - var Rencoded = this.encodePoint(R); - var s_ = this.hashInt(Rencoded, key.pubBytes(), message) - .mul(key.priv()); - var S = r.add(s_).umod(this.curve.n); - return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); -}; - -/** -* @param {Array} message - message bytes -* @param {Array|String|Signature} sig - sig bytes -* @param {Array|String|Point|KeyPair} pub - public key -* @returns {Boolean} - true if public key matches sig of message -*/ -EDDSA.prototype.verify = function verify(message, sig, pub) { - message = parseBytes(message); - sig = this.makeSignature(sig); - var key = this.keyFromPublic(pub); - var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message); - var SG = this.g.mul(sig.S()); - var RplusAh = sig.R().add(key.pub().mul(h)); - return RplusAh.eq(SG); -}; - -EDDSA.prototype.hashInt = function hashInt() { - var hash = this.hash(); - for (var i = 0; i < arguments.length; i++) - hash.update(arguments[i]); - return utils.intFromLE(hash.digest()).umod(this.curve.n); -}; - -EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { - return KeyPair.fromPublic(this, pub); -}; - -EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { - return KeyPair.fromSecret(this, secret); -}; - -EDDSA.prototype.makeSignature = function makeSignature(sig) { - if (sig instanceof Signature) - return sig; - return new Signature(this, sig); -}; - -/** -* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 -* -* EDDSA defines methods for encoding and decoding points and integers. These are -* helper convenience methods, that pass along to utility functions implied -* parameters. -* -*/ -EDDSA.prototype.encodePoint = function encodePoint(point) { - var enc = point.getY().toArray('le', this.encodingLength); - enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0; - return enc; -}; - -EDDSA.prototype.decodePoint = function decodePoint(bytes) { - bytes = utils.parseBytes(bytes); - - var lastIx = bytes.length - 1; - var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); - var xIsOdd = (bytes[lastIx] & 0x80) !== 0; - - var y = utils.intFromLE(normed); - return this.curve.pointFromY(y, xIsOdd); -}; - -EDDSA.prototype.encodeInt = function encodeInt(num) { - return num.toArray('le', this.encodingLength); -}; - -EDDSA.prototype.decodeInt = function decodeInt(bytes) { - return utils.intFromLE(bytes); -}; - -EDDSA.prototype.isPoint = function isPoint(val) { - return val instanceof this.pointClass; -}; - -},{"../../elliptic":143,"./key":154,"./signature":155,"hash.js":177}],154:[function(require,module,exports){ -'use strict'; - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var parseBytes = utils.parseBytes; -var cachedProperty = utils.cachedProperty; - -/** -* @param {EDDSA} eddsa - instance -* @param {Object} params - public/private key parameters -* -* @param {Array} [params.secret] - secret seed bytes -* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) -* @param {Array} [params.pub] - public key point encoded as bytes -* -*/ -function KeyPair(eddsa, params) { - this.eddsa = eddsa; - this._secret = parseBytes(params.secret); - if (eddsa.isPoint(params.pub)) - this._pub = params.pub; - else - this._pubBytes = parseBytes(params.pub); -} - -KeyPair.fromPublic = function fromPublic(eddsa, pub) { - if (pub instanceof KeyPair) - return pub; - return new KeyPair(eddsa, { pub: pub }); -}; - -KeyPair.fromSecret = function fromSecret(eddsa, secret) { - if (secret instanceof KeyPair) - return secret; - return new KeyPair(eddsa, { secret: secret }); -}; - -KeyPair.prototype.secret = function secret() { - return this._secret; -}; - -cachedProperty(KeyPair, 'pubBytes', function pubBytes() { - return this.eddsa.encodePoint(this.pub()); -}); - -cachedProperty(KeyPair, 'pub', function pub() { - if (this._pubBytes) - return this.eddsa.decodePoint(this._pubBytes); - return this.eddsa.g.mul(this.priv()); -}); - -cachedProperty(KeyPair, 'privBytes', function privBytes() { - var eddsa = this.eddsa; - var hash = this.hash(); - var lastIx = eddsa.encodingLength - 1; - - var a = hash.slice(0, eddsa.encodingLength); - a[0] &= 248; - a[lastIx] &= 127; - a[lastIx] |= 64; - - return a; -}); - -cachedProperty(KeyPair, 'priv', function priv() { - return this.eddsa.decodeInt(this.privBytes()); -}); - -cachedProperty(KeyPair, 'hash', function hash() { - return this.eddsa.hash().update(this.secret()).digest(); -}); - -cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { - return this.hash().slice(this.eddsa.encodingLength); -}); - -KeyPair.prototype.sign = function sign(message) { - assert(this._secret, 'KeyPair can only verify'); - return this.eddsa.sign(message, this); -}; - -KeyPair.prototype.verify = function verify(message, sig) { - return this.eddsa.verify(message, sig, this); -}; - -KeyPair.prototype.getSecret = function getSecret(enc) { - assert(this._secret, 'KeyPair is public only'); - return utils.encode(this.secret(), enc); -}; - -KeyPair.prototype.getPublic = function getPublic(enc) { - return utils.encode(this.pubBytes(), enc); -}; - -module.exports = KeyPair; - -},{"../../elliptic":143}],155:[function(require,module,exports){ -'use strict'; - -var BN = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; -var assert = utils.assert; -var cachedProperty = utils.cachedProperty; -var parseBytes = utils.parseBytes; - -/** -* @param {EDDSA} eddsa - eddsa instance -* @param {Array|Object} sig - -* @param {Array|Point} [sig.R] - R point as Point or bytes -* @param {Array|bn} [sig.S] - S scalar as bn or bytes -* @param {Array} [sig.Rencoded] - R point encoded -* @param {Array} [sig.Sencoded] - S scalar encoded -*/ -function Signature(eddsa, sig) { - this.eddsa = eddsa; - - if (typeof sig !== 'object') - sig = parseBytes(sig); - - if (Array.isArray(sig)) { - sig = { - R: sig.slice(0, eddsa.encodingLength), - S: sig.slice(eddsa.encodingLength) - }; - } - - assert(sig.R && sig.S, 'Signature without R or S'); - - if (eddsa.isPoint(sig.R)) - this._R = sig.R; - if (sig.S instanceof BN) - this._S = sig.S; - - this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; - this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; -} - -cachedProperty(Signature, 'S', function S() { - return this.eddsa.decodeInt(this.Sencoded()); -}); - -cachedProperty(Signature, 'R', function R() { - return this.eddsa.decodePoint(this.Rencoded()); -}); - -cachedProperty(Signature, 'Rencoded', function Rencoded() { - return this.eddsa.encodePoint(this.R()); -}); - -cachedProperty(Signature, 'Sencoded', function Sencoded() { - return this.eddsa.encodeInt(this.S()); -}); - -Signature.prototype.toBytes = function toBytes() { - return this.Rencoded().concat(this.Sencoded()); -}; - -Signature.prototype.toHex = function toHex() { - return utils.encode(this.toBytes(), 'hex').toUpperCase(); -}; - -module.exports = Signature; - -},{"../../elliptic":143,"bn.js":66}],156:[function(require,module,exports){ -module.exports = { - doubles: { - step: 4, - points: [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - naf: { - wnd: 7, - points: [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] - } -}; - -},{}],157:[function(require,module,exports){ -'use strict'; - -var utils = exports; -var BN = require('bn.js'); -var minAssert = require('minimalistic-assert'); -var minUtils = require('minimalistic-crypto-utils'); - -utils.assert = minAssert; -utils.toArray = minUtils.toArray; -utils.zero2 = minUtils.zero2; -utils.toHex = minUtils.toHex; -utils.encode = minUtils.encode; - -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; - } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.iushrn(shift); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; - } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.iushrn(1); - k2.iushrn(1); - } - - return jsf; -} -utils.getJSF = getJSF; - -function cachedProperty(obj, name, computer) { - var key = '_' + name; - obj.prototype[name] = function cachedProperty() { - return this[key] !== undefined ? this[key] : - this[key] = computer.call(this); - }; -} -utils.cachedProperty = cachedProperty; - -function parseBytes(bytes) { - return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : - bytes; -} -utils.parseBytes = parseBytes; - -function intFromLE(bytes) { - return new BN(bytes, 'hex', 'le'); -} -utils.intFromLE = intFromLE; - - -},{"bn.js":66,"minimalistic-assert":509,"minimalistic-crypto-utils":510}],158:[function(require,module,exports){ -module.exports={ - "_args": [ - [ - { - "raw": "elliptic@^6.2.3", - "scope": null, - "escapedName": "elliptic", - "name": "elliptic", - "rawSpec": "^6.2.3", - "spec": ">=6.2.3 <7.0.0", - "type": "range" - }, - "/Users/koruza/code/js-ipfs/node_modules/secp256k1" - ] - ], - "_from": "elliptic@>=6.2.3 <7.0.0", - "_id": "elliptic@6.4.0", - "_inCache": true, - "_location": "/elliptic", - "_nodeVersion": "7.0.0", - "_npmOperationalInternal": { - "host": "packages-18-east.internal.npmjs.com", - "tmp": "tmp/elliptic-6.4.0.tgz_1487798866428_0.30510620190761983" - }, - "_npmUser": { - "name": "indutny", - "email": "fedor@indutny.com" - }, - "_npmVersion": "3.10.8", - "_phantomChildren": {}, - "_requested": { - "raw": "elliptic@^6.2.3", - "scope": null, - "escapedName": "elliptic", - "name": "elliptic", - "rawSpec": "^6.2.3", - "spec": ">=6.2.3 <7.0.0", - "type": "range" - }, - "_requiredBy": [ - "/browserify-sign", - "/create-ecdh", - "/secp256k1" - ], - "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz", - "_shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df", - "_shrinkwrap": null, - "_spec": "elliptic@^6.2.3", - "_where": "/Users/koruza/code/js-ipfs/node_modules/secp256k1", - "author": { - "name": "Fedor Indutny", - "email": "fedor@indutny.com" - }, - "bugs": { - "url": "https://github.com/indutny/elliptic/issues" - }, - "dependencies": { - "bn.js": "^4.4.0", - "brorand": "^1.0.1", - "hash.js": "^1.0.0", - "hmac-drbg": "^1.0.0", - "inherits": "^2.0.1", - "minimalistic-assert": "^1.0.0", - "minimalistic-crypto-utils": "^1.0.0" - }, - "description": "EC cryptography", - "devDependencies": { - "brfs": "^1.4.3", - "coveralls": "^2.11.3", - "grunt": "^0.4.5", - "grunt-browserify": "^5.0.0", - "grunt-cli": "^1.2.0", - "grunt-contrib-connect": "^1.0.0", - "grunt-contrib-copy": "^1.0.0", - "grunt-contrib-uglify": "^1.0.1", - "grunt-mocha-istanbul": "^3.0.1", - "grunt-saucelabs": "^8.6.2", - "istanbul": "^0.4.2", - "jscs": "^2.9.0", - "jshint": "^2.6.0", - "mocha": "^2.1.0" - }, - "directories": {}, - "dist": { - "shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df", - "tarball": "https://registry.npmjs.org/elliptic/-/elliptic-6.4.0.tgz" - }, - "files": [ - "lib" - ], - "gitHead": "6b0d2b76caae91471649c8e21f0b1d3ba0f96090", - "homepage": "https://github.com/indutny/elliptic", - "keywords": [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ], - "license": "MIT", - "main": "lib/elliptic.js", - "maintainers": [ - { - "name": "indutny", - "email": "fedor@indutny.com" - } - ], - "name": "elliptic", - "optionalDependencies": {}, - "readme": "ERROR: No README data found!", - "repository": { - "type": "git", - "url": "git+ssh://git@github.com/indutny/elliptic.git" - }, - "scripts": { - "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", - "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", - "lint": "npm run jscs && npm run jshint", - "test": "npm run lint && npm run unit", - "unit": "istanbul test _mocha --reporter=spec test/index.js", - "version": "grunt dist && git add dist/" - }, - "version": "6.4.0" -} - -},{}],159:[function(require,module,exports){ -var once = require('once'); - -var noop = function() {}; - -var isRequest = function(stream) { - return stream.setHeader && typeof stream.abort === 'function'; -}; - -var isChildProcess = function(stream) { - return stream.stdio && Array.isArray(stream.stdio) && stream.stdio.length === 3 -}; - -var eos = function(stream, opts, callback) { - if (typeof opts === 'function') return eos(stream, null, opts); - if (!opts) opts = {}; - - callback = once(callback || noop); - - var ws = stream._writableState; - var rs = stream._readableState; - var readable = opts.readable || (opts.readable !== false && stream.readable); - var writable = opts.writable || (opts.writable !== false && stream.writable); - - var onlegacyfinish = function() { - if (!stream.writable) onfinish(); - }; - - var onfinish = function() { - writable = false; - if (!readable) callback.call(stream); - }; - - var onend = function() { - readable = false; - if (!writable) callback.call(stream); - }; - - var onexit = function(exitCode) { - callback.call(stream, exitCode ? new Error('exited with error code: ' + exitCode) : null); - }; - - var onclose = function() { - if (readable && !(rs && rs.ended)) return callback.call(stream, new Error('premature close')); - if (writable && !(ws && ws.ended)) return callback.call(stream, new Error('premature close')); - }; - - var onrequest = function() { - stream.req.on('finish', onfinish); - }; - - if (isRequest(stream)) { - stream.on('complete', onfinish); - stream.on('abort', onclose); - if (stream.req) onrequest(); - else stream.on('request', onrequest); - } else if (writable && !ws) { // legacy streams - stream.on('end', onlegacyfinish); - stream.on('close', onlegacyfinish); - } - - if (isChildProcess(stream)) stream.on('exit', onexit); - - stream.on('end', onend); - stream.on('finish', onfinish); - if (opts.error !== false) stream.on('error', callback); - stream.on('close', onclose); - - return function() { - stream.removeListener('complete', onfinish); - stream.removeListener('abort', onclose); - stream.removeListener('request', onrequest); - if (stream.req) stream.req.removeListener('finish', onfinish); - stream.removeListener('end', onlegacyfinish); - stream.removeListener('close', onlegacyfinish); - stream.removeListener('finish', onfinish); - stream.removeListener('exit', onexit); - stream.removeListener('end', onend); - stream.removeListener('error', callback); - stream.removeListener('close', onclose); - }; -}; - -module.exports = eos; - -},{"once":562}],160:[function(require,module,exports){ -var prr = require('prr') - -function init (type, message, cause) { - prr(this, { - type : type - , name : type - // can be passed just a 'cause' - , cause : typeof message != 'string' ? message : cause - , message : !!message && typeof message != 'string' ? message.message : message - - }, 'ewr') -} - -// generic prototype, not intended to be actually used - helpful for `instanceof` -function CustomError (message, cause) { - Error.call(this) - if (Error.captureStackTrace) - Error.captureStackTrace(this, arguments.callee) - init.call(this, 'CustomError', message, cause) -} - -CustomError.prototype = new Error() - -function createError (errno, type, proto) { - var err = function (message, cause) { - init.call(this, type, message, cause) - //TODO: the specificity here is stupid, errno should be available everywhere - if (type == 'FilesystemError') { - this.code = this.cause.code - this.path = this.cause.path - this.errno = this.cause.errno - this.message = - (errno.errno[this.cause.errno] - ? errno.errno[this.cause.errno].description - : this.cause.message) - + (this.cause.path ? ' [' + this.cause.path + ']' : '') - } - Error.call(this) - if (Error.captureStackTrace) - Error.captureStackTrace(this, arguments.callee) - } - err.prototype = !!proto ? new proto() : new CustomError() - return err -} - -module.exports = function (errno) { - var ce = function (type, proto) { - return createError(errno, type, proto) - } - return { - CustomError : CustomError - , FilesystemError : ce('FilesystemError') - , createError : ce - } -} - -},{"prr":162}],161:[function(require,module,exports){ -var all = module.exports.all = [ - { - errno: -2, - code: 'ENOENT', - description: 'no such file or directory' - }, - { - errno: -1, - code: 'UNKNOWN', - description: 'unknown error' - }, - { - errno: 0, - code: 'OK', - description: 'success' - }, - { - errno: 1, - code: 'EOF', - description: 'end of file' - }, - { - errno: 2, - code: 'EADDRINFO', - description: 'getaddrinfo error' - }, - { - errno: 3, - code: 'EACCES', - description: 'permission denied' - }, - { - errno: 4, - code: 'EAGAIN', - description: 'resource temporarily unavailable' - }, - { - errno: 5, - code: 'EADDRINUSE', - description: 'address already in use' - }, - { - errno: 6, - code: 'EADDRNOTAVAIL', - description: 'address not available' - }, - { - errno: 7, - code: 'EAFNOSUPPORT', - description: 'address family not supported' - }, - { - errno: 8, - code: 'EALREADY', - description: 'connection already in progress' - }, - { - errno: 9, - code: 'EBADF', - description: 'bad file descriptor' - }, - { - errno: 10, - code: 'EBUSY', - description: 'resource busy or locked' - }, - { - errno: 11, - code: 'ECONNABORTED', - description: 'software caused connection abort' - }, - { - errno: 12, - code: 'ECONNREFUSED', - description: 'connection refused' - }, - { - errno: 13, - code: 'ECONNRESET', - description: 'connection reset by peer' - }, - { - errno: 14, - code: 'EDESTADDRREQ', - description: 'destination address required' - }, - { - errno: 15, - code: 'EFAULT', - description: 'bad address in system call argument' - }, - { - errno: 16, - code: 'EHOSTUNREACH', - description: 'host is unreachable' - }, - { - errno: 17, - code: 'EINTR', - description: 'interrupted system call' - }, - { - errno: 18, - code: 'EINVAL', - description: 'invalid argument' - }, - { - errno: 19, - code: 'EISCONN', - description: 'socket is already connected' - }, - { - errno: 20, - code: 'EMFILE', - description: 'too many open files' - }, - { - errno: 21, - code: 'EMSGSIZE', - description: 'message too long' - }, - { - errno: 22, - code: 'ENETDOWN', - description: 'network is down' - }, - { - errno: 23, - code: 'ENETUNREACH', - description: 'network is unreachable' - }, - { - errno: 24, - code: 'ENFILE', - description: 'file table overflow' - }, - { - errno: 25, - code: 'ENOBUFS', - description: 'no buffer space available' - }, - { - errno: 26, - code: 'ENOMEM', - description: 'not enough memory' - }, - { - errno: 27, - code: 'ENOTDIR', - description: 'not a directory' - }, - { - errno: 28, - code: 'EISDIR', - description: 'illegal operation on a directory' - }, - { - errno: 29, - code: 'ENONET', - description: 'machine is not on the network' - }, - { - errno: 31, - code: 'ENOTCONN', - description: 'socket is not connected' - }, - { - errno: 32, - code: 'ENOTSOCK', - description: 'socket operation on non-socket' - }, - { - errno: 33, - code: 'ENOTSUP', - description: 'operation not supported on socket' - }, - { - errno: 34, - code: 'ENOENT', - description: 'no such file or directory' - }, - { - errno: 35, - code: 'ENOSYS', - description: 'function not implemented' - }, - { - errno: 36, - code: 'EPIPE', - description: 'broken pipe' - }, - { - errno: 37, - code: 'EPROTO', - description: 'protocol error' - }, - { - errno: 38, - code: 'EPROTONOSUPPORT', - description: 'protocol not supported' - }, - { - errno: 39, - code: 'EPROTOTYPE', - description: 'protocol wrong type for socket' - }, - { - errno: 40, - code: 'ETIMEDOUT', - description: 'connection timed out' - }, - { - errno: 41, - code: 'ECHARSET', - description: 'invalid Unicode character' - }, - { - errno: 42, - code: 'EAIFAMNOSUPPORT', - description: 'address family for hostname not supported' - }, - { - errno: 44, - code: 'EAISERVICE', - description: 'servname not supported for ai_socktype' - }, - { - errno: 45, - code: 'EAISOCKTYPE', - description: 'ai_socktype not supported' - }, - { - errno: 46, - code: 'ESHUTDOWN', - description: 'cannot send after transport endpoint shutdown' - }, - { - errno: 47, - code: 'EEXIST', - description: 'file already exists' - }, - { - errno: 48, - code: 'ESRCH', - description: 'no such process' - }, - { - errno: 49, - code: 'ENAMETOOLONG', - description: 'name too long' - }, - { - errno: 50, - code: 'EPERM', - description: 'operation not permitted' - }, - { - errno: 51, - code: 'ELOOP', - description: 'too many symbolic links encountered' - }, - { - errno: 52, - code: 'EXDEV', - description: 'cross-device link not permitted' - }, - { - errno: 53, - code: 'ENOTEMPTY', - description: 'directory not empty' - }, - { - errno: 54, - code: 'ENOSPC', - description: 'no space left on device' - }, - { - errno: 55, - code: 'EIO', - description: 'i/o error' - }, - { - errno: 56, - code: 'EROFS', - description: 'read-only file system' - }, - { - errno: 57, - code: 'ENODEV', - description: 'no such device' - }, - { - errno: 58, - code: 'ESPIPE', - description: 'invalid seek' - }, - { - errno: 59, - code: 'ECANCELED', - description: 'operation canceled' - } -] - -module.exports.errno = {} -module.exports.code = {} - -all.forEach(function (error) { - module.exports.errno[error.errno] = error - module.exports.code[error.code] = error -}) - -module.exports.custom = require('./custom')(module.exports) -module.exports.create = module.exports.custom.createError - -},{"./custom":160}],162:[function(require,module,exports){ -/*! - * prr - * (c) 2013 Rod Vagg - * https://github.com/rvagg/prr - * License: MIT - */ - -(function (name, context, definition) { - if (typeof module != 'undefined' && module.exports) - module.exports = definition() - else - context[name] = definition() -})('prr', this, function() { - - var setProperty = typeof Object.defineProperty == 'function' - ? function (obj, key, options) { - Object.defineProperty(obj, key, options) - return obj - } - : function (obj, key, options) { // < es5 - obj[key] = options.value - return obj - } - - , makeOptions = function (value, options) { - var oo = typeof options == 'object' - , os = !oo && typeof options == 'string' - , op = function (p) { - return oo - ? !!options[p] - : os - ? options.indexOf(p[0]) > -1 - : false - } - - return { - enumerable : op('enumerable') - , configurable : op('configurable') - , writable : op('writable') - , value : value - } - } - - , prr = function (obj, key, value, options) { - var k - - options = makeOptions(value, options) - - if (typeof key == 'object') { - for (k in key) { - if (Object.hasOwnProperty.call(key, k)) { - options.value = key[k] - setProperty(obj, k, options) - } - } - return obj - } - - return setProperty(obj, key, options) - } - - return prr -}) -},{}],163:[function(require,module,exports){ -module.exports={ - "genesisGasLimit": { - "v": 5000, - "d": "Gas limit of the Genesis block." - }, - "genesisDifficulty": { - "v": 17179869184, - "d": "Difficulty of the Genesis block." - }, - "genesisNonce": { - "v": "0x0000000000000042", - "d": "the geneis nonce" - }, - "genesisExtraData": { - "v": "0x11bbe8db4e347b4e8c937c1c8370e4b5ed33adb3db69cbdb7a38e1e50b1b82fa", - "d": "extra data " - }, - "genesisHash": { - "v": "0xd4e56740f876aef8c010b86a40d5f56745a118d0906a34e69aec8c0db1cb8fa3", - "d": "genesis hash" - }, - "genesisStateRoot": { - "v": "0xd7f8974fb5ac78d9ac099b9ad5018bedc2ce0a72dad1827a1709da30580f0544", - "d": "the genesis state root" - }, - "minGasLimit": { - "v": 5000, - "d": "Minimum the gas limit may ever be." - }, - "gasLimitBoundDivisor": { - "v": 1024, - "d": "The bound divisor of the gas limit, used in update calculations." - }, - "minimumDifficulty": { - "v": 131072, - "d": "The minimum that the difficulty may ever be." - }, - "difficultyBoundDivisor": { - "v": 2048, - "d": "The bound divisor of the difficulty, used in the update calculations." - }, - "durationLimit": { - "v": 13, - "d": "The decision boundary on the blocktime duration used to determine whether difficulty should go up or not." - }, - "maximumExtraDataSize": { - "v": 32, - "d": "Maximum size extra data may be after Genesis." - }, - "epochDuration": { - "v": 30000, - "d": "Duration between proof-of-work epochs." - }, - "stackLimit": { - "v": 1024, - "d": "Maximum size of VM stack allowed." - }, - "callCreateDepth": { - "v": 1024, - "d": "Maximum depth of call/create stack." - }, - - "tierStepGas": { - "v": [0, 2, 3, 5, 8, 10, 20], - "d": "Once per operation, for a selection of them." - }, - "expGas": { - "v": 10, - "d": "Once per EXP instuction." - }, - "expByteGas": { - "v": 10, - "d": "Times ceil(log256(exponent)) for the EXP instruction." - }, - - "sha3Gas": { - "v": 30, - "d": "Once per SHA3 operation." - }, - "sha3WordGas": { - "v": 6, - "d": "Once per word of the SHA3 operation's data." - }, - "sloadGas": { - "v": 50, - "d": "Once per SLOAD operation." - }, - "sstoreSetGas": { - "v": 20000, - "d": "Once per SSTORE operation if the zeroness changes from zero." - }, - "sstoreResetGas": { - "v": 5000, - "d": "Once per SSTORE operation if the zeroness does not change from zero." - }, - "sstoreRefundGas": { - "v": 15000, - "d": "Once per SSTORE operation if the zeroness changes to zero." - }, - "jumpdestGas": { - "v": 1, - "d": "Refunded gas, once per SSTORE operation if the zeroness changes to zero." - }, - - "logGas": { - "v": 375, - "d": "Per LOG* operation." - }, - "logDataGas": { - "v": 8, - "d": "Per byte in a LOG* operation's data." - }, - "logTopicGas": { - "v": 375, - "d": "Multiplied by the * of the LOG*, per LOG transaction. e.g. LOG0 incurs 0 * c_txLogTopicGas, LOG4 incurs 4 * c_txLogTopicGas." - }, - - "createGas": { - "v": 32000, - "d": "Once per CREATE operation & contract-creation transaction." - }, - - "callGas": { - "v": 40, - "d": "Once per CALL operation & message call transaction." - }, - "callStipend": { - "v": 2300, - "d": "Free gas given at beginning of call." - }, - "callValueTransferGas": { - "v": 9000, - "d": "Paid for CALL when the value transfor is non-zero." - }, - "callNewAccountGas": { - "v": 25000, - "d": "Paid for CALL when the destination address didn't exist prior." - }, - - "suicideRefundGas": { - "v": 24000, - "d": "Refunded following a suicide operation." - }, - - "memoryGas": { - "v": 3, - "d": "Times the address of the (highest referenced byte in memory + 1). NOTE: referencing happens on read, write and in instructions such as RETURN and CALL." - }, - "quadCoeffDiv": { - "v": 512, - "d": "Divisor for the quadratic particle of the memory cost equation." - }, - - "createDataGas": { - "v": 200, - "d": "" - }, - "txGas": { - "v": 21000, - "d": "Per transaction. NOTE: Not payable on data of calls between transactions." - }, - "txCreation": { - "v": 32000, - "d": "the cost of creating a contract via tx" - }, - "txDataZeroGas": { - "v": 4, - "d": "Per byte of data attached to a transaction that equals zero. NOTE: Not payable on data of calls between transactions." - }, - "txDataNonZeroGas": { - "v": 68, - "d": "Per byte of data attached to a transaction that is not equal to zero. NOTE: Not payable on data of calls between transactions." - }, - - "copyGas": { - "v": 3, - "d": "Multiplied by the number of 32-byte words that are copied (round up) for any *COPY operation and added." - }, - - "ecrecoverGas": { - "v": 3000, - "d": "" - }, - "sha256Gas": { - "v": 60, - "d": "" - }, - "sha256WordGas": { - "v": 12, - "d": "" - }, - "ripemd160Gas": { - "v": 600, - "d": "" - }, - "ripemd160WordGas": { - "v": 120, - "d": "" - }, - "identityGas": { - "v": 15, - "d": "" - }, - "identityWordGas": { - "v": 3, - "d": "" - }, - "minerReward": { - "v": "5000000000000000000", - "d": "the amount a miner get rewarded for mining a block" - }, - "ommerReward": { - "v": "625000000000000000", - "d": "The amount of wei a miner of an uncle block gets for being inculded in the blockchain" - }, - "niblingReward": { - "v": "156250000000000000", - "d": "the amount a miner gets for inculding a uncle" - }, - "homeSteadForkNumber": { - "v": 1150000, - "d": "the block that the Homestead fork started at" - }, - "homesteadRepriceForkNumber": { - "v": 2463000, - "d": "the block that the Homestead Reprice (EIP150) fork started at" - }, - "timebombPeriod": { - "v": 100000, - "d": "Exponential difficulty timebomb period" - }, - "freeBlockPeriod": { - "v": 2 - } -} - -},{}],164:[function(require,module,exports){ -(function (Buffer){ -const ethUtil = require('ethereumjs-util') -const rlp = require('rlp') - -var Account = module.exports = function (data) { - // Define Properties - var fields = [{ - name: 'nonce', - default: new Buffer([]) - }, { - name: 'balance', - default: new Buffer([]) - }, { - name: 'stateRoot', - length: 32, - default: ethUtil.SHA3_RLP - }, { - name: 'codeHash', - length: 32, - default: ethUtil.SHA3_NULL - }] - - ethUtil.defineProperties(this, fields, data) -} - -Account.prototype.serialize = function () { - return rlp.encode(this.raw) -} - -Account.prototype.isContract = function () { - return this.codeHash.toString('hex') !== ethUtil.SHA3_NULL_S -} - -Account.prototype.getCode = function (state, cb) { - if (!this.isContract()) { - cb(null, new Buffer([])) - return - } - - state.getRaw(this.codeHash, cb) -} - -Account.prototype.setCode = function (trie, code, cb) { - var self = this - - this.codeHash = ethUtil.sha3(code) - - if (this.codeHash.toString('hex') === ethUtil.SHA3_NULL_S) { - cb(null, new Buffer([])) - return - } - - trie.putRaw(this.codeHash, code, function (err) { - cb(err, self.codeHash) - }) -} - -Account.prototype.getStorage = function (trie, key, cb) { - var t = trie.copy() - t.root = this.stateRoot - t.get(key, cb) -} - -Account.prototype.setStorage = function (trie, key, val, cb) { - var self = this - var t = trie.copy() - t.root = self.stateRoot - t.put(key, val, function (err) { - if (err) return cb() - self.stateRoot = t.root - cb() - }) -} - -Account.prototype.isEmpty = function () { - return this.balance.toString('hex') === '' && - this.nonce.toString('hex') === '' && - this.stateRoot.toString('hex') === ethUtil.SHA3_RLP_S && - this.codeHash.toString('hex') === ethUtil.SHA3_NULL_S -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"ethereumjs-util":165,"rlp":655}],165:[function(require,module,exports){ -(function (Buffer){ -const SHA3 = require('keccakjs') -const secp256k1 = require('secp256k1') -const assert = require('assert') -const rlp = require('rlp') -const BN = require('bn.js') -const createHash = require('create-hash') - -/** - * the max integer that this VM can handle (a ```BN```) - * @var {BN} MAX_INTEGER - */ -exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16) - -/** - * 2^256 (a ```BN```) - * @var {BN} TWO_POW256 - */ -exports.TWO_POW256 = new BN('10000000000000000000000000000000000000000000000000000000000000000', 16) - -/** - * SHA3-256 hash of null (a ```String```) - * @var {String} SHA3_NULL_S - */ -exports.SHA3_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470' - -/** - * SHA3-256 hash of null (a ```Buffer```) - * @var {Buffer} SHA3_NULL - */ -exports.SHA3_NULL = new Buffer(exports.SHA3_NULL_S, 'hex') - -/** - * SHA3-256 of an RLP of an empty array (a ```String```) - * @var {String} SHA3_RLP_ARRAY_S - */ -exports.SHA3_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347' - -/** - * SHA3-256 of an RLP of an empty array (a ```Buffer```) - * @var {Buffer} SHA3_RLP_ARRAY - */ -exports.SHA3_RLP_ARRAY = new Buffer(exports.SHA3_RLP_ARRAY_S, 'hex') - -/** - * SHA3-256 hash of the RLP of null (a ```String```) - * @var {String} SHA3_RLP_S - */ -exports.SHA3_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421' - -/** - * SHA3-256 hash of the RLP of null (a ```Buffer```) - * @var {Buffer} SHA3_RLP - */ -exports.SHA3_RLP = new Buffer(exports.SHA3_RLP_S, 'hex') - -/** - * [`BN`](https://github.com/indutny/bn.js) - * @var {Function} - */ -exports.BN = BN - -/** - * [`rlp`](https://github.com/ethereumjs/rlp) - * @var {Function} - */ -exports.rlp = rlp - -/** - * [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) - * @var {Object} - */ -exports.secp256k1 = secp256k1 - -/** - * Returns a buffer filled with 0s - * @method zeros - * @param {Number} bytes the number of bytes the buffer should be - * @return {Buffer} - */ -exports.zeros = function (bytes) { - var buf = new Buffer(bytes) - buf.fill(0) - return buf -} - -/** - * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @method lsetLength - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @param {Boolean} [right=false] whether to start padding form the left or right - * @return {Buffer|Array} - */ -exports.setLengthLeft = exports.setLength = function (msg, length, right) { - var buf = exports.zeros(length) - msg = exports.toBuffer(msg) - if (right) { - if (msg.length < length) { - msg.copy(buf) - return buf - } - return msg.slice(0, length) - } else { - if (msg.length < length) { - msg.copy(buf, length - msg.length) - return buf - } - return msg.slice(-length) - } -} - -/** - * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @method lsetLength - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @return {Buffer|Array} - */ -exports.setLengthRight = function (msg, length) { - return exports.setLength(msg, length, true) -} - -/** - * Trims leading zeros from a `Buffer` or an `Array` - * @method unpad - * @param {Buffer|Array|String} a - * @return {Buffer|Array|String} - */ -exports.unpad = exports.stripZeros = function (a) { - a = exports.stripHexPrefix(a) - var first = a[0] - while (a.length > 0 && first.toString() === '0') { - a = a.slice(1) - first = a[0] - } - return a -} -/** - * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. - * @method toBuffer - * @param {*} v the value - */ -exports.toBuffer = function (v) { - if (!Buffer.isBuffer(v)) { - if (Array.isArray(v)) { - v = new Buffer(v) - } else if (typeof v === 'string') { - if (exports.isHexPrefixed(v)) { - v = new Buffer(exports.padToEven(exports.stripHexPrefix(v)), 'hex') - } else { - v = new Buffer(v) - } - } else if (typeof v === 'number') { - v = exports.intToBuffer(v) - } else if (v === null || v === undefined) { - v = new Buffer([]) - } else if (v.toArray) { - // converts a BN to a Buffer - v = new Buffer(v.toArray()) - } else { - throw new Error('invalid type') - } - } - return v -} - -/** - * Converts a `Number` into a hex `String` - * @method intToHex - * @param {Number} i - * @return {String} - */ -exports.intToHex = function (i) { - assert(i % 1 === 0, 'number is not a integer') - assert(i >= 0, 'number must be positive') - var hex = i.toString(16) - if (hex.length % 2) { - hex = '0' + hex - } - - return '0x' + hex -} - -/** - * Converts an `Number` to a `Buffer` - * @method intToBuffer - * @param {Number} i - * @return {Buffer} - */ -exports.intToBuffer = function (i) { - var hex = exports.intToHex(i) - return new Buffer(hex.slice(2), 'hex') -} - -/** - * Converts a `Buffer` to a `Number` - * @method bufferToInt - * @param {Buffer} buf - * @return {Number} - */ -exports.bufferToInt = function (buf) { - return parseInt(exports.bufferToHex(buf), 16) -} - -/** - * Converts a `Buffer` into a hex `String` - * @method bufferToHex - * @param {Buffer} buf - * @return {String} - */ -exports.bufferToHex = function (buf) { - buf = exports.toBuffer(buf) - if (buf.length === 0) { - return 0 - } - - return '0x' + buf.toString('hex') -} - -/** - * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. - * @method fromSigned - * @param {Buffer} num - * @return {BN} - */ -exports.fromSigned = function (num) { - return new BN(num).fromTwos(256) -} - -/** - * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. - * @method toUnsigned - * @param {BN} num - * @return {Buffer} - */ -exports.toUnsigned = function (num) { - return new Buffer(num.toTwos(256).toArray()) -} - -/** - * Creates SHA-3 hash of the input - * @method sha3 - * @param {Buffer|Array|String|Number} a the input data - * @param {Number} [bytes=256] the SHA width - * @return {Buffer} - */ -exports.sha3 = function (a, bytes) { - a = exports.toBuffer(a) - if (!bytes) bytes = 256 - - var h = new SHA3(bytes) - if (a) { - h.update(a) - } - return new Buffer(h.digest('hex'), 'hex') -} - -/** - * Creates SHA256 hash of the input - * @method sha256 - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.sha256 = function (a) { - a = exports.toBuffer(a) - return createHash('sha256').update(a).digest() -} - -/** - * Creates RIPEMD160 hash of the input - * @method ripemd160 - * @param {Buffer|Array|String|Number} a the input data - * @param {Boolean} padded whether it should be padded to 256 bits or not - * @return {Buffer} - */ -exports.ripemd160 = function (a, padded) { - a = exports.toBuffer(a) - var hash = createHash('rmd160').update(a).digest() - if (padded === true) { - return exports.setLength(hash, 32) - } else { - return hash - } -} - -/** - * Creates SHA-3 hash of the RLP encoded version of the input - * @method rlphash - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.rlphash = function (a) { - return exports.sha3(rlp.encode(a)) -} - -/** - * Checks if the private key satisfies the rules of the curve secp256k1. - * @method isValidPrivate - * @param {Buffer} privateKey - * @return {Boolean} - */ -exports.isValidPrivate = function (privateKey) { - return secp256k1.privateKeyVerify(privateKey) -} - -/** - * Checks if the public key satisfies the rules of the curve secp256k1 - * and the requirements of Ethereum. - * @method isValidPublic - * @param {Buffer} publicKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Boolean} - */ -exports.isValidPublic = function (publicKey, sanitize) { - if (publicKey.length === 64) { - // Convert to SEC1 for secp256k1 - return secp256k1.publicKeyVerify(Buffer.concat([ new Buffer([4]), publicKey ])) - } - - if (!sanitize) { - return false - } - - return secp256k1.publicKeyVerify(publicKey) -} - -/** - * Returns the ethereum address of a given public key. - * Accepts "Ethereum public keys" and SEC1 encoded keys. - * @method publicToAddress - * @param {Buffer} pubKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Buffer} - */ -exports.pubToAddress = exports.publicToAddress = function (pubKey, sanitize) { - pubKey = exports.toBuffer(pubKey) - if (sanitize && (pubKey.length !== 64)) { - pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1) - } - assert(pubKey.length === 64) - // Only take the lower 160bits of the hash - return exports.sha3(pubKey).slice(-20) -} - -/** - * Returns the ethereum public key of a given private key - * @method privateToPublic - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -var privateToPublic = exports.privateToPublic = function (privateKey) { - privateKey = exports.toBuffer(privateKey) - // skip the type flag and use the X, Y points - return secp256k1.publicKeyCreate(privateKey, false).slice(1) -} - -/** - * Converts a public key to the Ethereum format. - * @method importPublic - * @param {Buffer} publicKey - * @return {Buffer} - */ -exports.importPublic = function (publicKey) { - publicKey = exports.toBuffer(publicKey) - if (publicKey.length !== 64) { - publicKey = secp256k1.publicKeyConvert(publicKey, false).slice(1) - } - return publicKey -} - -/** - * ECDSA sign - * @method ecsign - * @param {Buffer} msgHash - * @param {Buffer} privateKey - * @return {Object} - */ -exports.ecsign = function (msgHash, privateKey) { - var sig = secp256k1.sign(msgHash, privateKey) - - var ret = {} - ret.r = sig.signature.slice(0, 32) - ret.s = sig.signature.slice(32, 64) - ret.v = sig.recovery + 27 - return ret -} - -/** - * ECDSA public key recovery from signature - * @method ecrecover - * @param {Buffer} msgHash - * @param {Buffer} v - * @param {Buffer} r - * @param {Buffer} s - * @return {Buffer} publicKey - */ -exports.ecrecover = function (msgHash, v, r, s) { - var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64) - var recovery = exports.bufferToInt(v) - 27 - if (recovery !== 0 && recovery !== 1) { - throw new Error('Invalid signature v value') - } - var senderPubKey = secp256k1.recover(msgHash, signature, recovery) - return secp256k1.publicKeyConvert(senderPubKey, false).slice(1) -} - -/** - * Convert signature parameters into the format of `eth_sign` RPC method - * @method toRpcSig - * @param {Number} v - * @param {Buffer} r - * @param {Buffer} s - * @return {String} sig - */ -exports.toRpcSig = function (v, r, s) { - // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin - // FIXME: this might change in the future - https://github.com/ethereum/go-ethereum/issues/2053 - return exports.bufferToHex(Buffer.concat([ r, s, exports.toBuffer(v - 27) ])) -} - -/** - * Convert signature format of the `eth_sign` RPC method to signature parameters - * @method fromRpcSig - * @param {String} sig - * @return {Object} - */ -exports.fromRpcSig = function (sig) { - sig = exports.toBuffer(sig) - - var v = sig[64] - // support both versions of `eth_sign` responses - if (v < 27) { - v += 27 - } - - return { - v: v, - r: sig.slice(0, 32), - s: sig.slice(32, 64) - } -} - -/** - * Returns the ethereum address of a given private key - * @method privateToAddress - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -exports.privateToAddress = function (privateKey) { - return exports.publicToAddress(privateToPublic(privateKey)) -} - -/** - * Checks if the address is a valid. Accepts checksummed addresses too - * @method isValidAddress - * @param {String} address - * @return {Boolean} - */ -exports.isValidAddress = function (address) { - return /^0x[0-9a-fA-F]{40}$/i.test(address) -} - -/** - * Returns a checksummed address - * @method toChecksumAddress - * @param {String} address - * @return {String} - */ -exports.toChecksumAddress = function (address) { - address = exports.stripHexPrefix(address).toLowerCase() - var hash = exports.sha3(address).toString('hex') - var ret = '0x' - - for (var i = 0; i < address.length; i++) { - if (parseInt(hash[i], 16) >= 8) { - ret += address[i].toUpperCase() - } else { - ret += address[i] - } - } - - return ret -} - -/** - * Checks if the address is a valid checksummed address - * @method isValidChecksumAddress - * @param {Buffer} address - * @return {Boolean} - */ -exports.isValidChecksumAddress = function (address) { - return exports.isValidAddress(address) && (exports.toChecksumAddress(address) === address) -} - -/** - * Generates an address of a newly created contract - * @method generateAddress - * @param {Buffer} from the address which is creating this new address - * @param {Buffer} nonce the nonce of the from account - * @return {Buffer} - */ -exports.generateAddress = function (from, nonce) { - from = exports.toBuffer(from) - nonce = new BN(nonce) - - if (nonce.isZero()) { - // in RLP we want to encode null in the case of zero nonce - // read the RLP documentation for an answer if you dare - nonce = null - } else { - nonce = new Buffer(nonce.toArray()) - } - - // Only take the lower 160bits of the hash - return exports.rlphash([from, nonce]).slice(-20) -} - -/** - * Returns true if the supplied address belongs to a precompiled account - * @method isPrecompiled - * @param {Buffer|String} address - * @return {Boolean} - */ -exports.isPrecompiled = function (address) { - var a = exports.unpad(address) - return a.length === 1 && a[0] > 0 && a[0] < 5 -} - -/** - * Returns a `Boolean` on whether or not the a `String` starts with "0x" - * @method isHexPrefixed - * @param {String} str - * @return {Boolean} - */ -exports.isHexPrefixed = function (str) { - return str.slice(0, 2) === '0x' -} - -/** - * Removes "0x" from a given `String` - * @method stripHexPrefix - * @param {String} str - * @return {String} - */ -exports.stripHexPrefix = function (str) { - if (typeof str !== 'string') { - return str - } - return exports.isHexPrefixed(str) ? str.slice(2) : str -} - -/** - * Adds "0x" to a given `String` if it does not already start with "0x" - * @method addHexPrefix - * @param {String} str - * @return {String} - */ -exports.addHexPrefix = function (str) { - if (typeof str !== 'string') { - return str - } - - return exports.isHexPrefixed(str) ? str : '0x' + str -} - -/** - * Pads a `String` to have an even length - * @method padToEven - * @param {String} a - * @return {String} - */ -exports.padToEven = function (a) { - if (a.length % 2) a = '0' + a - return a -} - -/** - * Converts a `Buffer` or `Array` to JSON - * @method BAToJSON - * @param {Buffer|Array} ba - * @return {Array|String|null} - */ -exports.baToJSON = function (ba) { - if (Buffer.isBuffer(ba)) { - return '0x' + ba.toString('hex') - } else if (ba instanceof Array) { - var array = [] - for (var i = 0; i < ba.length; i++) { - array.push(exports.baToJSON(ba[i])) - } - return array - } -} - -/** - * Defines properties on a `Object`. It make the assumption that underlying data is binary. - * @method defineProperties - * @param {Object} self the `Object` to define properties on - * @param {Array} fields an array fields to define. Fields can contain: - * * `name` - the name of the properties - * * `length` - the number of bytes the field can have - * * `allowLess` - if the field can be less than the length - * * `allowEmpty` - * @param {*} data data to be validated against the definitions - */ -exports.defineProperties = function (self, fields, data) { - self.raw = [] - self._fields = [] - - // attach the `toJSON` - self.toJSON = function (label) { - if (label) { - var obj = {} - self._fields.forEach(function (field) { - obj[field] = '0x' + self[field].toString('hex') - }) - return obj - } - return exports.baToJSON(this.raw) - } - - self.serialize = function serialize () { - return rlp.encode(self.raw) - } - - fields.forEach(function (field, i) { - self._fields.push(field.name) - function getter () { - return self.raw[i] - } - function setter (v) { - v = exports.toBuffer(v) - - if (v.toString('hex') === '00' && !field.allowZero) { - v = new Buffer([]) - } - - if (field.allowLess && field.length) { - v = exports.stripZeros(v) - assert(field.length >= v.length, 'The field ' + field.name + ' must not have more ' + field.length + ' bytes') - } else if (!(field.allowZero && v.length === 0) && field.length) { - assert(field.length === v.length, 'The field ' + field.name + ' must have byte length of ' + field.length) - } - - self.raw[i] = v - } - - Object.defineProperty(self, field.name, { - enumerable: true, - configurable: true, - get: getter, - set: setter - }) - - if (field.default) { - self[field.name] = field.default - } - - // attach alias - if (field.alias) { - Object.defineProperty(self, field.alias, { - enumerable: false, - configurable: true, - set: setter, - get: getter - }) - } - }) - - // if the constuctor is passed data - if (data) { - if (typeof data === 'string') { - data = new Buffer(exports.stripHexPrefix(data), 'hex') - } - - if (Buffer.isBuffer(data)) { - data = rlp.decode(data) - } - - if (Array.isArray(data)) { - if (data.length > self._fields.length) { - throw (new Error('wrong number of fields in data')) - } - - // make sure all the items are buffers - data.forEach(function (d, i) { - self[self._fields[i]] = exports.toBuffer(d) - }) - } else if (typeof data === 'object') { - for (var prop in data) { - if (self._fields.indexOf(prop) !== -1) { - self[prop] = data[prop] - } - } - } else { - throw new Error('invalid data') - } - } -} - -}).call(this,require("buffer").Buffer) -},{"assert":982,"bn.js":66,"buffer":987,"create-hash":100,"keccakjs":351,"rlp":655,"secp256k1":657}],166:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var utils = require('ethereumjs-util'); -var params = require('ethereum-common/params.json'); -var BN = utils.BN; -/** - * An object that repersents the block header - * @constructor - * @param {Array} data raw data, deserialized - * @prop {Buffer} parentHash the blocks' parent's hash - * @prop {Buffer} uncleHash sha3(rlp_encode(uncle_list)) - * @prop {Buffer} coinbase the miner address - * @prop {Buffer} stateRoot The root of a Merkle Patricia tree - * @prop {Buffer} transactionTrie the root of a Trie containing the transactions - * @prop {Buffer} receiptTrie the root of a Trie containing the transaction Reciept - * @prop {Buffer} bloom - * @prop {Buffer} difficulty - * @prop {Buffer} number the block's height - * @prop {Buffer} gasLimit - * @prop {Buffer} gasUsed - * @prop {Buffer} timestamp - * @prop {Buffer} extraData - * @prop {Array.} raw an array of buffers containing the raw blocks. - */ -var BlockHeader = module.exports = function (data) { - var fields = [{ - name: 'parentHash', - length: 32, - default: utils.zeros(32) - }, { - name: 'uncleHash', - default: utils.SHA3_RLP_ARRAY - }, { - name: 'coinbase', - length: 20, - default: utils.zeros(20) - }, { - name: 'stateRoot', - length: 32, - default: utils.zeros(32) - }, { - name: 'transactionsTrie', - length: 32, - default: utils.SHA3_RLP - }, { - name: 'receiptTrie', - length: 32, - default: utils.SHA3_RLP - }, { - name: 'bloom', - default: utils.zeros(256) - }, { - name: 'difficulty', - default: new Buffer([]) - }, { - name: 'number', - default: utils.intToBuffer(params.homeSteadForkNumber.v) - }, { - name: 'gasLimit', - default: new Buffer('ffffffffffffff', 'hex') - }, { - name: 'gasUsed', - empty: true, - default: new Buffer([]) - }, { - name: 'timestamp', - default: new Buffer([]) - }, { - name: 'extraData', - allowZero: true, - empty: true, - default: new Buffer([]) - }, { - name: 'mixHash', - default: utils.zeros(32) - // length: 32 - }, { - name: 'nonce', - default: new Buffer([]) // sha3(42) - }]; - utils.defineProperties(this, fields, data); -}; - -/** - * Returns the canoncical difficulty of the block - * @method canonicalDifficulty - * @param {Block} parentBlock the parent `Block` of the this header - * @return {BN} - */ -BlockHeader.prototype.canonicalDifficulty = function (parentBlock) { - var blockTs = new BN(this.timestamp); - var parentTs = new BN(parentBlock.header.timestamp); - var parentDif = new BN(parentBlock.header.difficulty); - var minimumDifficulty = new BN(params.minimumDifficulty.v); - var offset = parentDif.div(new BN(params.difficultyBoundDivisor.v)); - var dif; - - if (this.isHomestead()) { - // homestead - // 1 - (block_timestamp - parent_timestamp) // 10 - var a = blockTs.sub(parentTs).idivn(10).ineg().iaddn(1); - var cutoff = new BN(-99); - // MAX(cutoff, a) - if (cutoff.cmp(a) === 1) { - a = cutoff; - } - dif = parentDif.add(offset.mul(a)); - } else { - // prehomestead - if (parentTs.addn(params.durationLimit.v).cmp(blockTs) === 1) { - dif = offset.add(parentDif); - } else { - dif = parentDif.sub(offset); - } - } - - var exp = new BN(this.number).idivn(100000).isubn(2); - if (!exp.isNeg()) { - dif.iadd(new BN(2).pow(exp)); - } - - if (dif.cmp(minimumDifficulty) === -1) { - dif = minimumDifficulty; - } - - return dif; -}; - -/** - * checks that the block's `difficuly` matches the canonical difficulty - * @method validateDifficulty - * @param {Block} parentBlock this block's parent - * @return {Boolean} - */ -BlockHeader.prototype.validateDifficulty = function (parentBlock) { - var dif = this.canonicalDifficulty(parentBlock); - return dif.cmp(new BN(this.difficulty)) === 0; -}; - -/** - * Validates the gasLimit - * @method validateGasLimit - * @param {Block} parentBlock this block's parent - * @returns {Boolean} - */ -BlockHeader.prototype.validateGasLimit = function (parentBlock) { - var pGasLimit = new BN(parentBlock.header.gasLimit); - var gasLimit = new BN(this.gasLimit); - var a = pGasLimit.div(new BN(params.gasLimitBoundDivisor.v)); - var maxGasLimit = pGasLimit.add(a); - var minGasLimit = pGasLimit.sub(a); - - return gasLimit.lt(maxGasLimit) && gasLimit.gt(minGasLimit) && gasLimit.gte(params.minGasLimit.v); -}; - -/** - * Validates the entire block header - * @method validate - * @param {Blockchain} blockChain the blockchain that this block is validating against - * @param {Bignum} [height] if this is an uncle header, this is the height of the block that is including it - * @param {Function} cb the callback function. The callback is given an `error` if the block is invalid - */ -BlockHeader.prototype.validate = function (blockchain, height, cb) { - var self = this; - if (arguments.length === 2) { - cb = height; - height = false; - } - - if (this.isGenesis()) { - return cb(); - } - - // find the blocks parent - blockchain.getBlock(self.parentHash, function (err, parentBlock) { - if (err) { - return cb('could not find parent block'); - } - - self.parentBlock = parentBlock; - - var number = new BN(self.number); - if (number.cmp(new BN(parentBlock.header.number).iaddn(1)) !== 0) { - return cb('invalid number'); - } - - if (height) { - var dif = height.sub(new BN(parentBlock.header.number)); - if (!(dif.cmpn(8) === -1 && dif.cmpn(1) === 1)) { - return cb('uncle block has a parent that is too old or to young'); - } - } - - if (!self.validateDifficulty(parentBlock)) { - return cb('invalid Difficulty'); - } - - if (!self.validateGasLimit(parentBlock)) { - return cb('invalid gas limit'); - } - - if (utils.bufferToInt(parentBlock.header.number) + 1 !== utils.bufferToInt(self.number)) { - return cb('invalid heigth'); - } - - if (utils.bufferToInt(self.timestamp) <= utils.bufferToInt(parentBlock.header.timestamp)) { - return cb('invalid timestamp'); - } - - if (self.extraData.length > params.maximumExtraDataSize.v) { - return cb('invalid amount of extra data'); - } - - cb(); - }); -}; - -/** - * Returns the sha3 hash of the blockheader - * @method hash - * @return {Buffer} - */ -BlockHeader.prototype.hash = function () { - return utils.rlphash(this.raw); -}; - -/** - * checks if the blockheader is a genesis header - * @method isGenesis - * @return {Boolean} - */ -BlockHeader.prototype.isGenesis = function () { - return this.number.toString('hex') === ''; -}; - -/** - * Determines if a given block part of homestead or not - * @method isHomestead - * @return Boolean - */ -BlockHeader.prototype.isHomestead = function () { - return utils.bufferToInt(this.number) >= params.homeSteadForkNumber.v; -}; - -/** - * Determines if a given block part of Homestead Reprice (EIP150) or not - * @method isHomesteadReprice - * @return Boolean - */ -BlockHeader.prototype.isHomesteadReprice = function () { - return utils.bufferToInt(this.number) >= params.homesteadRepriceForkNumber.v; -}; - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"ethereum-common/params.json":163,"ethereumjs-util":168}],167:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); - -function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } - -var ethUtil = require('ethereumjs-util'); -var fees = require('ethereum-common/params.json'); -var BN = ethUtil.BN; - -// secp256k1n/2 -var N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); - -/** - * Creates a new transaction object. - * - * @example - * var rawTx = { - * nonce: '00', - * gasPrice: '09184e72a000', - * gasLimit: '2710', - * to: '0000000000000000000000000000000000000000', - * value: '00', - * data: '7f7465737432000000000000000000000000000000000000000000000000000000600057', - * v: '1c', - * r: '5e1d3a76fbf824220eafc8c79ad578ad2b67d01b0c2425eb1f1347e8f50882ab', - * s '5bd428537f05f9830e93792f90ea6a3e2d1ee84952dd96edbae9f658f831ab13' - * }; - * var tx = new Transaction(rawTx); - * - * @class - * @param {Buffer | Array | Object} data a transaction can be initiailized with either a buffer containing the RLP serialized transaction or an array of buffers relating to each of the tx Properties, listed in order below in the exmple. - * - * Or lastly an Object containing the Properties of the transaction like in the Usage example. - * - * For Object and Arrays each of the elements can either be a Buffer, a hex-prefixed (0x) String , Number, or an object with a toBuffer method such as Bignum - * - * @property {Buffer} raw The raw rlp encoded transaction - * @param {Buffer} data.nonce nonce number - * @param {Buffer} data.gasLimit transaction gas limit - * @param {Buffer} data.gasPrice transaction gas price - * @param {Buffer} data.to to the to address - * @param {Buffer} data.value the amount of ether sent - * @param {Buffer} data.data this will contain the data of the message or the init of a contract - * @param {Buffer} data.v EC signature parameter - * @param {Buffer} data.r EC signature parameter - * @param {Buffer} data.s EC recovery ID - * @param {Number} data.chainId EIP 155 chainId - mainnet: 1, ropsten: 3 - * */ - -var Transaction = function () { - function Transaction(data) { - _classCallCheck(this, Transaction); - - data = data || {}; - // Define Properties - var fields = [{ - name: 'nonce', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'gasPrice', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'gasLimit', - alias: 'gas', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'to', - allowZero: true, - length: 20, - default: new Buffer([]) - }, { - name: 'value', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 'data', - alias: 'input', - allowZero: true, - default: new Buffer([]) - }, { - name: 'v', - default: new Buffer([0x1c]) - }, { - name: 'r', - length: 32, - allowLess: true, - default: new Buffer([]) - }, { - name: 's', - length: 32, - allowLess: true, - default: new Buffer([]) - }]; - - /** - * Returns the rlp encoding of the transaction - * @method serialize - * @return {Buffer} - * @memberof Transaction - * @name serialize - */ - // attached serialize - ethUtil.defineProperties(this, fields, data); - - /** - * @property {Buffer} from (read only) sender address of this transaction, mathematically derived from other parameters. - * @name from - * @memberof Transaction - */ - Object.defineProperty(this, 'from', { - enumerable: true, - configurable: true, - get: this.getSenderAddress.bind(this) - }); - - // calculate chainId from signature - var sigV = ethUtil.bufferToInt(this.v); - var chainId = Math.floor((sigV - 35) / 2); - if (chainId < 0) chainId = 0; - - // set chainId - this._chainId = chainId || data.chainId || 0; - this._homestead = true; - } - - /** - * If the tx's `to` is to the creation address - * @return {Boolean} - */ - - - _createClass(Transaction, [{ - key: 'toCreationAddress', - value: function toCreationAddress() { - return this.to.toString('hex') === ''; - } - - /** - * Computes a sha3-256 hash of the serialized tx - * @param {Boolean} [includeSignature=true] whether or not to inculde the signature - * @return {Buffer} - */ - - }, { - key: 'hash', - value: function hash(includeSignature) { - if (includeSignature === undefined) includeSignature = true; - - // EIP155 spec: - // when computing the hash of a transaction for purposes of signing or recovering, - // instead of hashing only the first six elements (ie. nonce, gasprice, startgas, to, value, data), - // hash nine elements, with v replaced by CHAIN_ID, r = 0 and s = 0 - - var items = void 0; - if (includeSignature) { - items = this.raw; - } else { - if (this._chainId > 0) { - var raw = this.raw.slice(); - this.v = this._chainId; - this.r = 0; - this.s = 0; - items = this.raw; - this.raw = raw; - } else { - items = this.raw.slice(0, 6); - } - } - - // create hash - return ethUtil.rlphash(items); - } - - /** - * returns the public key of the sender - * @return {Buffer} - */ - - }, { - key: 'getChainId', - value: function getChainId() { - return this._chainId; - } - - /** - * returns the sender's address - * @return {Buffer} - */ - - }, { - key: 'getSenderAddress', - value: function getSenderAddress() { - if (this._from) { - return this._from; - } - var pubkey = this.getSenderPublicKey(); - this._from = ethUtil.publicToAddress(pubkey); - return this._from; - } - - /** - * returns the public key of the sender - * @return {Buffer} - */ - - }, { - key: 'getSenderPublicKey', - value: function getSenderPublicKey() { - if (!this._senderPubKey || !this._senderPubKey.length) { - if (!this.verifySignature()) throw new Error('Invalid Signature'); - } - return this._senderPubKey; - } - - /** - * Determines if the signature is valid - * @return {Boolean} - */ - - }, { - key: 'verifySignature', - value: function verifySignature() { - var msgHash = this.hash(false); - // All transaction signatures whose s-value is greater than secp256k1n/2 are considered invalid. - if (this._homestead && new BN(this.s).cmp(N_DIV_2) === 1) { - return false; - } - - try { - var v = ethUtil.bufferToInt(this.v); - if (this._chainId > 0) { - v -= this._chainId * 2 + 8; - } - this._senderPubKey = ethUtil.ecrecover(msgHash, v, this.r, this.s); - } catch (e) { - return false; - } - - return !!this._senderPubKey; - } - - /** - * sign a transaction with a given a private key - * @param {Buffer} privateKey - */ - - }, { - key: 'sign', - value: function sign(privateKey) { - var msgHash = this.hash(false); - var sig = ethUtil.ecsign(msgHash, privateKey); - if (this._chainId > 0) { - sig.v += this._chainId * 2 + 8; - } - Object.assign(this, sig); - } - - /** - * The amount of gas paid for the data in this tx - * @return {BN} - */ - - }, { - key: 'getDataFee', - value: function getDataFee() { - var data = this.raw[5]; - var cost = new BN(0); - for (var i = 0; i < data.length; i++) { - data[i] === 0 ? cost.iaddn(fees.txDataZeroGas.v) : cost.iaddn(fees.txDataNonZeroGas.v); - } - return cost; - } - - /** - * the minimum amount of gas the tx must have (DataFee + TxFee + Creation Fee) - * @return {BN} - */ - - }, { - key: 'getBaseFee', - value: function getBaseFee() { - var fee = this.getDataFee().iaddn(fees.txGas.v); - if (this._homestead && this.toCreationAddress()) { - fee.iaddn(fees.txCreation.v); - } - return fee; - } - - /** - * the up front amount that an account must have for this transaction to be valid - * @return {BN} - */ - - }, { - key: 'getUpfrontCost', - value: function getUpfrontCost() { - return new BN(this.gasLimit).imul(new BN(this.gasPrice)).iadd(new BN(this.value)); - } - - /** - * validates the signature and checks to see if it has enough gas - * @param {Boolean} [stringError=false] whether to return a string with a dscription of why the validation failed or return a Bloolean - * @return {Boolean|String} - */ - - }, { - key: 'validate', - value: function validate(stringError) { - var errors = []; - if (!this.verifySignature()) { - errors.push('Invalid Signature'); - } - - if (this.getBaseFee().cmp(new BN(this.gasLimit)) > 0) { - errors.push(['gas limit is too low. Need at least ' + this.getBaseFee()]); - } - - if (stringError === undefined || stringError === false) { - return errors.length === 0; - } else { - return errors.join(' '); - } - } - }]); - - return Transaction; -}(); - -module.exports = Transaction; - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"ethereum-common/params.json":163,"ethereumjs-util":168}],168:[function(require,module,exports){ -(function (Buffer){ -'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 && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - -var createKeccakHash = require('keccak'); -var secp256k1 = require('secp256k1'); -var assert = require('assert'); -var rlp = require('rlp'); -var BN = require('bn.js'); -var createHash = require('create-hash'); -Object.assign(exports, require('ethjs-util')); - -/** - * the max integer that this VM can handle (a ```BN```) - * @var {BN} MAX_INTEGER - */ -exports.MAX_INTEGER = new BN('ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff', 16); - -/** - * 2^256 (a ```BN```) - * @var {BN} TWO_POW256 - */ -exports.TWO_POW256 = new BN('10000000000000000000000000000000000000000000000000000000000000000', 16); - -/** - * SHA3-256 hash of null (a ```String```) - * @var {String} SHA3_NULL_S - */ -exports.SHA3_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470'; - -/** - * SHA3-256 hash of null (a ```Buffer```) - * @var {Buffer} SHA3_NULL - */ -exports.SHA3_NULL = Buffer.from(exports.SHA3_NULL_S, 'hex'); - -/** - * SHA3-256 of an RLP of an empty array (a ```String```) - * @var {String} SHA3_RLP_ARRAY_S - */ -exports.SHA3_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347'; - -/** - * SHA3-256 of an RLP of an empty array (a ```Buffer```) - * @var {Buffer} SHA3_RLP_ARRAY - */ -exports.SHA3_RLP_ARRAY = Buffer.from(exports.SHA3_RLP_ARRAY_S, 'hex'); - -/** - * SHA3-256 hash of the RLP of null (a ```String```) - * @var {String} SHA3_RLP_S - */ -exports.SHA3_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421'; - -/** - * SHA3-256 hash of the RLP of null (a ```Buffer```) - * @var {Buffer} SHA3_RLP - */ -exports.SHA3_RLP = Buffer.from(exports.SHA3_RLP_S, 'hex'); - -/** - * [`BN`](https://github.com/indutny/bn.js) - * @var {Function} - */ -exports.BN = BN; - -/** - * [`rlp`](https://github.com/ethereumjs/rlp) - * @var {Function} - */ -exports.rlp = rlp; - -/** - * [`secp256k1`](https://github.com/cryptocoinjs/secp256k1-node/) - * @var {Object} - */ -exports.secp256k1 = secp256k1; - -/** - * Returns a buffer filled with 0s - * @method zeros - * @param {Number} bytes the number of bytes the buffer should be - * @return {Buffer} - */ -exports.zeros = function (bytes) { - return Buffer.allocUnsafe(bytes).fill(0); -}; - -/** - * Left Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @method lsetLength - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @param {Boolean} [right=false] whether to start padding form the left or right - * @return {Buffer|Array} - */ -exports.setLengthLeft = exports.setLength = function (msg, length, right) { - var buf = exports.zeros(length); - msg = exports.toBuffer(msg); - if (right) { - if (msg.length < length) { - msg.copy(buf); - return buf; - } - return msg.slice(0, length); - } else { - if (msg.length < length) { - msg.copy(buf, length - msg.length); - return buf; - } - return msg.slice(-length); - } -}; - -/** - * Right Pads an `Array` or `Buffer` with leading zeros till it has `length` bytes. - * Or it truncates the beginning if it exceeds. - * @param {Buffer|Array} msg the value to pad - * @param {Number} length the number of bytes the output should be - * @return {Buffer|Array} - */ -exports.setLengthRight = function (msg, length) { - return exports.setLength(msg, length, true); -}; - -/** - * Trims leading zeros from a `Buffer` or an `Array` - * @param {Buffer|Array|String} a - * @return {Buffer|Array|String} - */ -exports.unpad = exports.stripZeros = function (a) { - a = exports.stripHexPrefix(a); - var first = a[0]; - while (a.length > 0 && first.toString() === '0') { - a = a.slice(1); - first = a[0]; - } - return a; -}; -/** - * Attempts to turn a value into a `Buffer`. As input it supports `Buffer`, `String`, `Number`, null/undefined, `BN` and other objects with a `toArray()` method. - * @param {*} v the value - */ -exports.toBuffer = function (v) { - if (!Buffer.isBuffer(v)) { - if (Array.isArray(v)) { - v = Buffer.from(v); - } else if (typeof v === 'string') { - if (exports.isHexString(v)) { - v = Buffer.from(exports.padToEven(exports.stripHexPrefix(v)), 'hex'); - } else { - v = Buffer.from(v); - } - } else if (typeof v === 'number') { - v = exports.intToBuffer(v); - } else if (v === null || v === undefined) { - v = Buffer.allocUnsafe(0); - } else if (v.toArray) { - // converts a BN to a Buffer - v = Buffer.from(v.toArray()); - } else { - throw new Error('invalid type'); - } - } - return v; -}; - -/** - * Converts a `Buffer` to a `Number` - * @param {Buffer} buf - * @return {Number} - * @throws If the input number exceeds 53 bits. - */ -exports.bufferToInt = function (buf) { - return new BN(exports.toBuffer(buf)).toNumber(); -}; - -/** - * Converts a `Buffer` into a hex `String` - * @param {Buffer} buf - * @return {String} - */ -exports.bufferToHex = function (buf) { - buf = exports.toBuffer(buf); - return '0x' + buf.toString('hex'); -}; - -/** - * Interprets a `Buffer` as a signed integer and returns a `BN`. Assumes 256-bit numbers. - * @param {Buffer} num - * @return {BN} - */ -exports.fromSigned = function (num) { - return new BN(num).fromTwos(256); -}; - -/** - * Converts a `BN` to an unsigned integer and returns it as a `Buffer`. Assumes 256-bit numbers. - * @param {BN} num - * @return {Buffer} - */ -exports.toUnsigned = function (num) { - return Buffer.from(num.toTwos(256).toArray()); -}; - -/** - * Creates SHA-3 hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @param {Number} [bits=256] the SHA width - * @return {Buffer} - */ -exports.sha3 = function (a, bits) { - a = exports.toBuffer(a); - if (!bits) bits = 256; - - return createKeccakHash('keccak' + bits).update(a).digest(); -}; - -/** - * Creates SHA256 hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.sha256 = function (a) { - a = exports.toBuffer(a); - return createHash('sha256').update(a).digest(); -}; - -/** - * Creates RIPEMD160 hash of the input - * @param {Buffer|Array|String|Number} a the input data - * @param {Boolean} padded whether it should be padded to 256 bits or not - * @return {Buffer} - */ -exports.ripemd160 = function (a, padded) { - a = exports.toBuffer(a); - var hash = createHash('rmd160').update(a).digest(); - if (padded === true) { - return exports.setLength(hash, 32); - } else { - return hash; - } -}; - -/** - * Creates SHA-3 hash of the RLP encoded version of the input - * @param {Buffer|Array|String|Number} a the input data - * @return {Buffer} - */ -exports.rlphash = function (a) { - return exports.sha3(rlp.encode(a)); -}; - -/** - * Checks if the private key satisfies the rules of the curve secp256k1. - * @param {Buffer} privateKey - * @return {Boolean} - */ -exports.isValidPrivate = function (privateKey) { - return secp256k1.privateKeyVerify(privateKey); -}; - -/** - * Checks if the public key satisfies the rules of the curve secp256k1 - * and the requirements of Ethereum. - * @param {Buffer} publicKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Boolean} - */ -exports.isValidPublic = function (publicKey, sanitize) { - if (publicKey.length === 64) { - // Convert to SEC1 for secp256k1 - return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey])); - } - - if (!sanitize) { - return false; - } - - return secp256k1.publicKeyVerify(publicKey); -}; - -/** - * Returns the ethereum address of a given public key. - * Accepts "Ethereum public keys" and SEC1 encoded keys. - * @param {Buffer} pubKey The two points of an uncompressed key, unless sanitize is enabled - * @param {Boolean} [sanitize=false] Accept public keys in other formats - * @return {Buffer} - */ -exports.pubToAddress = exports.publicToAddress = function (pubKey, sanitize) { - pubKey = exports.toBuffer(pubKey); - if (sanitize && pubKey.length !== 64) { - pubKey = secp256k1.publicKeyConvert(pubKey, false).slice(1); - } - assert(pubKey.length === 64); - // Only take the lower 160bits of the hash - return exports.sha3(pubKey).slice(-20); -}; - -/** - * Returns the ethereum public key of a given private key - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -var privateToPublic = exports.privateToPublic = function (privateKey) { - privateKey = exports.toBuffer(privateKey); - // skip the type flag and use the X, Y points - return secp256k1.publicKeyCreate(privateKey, false).slice(1); -}; - -/** - * Converts a public key to the Ethereum format. - * @param {Buffer} publicKey - * @return {Buffer} - */ -exports.importPublic = function (publicKey) { - publicKey = exports.toBuffer(publicKey); - if (publicKey.length !== 64) { - publicKey = secp256k1.publicKeyConvert(publicKey, false).slice(1); - } - return publicKey; -}; - -/** - * ECDSA sign - * @param {Buffer} msgHash - * @param {Buffer} privateKey - * @return {Object} - */ -exports.ecsign = function (msgHash, privateKey) { - var sig = secp256k1.sign(msgHash, privateKey); - - var ret = {}; - ret.r = sig.signature.slice(0, 32); - ret.s = sig.signature.slice(32, 64); - ret.v = sig.recovery + 27; - return ret; -}; - -/** - * Returns the keccak-256 hash of `message`, prefixed with the header used by the `eth_sign` RPC call. - * The output of this function can be fed into `ecsign` to produce the same signature as the `eth_sign` - * call for a given `message`, or fed to `ecrecover` along with a signature to recover the public key - * used to produce the signature. - * @param message - * @returns {Buffer} hash - */ -exports.hashPersonalMessage = function (message) { - var prefix = exports.toBuffer('\x19Ethereum Signed Message:\n' + message.length.toString()); - return exports.sha3(Buffer.concat([prefix, message])); -}; - -/** - * ECDSA public key recovery from signature - * @param {Buffer} msgHash - * @param {Number} v - * @param {Buffer} r - * @param {Buffer} s - * @return {Buffer} publicKey - */ -exports.ecrecover = function (msgHash, v, r, s) { - var signature = Buffer.concat([exports.setLength(r, 32), exports.setLength(s, 32)], 64); - var recovery = v - 27; - if (recovery !== 0 && recovery !== 1) { - throw new Error('Invalid signature v value'); - } - var senderPubKey = secp256k1.recover(msgHash, signature, recovery); - return secp256k1.publicKeyConvert(senderPubKey, false).slice(1); -}; - -/** - * Convert signature parameters into the format of `eth_sign` RPC method - * @param {Number} v - * @param {Buffer} r - * @param {Buffer} s - * @return {String} sig - */ -exports.toRpcSig = function (v, r, s) { - // NOTE: with potential introduction of chainId this might need to be updated - if (v !== 27 && v !== 28) { - throw new Error('Invalid recovery id'); - } - - // geth (and the RPC eth_sign method) uses the 65 byte format used by Bitcoin - // FIXME: this might change in the future - https://github.com/ethereum/go-ethereum/issues/2053 - return exports.bufferToHex(Buffer.concat([exports.setLengthLeft(r, 32), exports.setLengthLeft(s, 32), exports.toBuffer(v - 27)])); -}; - -/** - * Convert signature format of the `eth_sign` RPC method to signature parameters - * NOTE: all because of a bug in geth: https://github.com/ethereum/go-ethereum/issues/2053 - * @param {String} sig - * @return {Object} - */ -exports.fromRpcSig = function (sig) { - sig = exports.toBuffer(sig); - - // NOTE: with potential introduction of chainId this might need to be updated - if (sig.length !== 65) { - throw new Error('Invalid signature length'); - } - - var v = sig[64]; - // support both versions of `eth_sign` responses - if (v < 27) { - v += 27; - } - - return { - v: v, - r: sig.slice(0, 32), - s: sig.slice(32, 64) - }; -}; - -/** - * Returns the ethereum address of a given private key - * @param {Buffer} privateKey A private key must be 256 bits wide - * @return {Buffer} - */ -exports.privateToAddress = function (privateKey) { - return exports.publicToAddress(privateToPublic(privateKey)); -}; - -/** - * Checks if the address is a valid. Accepts checksummed addresses too - * @param {String} address - * @return {Boolean} - */ -exports.isValidAddress = function (address) { - return (/^0x[0-9a-fA-F]{40}$/i.test(address) - ); -}; - -/** - * Returns a checksummed address - * @param {String} address - * @return {String} - */ -exports.toChecksumAddress = function (address) { - address = exports.stripHexPrefix(address).toLowerCase(); - var hash = exports.sha3(address).toString('hex'); - var ret = '0x'; - - for (var i = 0; i < address.length; i++) { - if (parseInt(hash[i], 16) >= 8) { - ret += address[i].toUpperCase(); - } else { - ret += address[i]; - } - } - - return ret; -}; - -/** - * Checks if the address is a valid checksummed address - * @param {Buffer} address - * @return {Boolean} - */ -exports.isValidChecksumAddress = function (address) { - return exports.isValidAddress(address) && exports.toChecksumAddress(address) === address; -}; - -/** - * Generates an address of a newly created contract - * @param {Buffer} from the address which is creating this new address - * @param {Buffer} nonce the nonce of the from account - * @return {Buffer} - */ -exports.generateAddress = function (from, nonce) { - from = exports.toBuffer(from); - nonce = new BN(nonce); - - if (nonce.isZero()) { - // in RLP we want to encode null in the case of zero nonce - // read the RLP documentation for an answer if you dare - nonce = null; - } else { - nonce = Buffer.from(nonce.toArray()); - } - - // Only take the lower 160bits of the hash - return exports.rlphash([from, nonce]).slice(-20); -}; - -/** - * Returns true if the supplied address belongs to a precompiled account - * @param {Buffer|String} address - * @return {Boolean} - */ -exports.isPrecompiled = function (address) { - var a = exports.unpad(address); - return a.length === 1 && a[0] > 0 && a[0] < 5; -}; - -/** - * Adds "0x" to a given `String` if it does not already start with "0x" - * @param {String} str - * @return {String} - */ -exports.addHexPrefix = function (str) { - if (typeof str !== 'string') { - return str; - } - - return exports.isHexPrefixed(str) ? str : '0x' + str; -}; - -/** - * Validate ECDSA signature - * @method isValidSignature - * @param {Buffer} v - * @param {Buffer} r - * @param {Buffer} s - * @param {Boolean} [homestead=true] - * @return {Boolean} - */ - -exports.isValidSignature = function (v, r, s, homestead) { - var SECP256K1_N_DIV_2 = new BN('7fffffffffffffffffffffffffffffff5d576e7357a4501ddfe92f46681b20a0', 16); - var SECP256K1_N = new BN('fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141', 16); - - if (r.length !== 32 || s.length !== 32) { - return false; - } - - if (v !== 27 && v !== 28) { - return false; - } - - r = new BN(r); - s = new BN(s); - - if (r.isZero() || r.gt(SECP256K1_N) || s.isZero() || s.gt(SECP256K1_N)) { - return false; - } - - if (homestead === false && new BN(s).cmp(SECP256K1_N_DIV_2) === 1) { - return false; - } - - return true; -}; - -/** - * Converts a `Buffer` or `Array` to JSON - * @param {Buffer|Array} ba - * @return {Array|String|null} - */ -exports.baToJSON = function (ba) { - if (Buffer.isBuffer(ba)) { - return '0x' + ba.toString('hex'); - } else if (ba instanceof Array) { - var array = []; - for (var i = 0; i < ba.length; i++) { - array.push(exports.baToJSON(ba[i])); - } - return array; - } -}; - -/** - * Defines properties on a `Object`. It make the assumption that underlying data is binary. - * @param {Object} self the `Object` to define properties on - * @param {Array} fields an array fields to define. Fields can contain: - * * `name` - the name of the properties - * * `length` - the number of bytes the field can have - * * `allowLess` - if the field can be less than the length - * * `allowEmpty` - * @param {*} data data to be validated against the definitions - */ -exports.defineProperties = function (self, fields, data) { - self.raw = []; - self._fields = []; - - // attach the `toJSON` - self.toJSON = function (label) { - if (label) { - var obj = {}; - self._fields.forEach(function (field) { - obj[field] = '0x' + self[field].toString('hex'); - }); - return obj; - } - return exports.baToJSON(this.raw); - }; - - self.serialize = function serialize() { - return rlp.encode(self.raw); - }; - - fields.forEach(function (field, i) { - self._fields.push(field.name); - function getter() { - return self.raw[i]; - } - function setter(v) { - v = exports.toBuffer(v); - - if (v.toString('hex') === '00' && !field.allowZero) { - v = Buffer.allocUnsafe(0); - } - - if (field.allowLess && field.length) { - v = exports.stripZeros(v); - assert(field.length >= v.length, 'The field ' + field.name + ' must not have more ' + field.length + ' bytes'); - } else if (!(field.allowZero && v.length === 0) && field.length) { - assert(field.length === v.length, 'The field ' + field.name + ' must have byte length of ' + field.length); - } - - self.raw[i] = v; - } - - Object.defineProperty(self, field.name, { - enumerable: true, - configurable: true, - get: getter, - set: setter - }); - - if (field.default) { - self[field.name] = field.default; - } - - // attach alias - if (field.alias) { - Object.defineProperty(self, field.alias, { - enumerable: false, - configurable: true, - set: setter, - get: getter - }); - } - }); - - // if the constuctor is passed data - if (data) { - if (typeof data === 'string') { - data = Buffer.from(exports.stripHexPrefix(data), 'hex'); - } - - if (Buffer.isBuffer(data)) { - data = rlp.decode(data); - } - - if (Array.isArray(data)) { - if (data.length > self._fields.length) { - throw new Error('wrong number of fields in data'); - } - - // make sure all the items are buffers - data.forEach(function (d, i) { - self[self._fields[i]] = exports.toBuffer(d); - }); - } else if ((typeof data === 'undefined' ? 'undefined' : _typeof(data)) === 'object') { - var keys = Object.keys(data); - fields.forEach(function (field) { - if (keys.indexOf(field.name) !== -1) self[field.name] = data[field.name]; - if (keys.indexOf(field.alias) !== -1) self[field.alias] = data[field.alias]; - }); - } else { - throw new Error('invalid data'); - } - } -}; - -}).call(this,require("buffer").Buffer) -},{"assert":982,"bn.js":66,"buffer":987,"create-hash":100,"ethjs-util":169,"keccak":345,"rlp":655,"secp256k1":657}],169:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var isHexPrefixed = require('is-hex-prefixed'); -var stripHexPrefix = require('strip-hex-prefix'); - -/** - * Pads a `String` to have an even length - * @param {String} value - * @return {String} output - */ -function padToEven(value) { - var a = value; // eslint-disable-line - - if (typeof a !== 'string') { - throw new Error('[ethjs-util] while padding to even, value must be string, is currently ' + typeof a + ', while padToEven.'); - } - - if (a.length % 2) { - a = '0' + a; - } - - return a; -} - -/** - * Converts a `Number` into a hex `String` - * @param {Number} i - * @return {String} - */ -function intToHex(i) { - var hex = i.toString(16); // eslint-disable-line - - return '0x' + padToEven(hex); -} - -/** - * Converts an `Number` to a `Buffer` - * @param {Number} i - * @return {Buffer} - */ -function intToBuffer(i) { - var hex = intToHex(i); - - return new Buffer(hex.slice(2), 'hex'); -} - -/** - * Get the binary size of a string - * @param {String} str - * @return {Number} - */ -function getBinarySize(str) { - if (typeof str !== 'string') { - throw new Error('[ethjs-util] while getting binary size, method getBinarySize requires input \'str\' to be type String, got \'' + typeof str + '\'.'); - } - - return Buffer.byteLength(str, 'utf8'); -} - -/** - * Returns TRUE if the first specified array contains all elements - * from the second one. FALSE otherwise. - * - * @param {array} superset - * @param {array} subset - * - * @returns {boolean} - */ -function arrayContainsArray(superset, subset, some) { - if (Array.isArray(superset) !== true) { - throw new Error('[ethjs-util] method arrayContainsArray requires input \'superset\' to be an array got type \'' + typeof superset + '\''); - } - if (Array.isArray(subset) !== true) { - throw new Error('[ethjs-util] method arrayContainsArray requires input \'subset\' to be an array got type \'' + typeof subset + '\''); - } - - return subset[Boolean(some) && 'some' || 'every'](function (value) { - return superset.indexOf(value) >= 0; - }); -} - -/** - * Should be called to get utf8 from it's hex representation - * - * @method toUtf8 - * @param {String} string in hex - * @returns {String} ascii string representation of hex value - */ -function toUtf8(hex) { - var bufferValue = new Buffer(padToEven(stripHexPrefix(hex).replace(/^0+|0+$/g, '')), 'hex'); - - return bufferValue.toString('utf8'); -} - -/** - * Should be called to get ascii from it's hex representation - * - * @method toAscii - * @param {String} string in hex - * @returns {String} ascii string representation of hex value - */ -function toAscii(hex) { - var str = ''; // eslint-disable-line - var i = 0, - l = hex.length; // eslint-disable-line - - if (hex.substring(0, 2) === '0x') { - i = 2; - } - - for (; i < l; i += 2) { - var code = parseInt(hex.substr(i, 2), 16); - str += String.fromCharCode(code); - } - - return str; -} - -/** - * Should be called to get hex representation (prefixed by 0x) of utf8 string - * - * @method fromUtf8 - * @param {String} string - * @param {Number} optional padding - * @returns {String} hex representation of input string - */ -function fromUtf8(stringValue) { - var str = new Buffer(stringValue, 'utf8'); - - return '0x' + padToEven(str.toString('hex')).replace(/^0+|0+$/g, ''); -} - -/** - * Should be called to get hex representation (prefixed by 0x) of ascii string - * - * @method fromAscii - * @param {String} string - * @param {Number} optional padding - * @returns {String} hex representation of input string - */ -function fromAscii(stringValue) { - var hex = ''; // eslint-disable-line - for (var i = 0; i < stringValue.length; i++) { - // eslint-disable-line - var code = stringValue.charCodeAt(i); - var n = code.toString(16); - hex += n.length < 2 ? '0' + n : n; - } - - return '0x' + hex; -} - -/** - * getKeys([{a: 1, b: 2}, {a: 3, b: 4}], 'a') => [1, 3] - * - * @method getKeys get specific key from inner object array of objects - * @param {String} params - * @param {String} key - * @param {Boolean} allowEmpty - * @returns {Array} output just a simple array of output keys - */ -function getKeys(params, key, allowEmpty) { - if (!Array.isArray(params)) { - throw new Error('[ethjs-util] method getKeys expecting type Array as \'params\' input, got \'' + typeof params + '\''); - } - if (typeof key !== 'string') { - throw new Error('[ethjs-util] method getKeys expecting type String for input \'key\' got \'' + typeof key + '\'.'); - } - - var result = []; // eslint-disable-line - - for (var i = 0; i < params.length; i++) { - // eslint-disable-line - var value = params[i][key]; // eslint-disable-line - if (allowEmpty && !value) { - value = ''; - } else if (typeof value !== 'string') { - throw new Error('invalid abi'); - } - result.push(value); - } - - return result; -} - -/** - * Is the string a hex string. - * - * @method check if string is hex string of specific length - * @param {String} value - * @param {Number} length - * @returns {Boolean} output the string is a hex string - */ -function isHexString(value, length) { - if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { - return false; - } - - if (length && value.length !== 2 + 2 * length) { - return false; - } - - return true; -} - -module.exports = { - arrayContainsArray: arrayContainsArray, - intToBuffer: intToBuffer, - getBinarySize: getBinarySize, - isHexPrefixed: isHexPrefixed, - stripHexPrefix: stripHexPrefix, - padToEven: padToEven, - intToHex: intToHex, - fromAscii: fromAscii, - fromUtf8: fromUtf8, - toAscii: toAscii, - toUtf8: toUtf8, - getKeys: getKeys, - isHexString: isHexString -}; -}).call(this,require("buffer").Buffer) -},{"buffer":987,"is-hex-prefixed":339,"strip-hex-prefix":716}],170:[function(require,module,exports){ -(function (Buffer){ -var md5 = require('create-hash/md5') -module.exports = EVP_BytesToKey -function EVP_BytesToKey (password, salt, keyLen, ivLen) { - if (!Buffer.isBuffer(password)) { - password = new Buffer(password, 'binary') - } - if (salt && !Buffer.isBuffer(salt)) { - salt = new Buffer(salt, 'binary') - } - keyLen = keyLen / 8 - ivLen = ivLen || 0 - var ki = 0 - var ii = 0 - var key = new Buffer(keyLen) - var iv = new Buffer(ivLen) - var addmd = 0 - var md_buf - var i - var bufs = [] - while (true) { - if (addmd++ > 0) { - bufs.push(md_buf) - } - bufs.push(password) - if (salt) { - bufs.push(salt) - } - md_buf = md5(Buffer.concat(bufs)) - bufs = [] - i = 0 - if (keyLen > 0) { - while (true) { - if (keyLen === 0) { - break - } - if (i === md_buf.length) { - break - } - key[ki++] = md_buf[i] - keyLen-- - i++ - } - } - if (ivLen > 0 && i !== md_buf.length) { - while (true) { - if (ivLen === 0) { - break - } - if (i === md_buf.length) { - break - } - iv[ii++] = md_buf[i] - ivLen-- - i++ - } - } - if (keyLen === 0 && ivLen === 0) { - break - } - } - for (i = 0; i < md_buf.length; i++) { - md_buf[i] = 0 - } - return { - key: key, - iv: iv - } -} - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"create-hash/md5":102}],171:[function(require,module,exports){ -const EventEmitter = require('events').EventEmitter -const assert = require('assert') -const fsm = require('fsm') - -module.exports = fsmEvent - -// create an fsmEvent instance -// obj -> fn -function fsmEvent (start, events) { - if (typeof start === 'object') { - events = start - start = 'START' - } - assert.equal(typeof start, 'string') - assert.equal(typeof events, 'object') - assert.ok(events[start], 'invalid starting state ' + start) - assert.ok(fsm.validate(events)) - - const emitter = new EventEmitter() - emit._graph = fsm.reachable(events) - emit._emitter = emitter - emit._events = events - emit._state = start - emit.emit = emit - emit.on = on - - return emit - - // set a state listener - // str, fn -> null - function on (event, cb) { - emitter.on(event, cb) - } - - // change the state - // str -> null - function emit (str) { - const nwState = emit._events[emit._state][str] - if (!reach(emit._state, nwState, emit._graph)) { - const err = 'invalid transition: ' + emit._state + ' -> ' + str - return emitter.emit('error', err) - } - - const leaveEv = emit._state + ':leave' - const enterEv = nwState + ':enter' - - if (!emit._state) return enter() - return leave() - - function leave () { - if (!emitter._events[leaveEv]) enter() - else emitter.emit(leaveEv, enter) - } - - function enter () { - if (!emitter._events[enterEv]) done() - else emitter.emit(enterEv, done) - } - - function done () { - emit._state = nwState - emitter.emit(nwState) - emitter.emit('done') - } - } -} - -// check if state can reach in reach -// str, str, obj -> bool -function reach (curr, next, reachable) { - if (!next) return false - if (!curr) return true - - const here = reachable[curr] - if (!here || !here[next]) return false - return here[next].length === 1 -} - -},{"assert":982,"events":989,"fsm":172}],172:[function(require,module,exports){ -function each(obj, iter) { - for(var key in obj) { - var value = obj[key] - iter(value, key, obj) - } -} - -function keys (obj) { - return Object.keys(obj).sort() -} - -function contains (a, v) { - return ~a.indexOf(v) -} -function union (a, b) { - return a.filter(function (v) { - return contains(b, v) - }) -} - -function disunion1(a, b) { - return a.filter(function (v) { - return !contains(b, v) - }) -} - -function disunion(a, b) { - return a.filter(function (v) { - return !contains(b, v) - }).concat(b.filter(function (v) { - return !contains(a, v) - })).sort() -} - -function equal (a, b) { - if(a.length != b.length) return false - for(var i in a) - if(b[i] !== a[i]) return false -} - -function empty (v) { - for(var k in v) - return false - return true -} - -//check that all transitions are to valid states. -var validate = exports.validate = function (fsm) { - var states = Object.keys(fsm) - each(fsm, function (state, name) { - each(state, function (_state, event) { - if(!fsm[_state]) - throw new Error( - 'invalid transition from state:' + name - + ' to state:' + _state - + ' on event:' + event - ) - }) - }) - return true -} - -//get a list of all states that are reachable from any given state. -//(with the shortest paths?) -// returns object: {STATES: {REACHABLE_STATE: path}} - -var reachable = exports.reachable = function (fsm) { - var reachable = {} - var added = false - do { - added = false - each(fsm, function (state, name) { - var reach = reachable[name] = reachable[name] || {} - //add any state that can be reached directly. - each(state, function (_name, event) { - if(!reach[_name]) reach[_name] = [event], added = true - }) - //add any state that can be reached from a state you can reach directly. - each(state, function (_name, event) { - var _state = reachable[_name] - each(_state, function (path, _name) { - if(!reach[_name]) - reach[_name] = [event].concat(path), added = true - }) - }) - }) - } while(added); - return reachable -} - -// deadlock: are there any dead ends that cannot reach another state? - -exports.terminal = -exports.deadlock = function (fsm) { - var dead = [] - each(fsm, function (state, name) { - if(empty(state)) dead.push(name) - }) - return dead -} - -// livelock; are there any cycles that cannot reach a terminal state? -// return any states that cannot reach the given terminal states, -// unless they are themselves terminal states. - -var livelock = exports.livelock = function (fsm, terminals) { - var reach = reachable(fsm), locked = [] - each(reach, function (reaches, name) { - if(contains(terminals, name)) return - each(terminals, function (_name) { - if(!reaches[_name] && !contains(locked, name)) - locked.push(name) - }) - }) - return locked.sort() -} - - -function events (fsm) { - var events = [] - each(fsm, function (state, name) { - each(state, function (_state, event) { - if(!contains(events, event)) events.push(event) - }) - }) - return events.sort() -} - -var combine = exports.combine = function (fsm1, fsm2, start1, start2) { - var combined = {} - var events1 = events(fsm1) - var events2 = events(fsm2) - var independent = disunion(events1, events2) - - function expand(name1, name2) { - var cName = name1 + '-' + name2, state - if(!combined[cName]) combined[cName] = {} - state = combined[cName] - - //Q: what are the events which are allowed to occur from this state? - //A: independent events (used in only one fsm) or events that occur in both fsms in current state. - - var trans1 = keys(fsm1[name1]), trans2 = keys(fsm2[name2]) - var allowed = union(trans1, trans2) - - //expand to a new state - allowed.forEach(function (event) { - state[event] = fsm1[name1][event] + '-' + fsm2[name2][event] - if(!combined[state[event]]) - expand(fsm1[name1][event], fsm2[name2][event]) - }) - - //only transition fsm1 - union(independent, trans1).forEach(function (event) { - state[event] = fsm1[name1][event] + '-' + name2 - if(!combined[state[event]]) - expand(fsm1[name1][event], name2) - }) - - union(independent, trans2).forEach(function (event) { - state[event] = name1 + '-' + fsm2[name2][event] - if(!combined[state[event]]) - expand(name1, fsm2[name2][event]) - }) - - return combined[cName] - } - - expand(start1, start2) - return combined -} - - -},{}],173:[function(require,module,exports){ -"use strict" - -module.exports = createRBTree - -var RED = 0 -var BLACK = 1 - -function RBNode(color, key, value, left, right, count) { - this._color = color - this.key = key - this.value = value - this.left = left - this.right = right - this._count = count -} - -function cloneNode(node) { - return new RBNode(node._color, node.key, node.value, node.left, node.right, node._count) -} - -function repaint(color, node) { - return new RBNode(color, node.key, node.value, node.left, node.right, node._count) -} - -function recount(node) { - node._count = 1 + (node.left ? node.left._count : 0) + (node.right ? node.right._count : 0) -} - -function RedBlackTree(compare, root) { - this._compare = compare - this.root = root -} - -var proto = RedBlackTree.prototype - -Object.defineProperty(proto, "keys", { - get: function() { - var result = [] - this.forEach(function(k,v) { - result.push(k) - }) - return result - } -}) - -Object.defineProperty(proto, "values", { - get: function() { - var result = [] - this.forEach(function(k,v) { - result.push(v) - }) - return result - } -}) - -//Returns the number of nodes in the tree -Object.defineProperty(proto, "length", { - get: function() { - if(this.root) { - return this.root._count - } - return 0 - } -}) - -//Insert a new item into the tree -proto.insert = function(key, value) { - var cmp = this._compare - //Find point to insert new node at - var n = this.root - var n_stack = [] - var d_stack = [] - while(n) { - var d = cmp(key, n.key) - n_stack.push(n) - d_stack.push(d) - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - //Rebuild path to leaf node - n_stack.push(new RBNode(RED, key, value, null, null, 1)) - for(var s=n_stack.length-2; s>=0; --s) { - var n = n_stack[s] - if(d_stack[s] <= 0) { - n_stack[s] = new RBNode(n._color, n.key, n.value, n_stack[s+1], n.right, n._count+1) - } else { - n_stack[s] = new RBNode(n._color, n.key, n.value, n.left, n_stack[s+1], n._count+1) - } - } - //Rebalance tree using rotations - //console.log("start insert", key, d_stack) - for(var s=n_stack.length-1; s>1; --s) { - var p = n_stack[s-1] - var n = n_stack[s] - if(p._color === BLACK || n._color === BLACK) { - break - } - var pp = n_stack[s-2] - if(pp.left === p) { - if(p.left === n) { - var y = pp.right - if(y && y._color === RED) { - //console.log("LLr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LLb") - pp._color = RED - pp.left = p.right - p._color = BLACK - p.right = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = p - } else { - ppp.right = p - } - } - break - } - } else { - var y = pp.right - if(y && y._color === RED) { - //console.log("LRr") - p._color = BLACK - pp.right = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("LRb") - p.right = n.left - pp._color = RED - pp.left = n.right - n._color = BLACK - n.left = p - n.right = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.left === pp) { - ppp.left = n - } else { - ppp.right = n - } - } - break - } - } - } else { - if(p.right === n) { - var y = pp.left - if(y && y._color === RED) { - //console.log("RRr", y.key) - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RRb") - pp._color = RED - pp.right = p.left - p._color = BLACK - p.left = pp - n_stack[s-2] = p - n_stack[s-1] = n - recount(pp) - recount(p) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = p - } else { - ppp.left = p - } - } - break - } - } else { - var y = pp.left - if(y && y._color === RED) { - //console.log("RLr") - p._color = BLACK - pp.left = repaint(BLACK, y) - pp._color = RED - s -= 1 - } else { - //console.log("RLb") - p.left = n.right - pp._color = RED - pp.right = n.left - n._color = BLACK - n.right = p - n.left = pp - n_stack[s-2] = n - n_stack[s-1] = p - recount(pp) - recount(p) - recount(n) - if(s >= 3) { - var ppp = n_stack[s-3] - if(ppp.right === pp) { - ppp.right = n - } else { - ppp.left = n - } - } - break - } - } - } - } - //Return new tree - n_stack[0]._color = BLACK - return new RedBlackTree(cmp, n_stack[0]) -} - - -//Visit all nodes inorder -function doVisitFull(visit, node) { - if(node.left) { - var v = doVisitFull(visit, node.left) - if(v) { return v } - } - var v = visit(node.key, node.value) - if(v) { return v } - if(node.right) { - return doVisitFull(visit, node.right) - } -} - -//Visit half nodes in order -function doVisitHalf(lo, compare, visit, node) { - var l = compare(lo, node.key) - if(l <= 0) { - if(node.left) { - var v = doVisitHalf(lo, compare, visit, node.left) - if(v) { return v } - } - var v = visit(node.key, node.value) - if(v) { return v } - } - if(node.right) { - return doVisitHalf(lo, compare, visit, node.right) - } -} - -//Visit all nodes within a range -function doVisit(lo, hi, compare, visit, node) { - var l = compare(lo, node.key) - var h = compare(hi, node.key) - var v - if(l <= 0) { - if(node.left) { - v = doVisit(lo, hi, compare, visit, node.left) - if(v) { return v } - } - if(h > 0) { - v = visit(node.key, node.value) - if(v) { return v } - } - } - if(h > 0 && node.right) { - return doVisit(lo, hi, compare, visit, node.right) - } -} - - -proto.forEach = function rbTreeForEach(visit, lo, hi) { - if(!this.root) { - return - } - switch(arguments.length) { - case 1: - return doVisitFull(visit, this.root) - break - - case 2: - return doVisitHalf(lo, this._compare, visit, this.root) - break - - case 3: - if(this._compare(lo, hi) >= 0) { - return - } - return doVisit(lo, hi, this._compare, visit, this.root) - break - } -} - -//First item in list -Object.defineProperty(proto, "begin", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.left - } - return new RedBlackTreeIterator(this, stack) - } -}) - -//Last item in list -Object.defineProperty(proto, "end", { - get: function() { - var stack = [] - var n = this.root - while(n) { - stack.push(n) - n = n.right - } - return new RedBlackTreeIterator(this, stack) - } -}) - -//Find the ith item in the tree -proto.at = function(idx) { - if(idx < 0) { - return new RedBlackTreeIterator(this, []) - } - var n = this.root - var stack = [] - while(true) { - stack.push(n) - if(n.left) { - if(idx < n.left._count) { - n = n.left - continue - } - idx -= n.left._count - } - if(!idx) { - return new RedBlackTreeIterator(this, stack) - } - idx -= 1 - if(n.right) { - if(idx >= n.right._count) { - break - } - n = n.right - } else { - break - } - } - return new RedBlackTreeIterator(this, []) -} - -proto.ge = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d <= 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} - -proto.gt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d < 0) { - last_ptr = stack.length - } - if(d < 0) { - n = n.left - } else { - n = n.right - } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} - -proto.lt = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d > 0) { - last_ptr = stack.length - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} - -proto.le = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - var last_ptr = 0 - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d >= 0) { - last_ptr = stack.length - } - if(d < 0) { - n = n.left - } else { - n = n.right - } - } - stack.length = last_ptr - return new RedBlackTreeIterator(this, stack) -} - -//Finds the item with key if it exists -proto.find = function(key) { - var cmp = this._compare - var n = this.root - var stack = [] - while(n) { - var d = cmp(key, n.key) - stack.push(n) - if(d === 0) { - return new RedBlackTreeIterator(this, stack) - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - return new RedBlackTreeIterator(this, []) -} - -//Removes item with key from tree -proto.remove = function(key) { - var iter = this.find(key) - if(iter) { - return iter.remove() - } - return this -} - -//Returns the item at `key` -proto.get = function(key) { - var cmp = this._compare - var n = this.root - while(n) { - var d = cmp(key, n.key) - if(d === 0) { - return n.value - } - if(d <= 0) { - n = n.left - } else { - n = n.right - } - } - return -} - -//Iterator for red black tree -function RedBlackTreeIterator(tree, stack) { - this.tree = tree - this._stack = stack -} - -var iproto = RedBlackTreeIterator.prototype - -//Test if iterator is valid -Object.defineProperty(iproto, "valid", { - get: function() { - return this._stack.length > 0 - } -}) - -//Node of the iterator -Object.defineProperty(iproto, "node", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1] - } - return null - }, - enumerable: true -}) - -//Makes a copy of an iterator -iproto.clone = function() { - return new RedBlackTreeIterator(this.tree, this._stack.slice()) -} - -//Swaps two nodes -function swapNode(n, v) { - n.key = v.key - n.value = v.value - n.left = v.left - n.right = v.right - n._color = v._color - n._count = v._count -} - -//Fix up a double black node in a tree -function fixDoubleBlack(stack) { - var n, p, s, z - for(var i=stack.length-1; i>=0; --i) { - n = stack[i] - if(i === 0) { - n._color = BLACK - return - } - //console.log("visit node:", n.key, i, stack[i].key, stack[i-1].key) - p = stack[i-1] - if(p.left === n) { - //console.log("left child") - s = p.right - if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.right = cloneNode(s) - z = s.right = cloneNode(s.right) - p.right = s.left - s.left = p - s.right = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - return - } else if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red") - s = p.right = cloneNode(s) - z = s.left = cloneNode(s.left) - p.right = z.left - s.left = z.right - z.left = p - z.right = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = z - } else { - pp.right = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent", p.right.value) - p._color = BLACK - p.right = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent", p.right.value) - p.right = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.right = s.left - s.left = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.left === p) { - pp.left = s - } else { - pp.right = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } else { - //console.log("right child") - s = p.left - if(s.left && s.left._color === RED) { - //console.log("case 1: left sibling child red", p.value, p._color) - s = p.left = cloneNode(s) - z = s.left = cloneNode(s.left) - p.left = s.right - s.right = p - s.left = z - s._color = p._color - n._color = BLACK - p._color = BLACK - z._color = BLACK - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - return - } else if(s.right && s.right._color === RED) { - //console.log("case 1: right sibling child red") - s = p.left = cloneNode(s) - z = s.right = cloneNode(s.right) - p.left = z.right - s.right = z.left - z.right = p - z.left = s - z._color = p._color - p._color = BLACK - s._color = BLACK - n._color = BLACK - recount(p) - recount(s) - recount(z) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = z - } else { - pp.left = z - } - } - stack[i-1] = z - return - } - if(s._color === BLACK) { - if(p._color === RED) { - //console.log("case 2: black sibling, red parent") - p._color = BLACK - p.left = repaint(RED, s) - return - } else { - //console.log("case 2: black sibling, black parent") - p.left = repaint(RED, s) - continue - } - } else { - //console.log("case 3: red sibling") - s = cloneNode(s) - p.left = s.right - s.right = p - s._color = p._color - p._color = RED - recount(p) - recount(s) - if(i > 1) { - var pp = stack[i-2] - if(pp.right === p) { - pp.right = s - } else { - pp.left = s - } - } - stack[i-1] = s - stack[i] = p - if(i+1 < stack.length) { - stack[i+1] = n - } else { - stack.push(n) - } - i = i+2 - } - } - } -} - -//Removes item at iterator from tree -iproto.remove = function() { - var stack = this._stack - if(stack.length === 0) { - return this.tree - } - //First copy path to node - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, n.value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - var n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - } - - //Get node - n = cstack[cstack.length-1] - //console.log("start remove: ", n.value) - - //If not leaf, then swap with previous node - if(n.left && n.right) { - //console.log("moving to leaf") - - //First walk to previous leaf - var split = cstack.length - n = n.left - while(n.right) { - cstack.push(n) - n = n.right - } - //Copy path to leaf - var v = cstack[split-1] - cstack.push(new RBNode(n._color, v.key, v.value, n.left, n.right, n._count)) - cstack[split-1].key = n.key - cstack[split-1].value = n.value - - //Fix up stack - for(var i=cstack.length-2; i>=split; --i) { - n = cstack[i] - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - cstack[split-1].left = cstack[split] - } - //console.log("stack=", cstack.map(function(v) { return v.value })) - - //Remove leaf node - n = cstack[cstack.length-1] - if(n._color === RED) { - //Easy case: removing red leaf - //console.log("RED leaf") - var p = cstack[cstack.length-2] - if(p.left === n) { - p.left = null - } else if(p.right === n) { - p.right = null - } - cstack.pop() - for(var i=0; i 0) { - return this._stack[this._stack.length-1].key - } - return - }, - enumerable: true -}) - -//Returns value -Object.defineProperty(iproto, "value", { - get: function() { - if(this._stack.length > 0) { - return this._stack[this._stack.length-1].value - } - return - }, - enumerable: true -}) - - -//Returns the position of this iterator in the sorted list -Object.defineProperty(iproto, "index", { - get: function() { - var idx = 0 - var stack = this._stack - if(stack.length === 0) { - var r = this.tree.root - if(r) { - return r._count - } - return 0 - } else if(stack[stack.length-1].left) { - idx = stack[stack.length-1].left._count - } - for(var s=stack.length-2; s>=0; --s) { - if(stack[s+1] === stack[s].right) { - ++idx - if(stack[s].left) { - idx += stack[s].left._count - } - } - } - return idx - }, - enumerable: true -}) - -//Advances iterator to next element in list -iproto.next = function() { - var stack = this._stack - if(stack.length === 0) { - return - } - var n = stack[stack.length-1] - if(n.right) { - n = n.right - while(n) { - stack.push(n) - n = n.left - } - } else { - stack.pop() - while(stack.length > 0 && stack[stack.length-1].right === n) { - n = stack[stack.length-1] - stack.pop() - } - } -} - -//Checks if iterator is at end of tree -Object.defineProperty(iproto, "hasNext", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].right) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].left === stack[s]) { - return true - } - } - return false - } -}) - -//Update value -iproto.update = function(value) { - var stack = this._stack - if(stack.length === 0) { - throw new Error("Can't update empty node!") - } - var cstack = new Array(stack.length) - var n = stack[stack.length-1] - cstack[cstack.length-1] = new RBNode(n._color, n.key, value, n.left, n.right, n._count) - for(var i=stack.length-2; i>=0; --i) { - n = stack[i] - if(n.left === stack[i+1]) { - cstack[i] = new RBNode(n._color, n.key, n.value, cstack[i+1], n.right, n._count) - } else { - cstack[i] = new RBNode(n._color, n.key, n.value, n.left, cstack[i+1], n._count) - } - } - return new RedBlackTree(this.tree._compare, cstack[0]) -} - -//Moves iterator backward one element -iproto.prev = function() { - var stack = this._stack - if(stack.length === 0) { - return - } - var n = stack[stack.length-1] - if(n.left) { - n = n.left - while(n) { - stack.push(n) - n = n.right - } - } else { - stack.pop() - while(stack.length > 0 && stack[stack.length-1].left === n) { - n = stack[stack.length-1] - stack.pop() - } - } -} - -//Checks if iterator is at start of tree -Object.defineProperty(iproto, "hasPrev", { - get: function() { - var stack = this._stack - if(stack.length === 0) { - return false - } - if(stack[stack.length-1].left) { - return true - } - for(var s=stack.length-1; s>0; --s) { - if(stack[s-1].right === stack[s]) { - return true - } - } - return false - } -}) - -//Default comparison function -function defaultCompare(a, b) { - if(a < b) { - return -1 - } - if(a > b) { - return 1 - } - return 0 -} - -//Build a tree -function createRBTree(compare) { - return new RedBlackTree(compare || defaultCompare, null) -} -},{}],174:[function(require,module,exports){ -var util = require('util') - -var INDENT_START = /[\{\[]/ -var INDENT_END = /[\}\]]/ - -module.exports = function() { - var lines = [] - var indent = 0 - - var push = function(str) { - var spaces = '' - while (spaces.length < indent*2) spaces += ' ' - lines.push(spaces+str) - } - - var line = function(fmt) { - if (!fmt) return line - - if (INDENT_END.test(fmt.trim()[0]) && INDENT_START.test(fmt[fmt.length-1])) { - indent-- - push(util.format.apply(util, arguments)) - indent++ - return line - } - if (INDENT_START.test(fmt[fmt.length-1])) { - push(util.format.apply(util, arguments)) - indent++ - return line - } - if (INDENT_END.test(fmt.trim()[0])) { - indent-- - push(util.format.apply(util, arguments)) - return line - } - - push(util.format.apply(util, arguments)) - return line - } - - line.toString = function() { - return lines.join('\n') - } - - line.toFunction = function(scope) { - var src = 'return ('+line.toString()+')' - - var keys = Object.keys(scope || {}).map(function(key) { - return key - }) - - var vals = keys.map(function(key) { - return scope[key] - }) - - return Function.apply(null, keys.concat(src)).apply(null, vals) - } - - if (arguments.length) line.apply(null, arguments) - - return line -} - -},{"util":1036}],175:[function(require,module,exports){ -var isProperty = require('is-property') - -var gen = function(obj, prop) { - return isProperty(prop) ? obj+'.'+prop : obj+'['+JSON.stringify(prop)+']' -} - -gen.valid = isProperty -gen.property = function (prop) { - return isProperty(prop) ? prop : JSON.stringify(prop) -} - -module.exports = gen - -},{"is-property":341}],176:[function(require,module,exports){ -(function (Buffer){ -'use strict' -var Transform = require('stream').Transform -var inherits = require('inherits') - -function HashBase (blockSize) { - Transform.call(this) - - this._block = new Buffer(blockSize) - this._blockSize = blockSize - this._blockOffset = 0 - this._length = [0, 0, 0, 0] - - this._finalized = false -} - -inherits(HashBase, Transform) - -HashBase.prototype._transform = function (chunk, encoding, callback) { - var error = null - try { - if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding) - this.update(chunk) - } catch (err) { - error = err - } - - callback(error) -} - -HashBase.prototype._flush = function (callback) { - var error = null - try { - this.push(this._digest()) - } catch (err) { - error = err - } - - callback(error) -} - -HashBase.prototype.update = function (data, encoding) { - if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') - if (this._finalized) throw new Error('Digest already called') - if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary') - - // consume data - var block = this._block - var offset = 0 - while (this._blockOffset + data.length - offset >= this._blockSize) { - for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] - this._update() - this._blockOffset = 0 - } - while (offset < data.length) block[this._blockOffset++] = data[offset++] - - // update length - for (var j = 0, carry = data.length * 8; carry > 0; ++j) { - this._length[j] += carry - carry = (this._length[j] / 0x0100000000) | 0 - if (carry > 0) this._length[j] -= 0x0100000000 * carry - } - - return this -} - -HashBase.prototype._update = function (data) { - throw new Error('_update is not implemented') -} - -HashBase.prototype.digest = function (encoding) { - if (this._finalized) throw new Error('Digest already called') - this._finalized = true - - var digest = this._digest() - if (encoding !== undefined) digest = digest.toString(encoding) - return digest -} - -HashBase.prototype._digest = function () { - throw new Error('_digest is not implemented') -} - -module.exports = HashBase - -}).call(this,require("buffer").Buffer) -},{"buffer":987,"inherits":216,"stream":1028}],177:[function(require,module,exports){ -var hash = exports; - -hash.utils = require('./hash/utils'); -hash.common = require('./hash/common'); -hash.sha = require('./hash/sha'); -hash.ripemd = require('./hash/ripemd'); -hash.hmac = require('./hash/hmac'); - -// 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; - -},{"./hash/common":178,"./hash/hmac":179,"./hash/ripemd":180,"./hash/sha":181,"./hash/utils":188}],178:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var assert = require('minimalistic-assert'); - -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; -}; - -},{"./utils":188,"minimalistic-assert":509}],179:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var assert = require('minimalistic-assert'); - -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -module.exports = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; - -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; - -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; - -},{"./utils":188,"minimalistic-assert":509}],180:[function(require,module,exports){ -'use strict'; - -var utils = require('./utils'); -var common = require('./common'); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_3 = utils.sum32_3; -var sum32_4 = utils.sum32_4; -var BlockHash = common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash); -exports.ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; -RIPEMD160.padLength = 64; - -RIPEMD160.prototype._update = function update(msg, start) { - 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 Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32( - rotl32( - sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32(C, 10); - C = B; - B = T; - T = sum32( - rotl32( - sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3(this.h[1], C, Dh); - this.h[1] = sum32_3(this.h[2], D, Eh); - this.h[2] = sum32_3(this.h[3], E, Ah); - this.h[3] = sum32_3(this.h[4], A, Bh); - this.h[4] = sum32_3(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; - -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 -]; - -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; - -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 -]; - -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; - -},{"./common":178,"./utils":188}],181:[function(require,module,exports){ -'use strict'; - -exports.sha1 = require('./sha/1'); -exports.sha224 = require('./sha/224'); -exports.sha256 = require('./sha/256'); -exports.sha384 = require('./sha/384'); -exports.sha512 = require('./sha/512'); - -},{"./sha/1":182,"./sha/224":183,"./sha/256":184,"./sha/384":185,"./sha/512":186}],182:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var shaCommon = require('./common'); - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_5 = utils.sum32_5; -var ft_1 = shaCommon.ft_1; -var BlockHash = common.BlockHash; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; - -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash.call(this); - this.h = [ - 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash); -module.exports = SHA1; - -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; -SHA1.padLength = 64; - -SHA1.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] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - - 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]; - - for (i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32(b, 30); - b = a; - a = t; - } - - 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); -}; - -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -},{"../common":178,"../utils":188,"./common":187}],183:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var SHA256 = require('./256'); - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ - 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, SHA256); -module.exports = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; -SHA224.padLength = 64; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - - -},{"../utils":188,"./256":184}],184:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var shaCommon = require('./common'); -var assert = require('minimalistic-assert'); - -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'); -}; - -},{"../common":178,"../utils":188,"./common":187,"minimalistic-assert":509}],185:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); - -var SHA512 = require('./512'); - -function SHA384() { - if (!(this instanceof SHA384)) - return new SHA384(); - - SHA512.call(this); - this.h = [ - 0xcbbb9d5d, 0xc1059ed8, - 0x629a292a, 0x367cd507, - 0x9159015a, 0x3070dd17, - 0x152fecd8, 0xf70e5939, - 0x67332667, 0xffc00b31, - 0x8eb44a87, 0x68581511, - 0xdb0c2e0d, 0x64f98fa7, - 0x47b5481d, 0xbefa4fa4 ]; -} -utils.inherits(SHA384, SHA512); -module.exports = SHA384; - -SHA384.blockSize = 1024; -SHA384.outSize = 384; -SHA384.hmacStrength = 192; -SHA384.padLength = 128; - -SHA384.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 12), 'big'); - else - return utils.split32(this.h.slice(0, 12), 'big'); -}; - -},{"../utils":188,"./512":186}],186:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -var common = require('../common'); -var assert = require('minimalistic-assert'); - -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; -} - -},{"../common":178,"../utils":188,"minimalistic-assert":509}],187:[function(require,module,exports){ -'use strict'; - -var utils = require('../utils'); -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; - -},{"../utils":188}],188:[function(require,module,exports){ -'use strict'; - -var assert = require('minimalistic-assert'); -var inherits = require('inherits'); - -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; - -},{"inherits":216,"minimalistic-assert":509}],189:[function(require,module,exports){ -'use strict'; - -var hash = require('hash.js'); -var utils = require('minimalistic-crypto-utils'); -var assert = require('minimalistic-assert'); - -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - - this._reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - - var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); - var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); - var pers = utils.toArray(options.pers, options.persEnc || 'hex'); - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -module.exports = HmacDRBG; - -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this._reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new hash.hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; - - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils.toArray(entropy, entropyEnc); - add = utils.toArray(add, addEnc); - - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this._reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this._reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils.toArray(add, addEnc || 'hex'); - this._update(add); - } - - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - - var res = temp.slice(0, len); - this._update(add); - this._reseed++; - return utils.encode(res, enc); -}; - -},{"hash.js":177,"minimalistic-assert":509,"minimalistic-crypto-utils":510}],190:[function(require,module,exports){ -var hpack = exports; - -hpack.utils = require('./hpack/utils'); -hpack.huffman = require('./hpack/huffman'); -hpack['static-table'] = require('./hpack/static-table'); -hpack.table = require('./hpack/table'); - -hpack.decoder = require('./hpack/decoder'); -hpack.decompressor = require('./hpack/decompressor'); - -hpack.encoder = require('./hpack/encoder'); -hpack.compressor = require('./hpack/compressor'); - -},{"./hpack/compressor":191,"./hpack/decoder":192,"./hpack/decompressor":193,"./hpack/encoder":194,"./hpack/huffman":195,"./hpack/static-table":196,"./hpack/table":197,"./hpack/utils":198}],191:[function(require,module,exports){ -var hpack = require('../hpack'); -var utils = hpack.utils; -var encoder = hpack.encoder; -var table = hpack.table; -var assert = utils.assert; - -var inherits = require('inherits'); -var Duplex = require('readable-stream').Duplex; - -function Compressor(options) { - Duplex.call(this, { - writableObjectMode: true - }); - - this._encoder = null; - this._table = table.create(options.table); -} -inherits(Compressor, Duplex); -module.exports = Compressor; - -Compressor.create = function create(options) { - return new Compressor(options); -}; - -Compressor.prototype._read = function _read() { - // We only push! -}; - -Compressor.prototype._write = function _write(data, enc, cb) { - assert(Array.isArray(data), 'Compressor.write() expects list of headers'); - - this._encoder = encoder.create(); - for (var i = 0; i < data.length; i++) - this._encodeHeader(data[i]); - - var data = this._encoder.render(); - this._encoder = null; - - cb(null); - for (var i = 0; i < data.length; i++) - this.push(data[i]); -}; - -Compressor.prototype.updateTableSize = function updateTableSize(size) { - if (size >= this._table.protocolMaxSize) { - size = this._table.protocolMaxSize; - - var enc = encoder.create(); - - // indexed = 0 - // incremental = 0 - // update = 1 - enc.encodeBits(1, 3); - enc.encodeInt(size); - - var data = enc.render(); - for (var i = 0; i < data.length; i++) - this.push(data[i]); - } - - this._table.updateSize(size); -}; - -Compressor.prototype.reset = function reset() { - var enc = encoder.create(); - var size = this._table.maxSize; - - // indexed = 0 - // incremental = 0 - // update = 1 - enc.encodeBits(1, 3); - enc.encodeInt(0); - - // Evict everything - this._table.updateSize(0); - - // indexed = 0 - // incremental = 0 - // update = 1 - enc.encodeBits(1, 3); - enc.encodeInt(size); - - // Revert size - this._table.updateSize(size); - - var data = enc.render(); - for (var i = 0; i < data.length; i++) - this.push(data[i]); -}; - -Compressor.prototype._encodeHeader = function _encodeHeader(header) { - if (header.neverIndex) { - var index = 0; - var neverIndex = 1; - var isIndexed = 0; - var isIncremental = 0; - } else { - var index = this._table.reverseLookup(header.name, header.value); - var isIndexed = index > 0; - var isIncremental = header.incremental !== false; - var neverIndex = 0; - } - - this._encoder.encodeBit(isIndexed); - if (isIndexed) { - this._encoder.encodeInt(index); - return; - } - - var name = utils.toArray(header.name); - var value = utils.toArray(header.value); - - this._encoder.encodeBit(isIncremental); - if (isIncremental) { - this._table.add(header.name, header.value, name.length, value.length); - } else { - // Update = false - this._encoder.encodeBit(0); - this._encoder.encodeBit(neverIndex); - } - - // index is negative for `name`-only headers - this._encoder.encodeInt(-index); - if (index === 0) - this._encoder.encodeStr(name, header.huffman !== false); - this._encoder.encodeStr(value, header.huffman !== false); -}; - -},{"../hpack":190,"inherits":216,"readable-stream":207}],192:[function(require,module,exports){ -var hpack = require('../hpack'); -var utils = hpack.utils; -var huffman = hpack.huffman.decode; -var assert = utils.assert; - -var OffsetBuffer = require('obuf'); - -function Decoder() { - this.buffer = new OffsetBuffer(); - this.bitOffset = 0; - - // Used internally in decodeStr - this._huffmanNode = null; -} -module.exports = Decoder; - -Decoder.create = function create() { - return new Decoder(); -}; - -Decoder.prototype.isEmpty = function isEmpty() { - return this.buffer.isEmpty(); -}; - -Decoder.prototype.push = function push(chunk) { - this.buffer.push(chunk); -}; - -Decoder.prototype.decodeBit = function decodeBit() { - // Need at least one octet - assert(this.buffer.has(1), 'Buffer too small for an int'); - - var octet; - var offset = this.bitOffset; - - if (++this.bitOffset === 8) { - octet = this.buffer.readUInt8(); - this.bitOffset = 0; - } else { - octet = this.buffer.peekUInt8(); - } - return (octet >>> (7 - offset)) & 1; -}; - -// Just for testing -Decoder.prototype.skipBits = function skipBits(n) { - this.bitOffset += n; - this.buffer.skip(this.bitOffset >> 3); - this.bitOffset &= 0x7; -}; - -Decoder.prototype.decodeInt = function decodeInt() { - // Need at least one octet - assert(this.buffer.has(1), 'Buffer too small for an int'); - - var prefix = 8 - this.bitOffset; - - // We are going to end up octet-aligned - this.bitOffset = 0; - - var max = (1 << prefix) - 1; - var octet = this.buffer.readUInt8() & max; - - // Fast case - int fits into the prefix - if (octet !== max) - return octet; - - // TODO(indutny): what about > 32bit numbers? - var res = 0; - var isLast = false; - var len = 0; - do { - octet = this.buffer.readUInt8(); - isLast = (octet & 0x80) === 0; - - res <<= 7; - res |= octet & 0x7f; - len++; - } while (!isLast); - assert(isLast, 'Incomplete data for multi-octet integer'); - assert(len <= 4, 'Integer does not fit into 32 bits'); - - // Reverse bits - res = (res >>> 21) | - (((res >> 14) & 0x7f) << 7) | - (((res >> 7) & 0x7f) << 14) | - ((res & 0x7f) << 21); - res >>= (4 - len) * 7; - - // Append prefix max - res += max; - - return res; -}; - -Decoder.prototype.decodeHuffmanWord = function decodeHuffmanWord(input, - inputBits, - out) { - var root = huffman; - var node = this._huffmanNode; - var word = input; - var bits = inputBits; - - for (; bits > 0; word &= (1 << bits) - 1) { - // Nudge the word bit length to match it - for (var i = Math.max(0, bits - 8); i < bits; i++) { - var subnode = node[word >>> i]; - if (typeof subnode !== 'number') { - node = subnode; - bits = i; - break; - } - - if (subnode === 0) - continue; - - // Word bit length should match - if ((subnode >>> 9) !== bits - i) { - subnode = 0; - continue; - } - - var octet = subnode & 0x1ff; - assert(octet !== 256, 'EOS in encoding'); - out.push(octet); - node = root; - - bits = i; - break; - } - if (subnode === 0) - break; - } - this._huffmanNode = node; - - return bits; -}; - -Decoder.prototype.decodeStr = function decodeStr() { - var isHuffman = this.decodeBit(); - var len = this.decodeInt(); - assert(this.buffer.has(len), 'Not enough octets for string'); - - if (!isHuffman) - return this.buffer.take(len); - - this._huffmanNode = huffman; - - var out = []; - - var word = 0; - var bits = 0; - var lastKey = 0; - for (var i = 0; i < len; i++) { - word <<= 8; - word |= this.buffer.readUInt8(); - bits += 8; - - bits = this.decodeHuffmanWord(word, bits, out); - lastKey = word >> bits; - word &= (1 << bits) - 1; - } - assert(this._huffmanNode === huffman, '8-bit EOS'); - assert(word + 1 === (1 << bits), 'Final sequence is not EOS'); - - this._huffmanNode = null; - - return out; -}; - -},{"../hpack":190,"obuf":561}],193:[function(require,module,exports){ -(function (process){ -var hpack = require('../hpack'); -var utils = hpack.utils; -var decoder = hpack.decoder; -var table = hpack.table; -var assert = utils.assert; - -var inherits = require('inherits'); -var Duplex = require('readable-stream').Duplex; - -function Decompressor(options) { - Duplex.call(this, { - readableObjectMode: true - }); - - this._decoder = decoder.create(); - this._table = table.create(options.table); -} -inherits(Decompressor, Duplex); -module.exports = Decompressor; - -Decompressor.create = function create(options) { - return new Decompressor(options); -}; - -Decompressor.prototype._read = function _read() { - // We only push! -}; - -Decompressor.prototype._write = function _write(data, enc, cb) { - this._decoder.push(data); - - cb(null); -}; - -Decompressor.prototype.execute = function execute(cb) { - while (!this._decoder.isEmpty()) { - try { - this._execute(); - } catch (err) { - if (cb) - return done(err); - else - return this.emit('error', err); - } - } - - if (cb) - done(null); - - function done(err) { - process.nextTick(function() { - cb(err); - }); - } -}; - -Decompressor.prototype.updateTableSize = function updateTableSize(size) { - this._table.updateSize(size); -}; - -Decompressor.prototype._execute = function _execute() { - var isIndexed = this._decoder.decodeBit(); - if (isIndexed) - return this._processIndexed(); - - var isIncremental = this._decoder.decodeBit(); - var neverIndex = 0; - if (!isIncremental) { - var isUpdate = this._decoder.decodeBit(); - if (isUpdate) - return this._processUpdate(); - - neverIndex = this._decoder.decodeBit(); - } - - this._processLiteral(isIncremental, neverIndex); -}; - -Decompressor.prototype._processIndexed = function _processIndexed() { - var index = this._decoder.decodeInt(); - - var lookup = this._table.lookup(index); - this.push({ name: lookup.name, value: lookup.value, neverIndex: false }); -}; - -Decompressor.prototype._processLiteral = function _processLiteral(inc, never) { - var index = this._decoder.decodeInt(); - - var name; - var nameSize; - - // Literal header-name too - if (index === 0) { - name = this._decoder.decodeStr(); - nameSize = name.length; - name = utils.stringify(name); - } else { - var lookup = this._table.lookup(index); - nameSize = lookup.nameSize; - name = lookup.name; - } - - var value = this._decoder.decodeStr(); - var valueSize = value.length; - value = utils.stringify(value); - - if (inc) - this._table.add(name, value, nameSize, valueSize); - - this.push({ name: name, value: value, neverIndex: never !== 0}); -}; - -Decompressor.prototype._processUpdate = function _processUpdate() { - var size = this._decoder.decodeInt(); - this.updateTableSize(size); -}; - -}).call(this,require('_process')) -},{"../hpack":190,"_process":1009,"inherits":216,"readable-stream":207}],194:[function(require,module,exports){ -var hpack = require('../hpack'); -var utils = hpack.utils; -var huffman = hpack.huffman.encode; -var assert = utils.assert; - -var WBuf = require('wbuf'); - -function Encoder() { - this.buffer = new WBuf(); - this.word = 0; - this.bitOffset = 0; -} -module.exports = Encoder; - -Encoder.create = function create() { - return new Encoder(); -}; - -Encoder.prototype.render = function render() { - return this.buffer.render(); -}; - -Encoder.prototype.encodeBit = function encodeBit(bit) { - var octet; - - this.word <<= 1; - this.word |= bit; - this.bitOffset++; - - if (this.bitOffset === 8) { - this.buffer.writeUInt8(this.word); - this.word = 0; - this.bitOffset = 0; - } -}; - -Encoder.prototype.encodeBits = function encodeBits(bits, len) { - var left = bits; - var leftLen = len; - - while (leftLen > 0) { - var avail = Math.min(leftLen, 8 - this.bitOffset); - var toWrite = left >>> (leftLen - avail); - - if (avail === 8) { - this.buffer.writeUInt8(toWrite); - } else { - this.word <<= avail; - this.word |= toWrite; - this.bitOffset += avail; - if (this.bitOffset === 8) { - this.buffer.writeUInt8(this.word); - this.word = 0; - this.bitOffset = 0; - } - } - - leftLen -= avail; - left &= (1 << leftLen) - 1; - } -}; - -// Just for testing -Encoder.prototype.skipBits = function skipBits(num) { - this.bitOffset += num; - this.buffer.skip(this.bitOffset >> 3); - this.bitOffset &= 0x7; -}; - -Encoder.prototype.encodeInt = function encodeInt(num) { - var prefix = 8 - this.bitOffset; - - // We are going to end up octet-aligned - this.bitOffset = 0; - - var max = (1 << prefix) - 1; - - // Fast case - int fits into the prefix - if (num < max) { - this.buffer.writeUInt8((this.word << prefix) | num); - return octet; - } - - var left = num - max; - this.buffer.writeUInt8((this.word << prefix) | max); - do { - var octet = left & 0x7f; - left >>= 7; - if (left !== 0) - octet |= 0x80; - - this.buffer.writeUInt8(octet); - } while (left !== 0); -}; - -Encoder.prototype.encodeStr = function encodeStr(value, isHuffman) { - this.encodeBit(isHuffman ? 1 : 0); - - if (!isHuffman) { - this.buffer.reserve(value.length + 1); - this.encodeInt(value.length); - for (var i = 0; i < value.length; i++) - this.buffer.writeUInt8(value[i]); - return; - } - - var codes = []; - var len = 0; - var pad = 0; - - for (var i = 0; i < value.length; i++) { - var code = huffman[value[i]]; - codes.push(code); - len += code[0]; - } - if (len % 8 !== 0) - pad = 8 - (len % 8); - len += pad; - - this.buffer.reserve((len / 8) + 1); - this.encodeInt(len / 8); - for (var i = 0; i < codes.length; i++) { - var code = codes[i]; - this.encodeBits(code[1], code[0]); - } - - // Append padding - this.encodeBits(0xff >>> (8 - pad), pad); -}; - -},{"../hpack":190,"wbuf":729}],195:[function(require,module,exports){ -exports.decode = - [2608,2609,2610,2657,2659,2661,2665,2671,2675,2676,0,0,0,0,0,0,0,0,0,0, - 3104,3109,3117,3118,3119,3123,3124,3125,3126,3127,3128,3129,3133,3137,3167, - 3170,3172,3174,3175,3176,3180,3181,3182,3184,3186,3189,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 3642,3650,3651,3652,3653,3654,3655,3656,3657,3658,3659,3660,3661,3662,3663, - 3664,3665,3666,3667,3668,3669,3670,3671,3673,3690,3691,3697,3702,3703,3704, - 3705,3706,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,4134,4138,4140,4155,4184,4186,[1057, - 1058,1064,1065,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], - [1087,0,1575,1579,1660,0,0,0,0,0,2083,2110,0,0,0,0,0,0,0,0,0,0,0,0,2560, - 2596,2624,2651,2653,2686,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,3166,3197,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3644, - 3680,3707,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,[1628,1731,1744,0,0,0,2176,2178, - 2179,2210,2232,2242,2272,2274,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2713,2721,2727, - 2732,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0],[2736,2737,2739,2769,2776,2777,2787,2789,2790,0,0,0,0,0,0,0,0,0, - 3201,3204,3205,3206,3208,3218,3226,3228,3232,3235,3236,3241,3242,3245,3250, - 3253,3257,3258,3259,3261,3262,3268,3270,3300,3304,3305,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3585, - 3719,3721,3722,3723,3724,3725,3727,3731,3733,3734,3735,3736,3739,3741,3742, - 3749,3750,3752,3758,3759,3764,3766,3767,3772,3775,3781,3815,3823,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,4105,4238,4240,4241,4244,4255,4267,4302,4311,4321,4332,4333,[711,719,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[746,747,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[1216,1217, - 1224,1225,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0], - [1226,1229,1234,1237,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0],[1242,1243,1262,1264,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0],[1266,1267,1279,0,0,0,1739,1740,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0],[1747,1748,1750,1757,1758,1759,1777,1780,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[1781,1782,1783,1784,1786, - 1787,1788,1789,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[1790,0, - 2050,2051,2052,2053,2054,2055,2056,2059,2060,2062,2063,2064,2065,2066,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0],[2067,2068,2069,2071,2072,2073,2074,2075, - 2076,2077,2078,2079,2175,2268,2297,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,3082,3085,3094,3328,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0, - 0,0,0,0,0]]]]; -exports.encode = - [[13,8184],[23,8388568],[28,268435426],[28,268435427],[28,268435428],[28, - 268435429],[28,268435430],[28,268435431],[28,268435432],[24,16777194],[30, - 1073741820],[28,268435433],[28,268435434],[30,1073741821],[28,268435435], - [28,268435436],[28,268435437],[28,268435438],[28,268435439],[28,268435440], - [28,268435441],[28,268435442],[30,1073741822],[28,268435443],[28, - 268435444],[28,268435445],[28,268435446],[28,268435447],[28,268435448],[28, - 268435449],[28,268435450],[28,268435451],[6,20],[10,1016],[10,1017],[12, - 4090],[13,8185],[6,21],[8,248],[11,2042],[10,1018],[10,1019],[8,249],[11, - 2043],[8,250],[6,22],[6,23],[6,24],[5,0],[5,1],[5,2],[6,25],[6,26],[6,27], - [6,28],[6,29],[6,30],[6,31],[7,92],[8,251],[15,32764],[6,32],[12,4091],[10, - 1020],[13,8186],[6,33],[7,93],[7,94],[7,95],[7,96],[7,97],[7,98],[7,99],[7, - 100],[7,101],[7,102],[7,103],[7,104],[7,105],[7,106],[7,107],[7,108],[7, - 109],[7,110],[7,111],[7,112],[7,113],[7,114],[8,252],[7,115],[8,253],[13, - 8187],[19,524272],[13,8188],[14,16380],[6,34],[15,32765],[5,3],[6,35],[5, - 4],[6,36],[5,5],[6,37],[6,38],[6,39],[5,6],[7,116],[7,117],[6,40],[6,41], - [6,42],[5,7],[6,43],[7,118],[6,44],[5,8],[5,9],[6,45],[7,119],[7,120],[7, - 121],[7,122],[7,123],[15,32766],[11,2044],[14,16381],[13,8189],[28, - 268435452],[20,1048550],[22,4194258],[20,1048551],[20,1048552],[22, - 4194259],[22,4194260],[22,4194261],[23,8388569],[22,4194262],[23,8388570], - [23,8388571],[23,8388572],[23,8388573],[23,8388574],[24,16777195],[23, - 8388575],[24,16777196],[24,16777197],[22,4194263],[23,8388576],[24, - 16777198],[23,8388577],[23,8388578],[23,8388579],[23,8388580],[21,2097116], - [22,4194264],[23,8388581],[22,4194265],[23,8388582],[23,8388583],[24, - 16777199],[22,4194266],[21,2097117],[20,1048553],[22,4194267],[22,4194268], - [23,8388584],[23,8388585],[21,2097118],[23,8388586],[22,4194269],[22, - 4194270],[24,16777200],[21,2097119],[22,4194271],[23,8388587],[23,8388588], - [21,2097120],[21,2097121],[22,4194272],[21,2097122],[23,8388589],[22, - 4194273],[23,8388590],[23,8388591],[20,1048554],[22,4194274],[22,4194275], - [22,4194276],[23,8388592],[22,4194277],[22,4194278],[23,8388593],[26, - 67108832],[26,67108833],[20,1048555],[19,524273],[22,4194279],[23,8388594], - [22,4194280],[25,33554412],[26,67108834],[26,67108835],[26,67108836],[27, - 134217694],[27,134217695],[26,67108837],[24,16777201],[25,33554413],[19, - 524274],[21,2097123],[26,67108838],[27,134217696],[27,134217697],[26, - 67108839],[27,134217698],[24,16777202],[21,2097124],[21,2097125],[26, - 67108840],[26,67108841],[28,268435453],[27,134217699],[27,134217700],[27, - 134217701],[20,1048556],[24,16777203],[20,1048557],[21,2097126],[22, - 4194281],[21,2097127],[21,2097128],[23,8388595],[22,4194282],[22,4194283], - [25,33554414],[25,33554415],[24,16777204],[24,16777205],[26,67108842],[23, - 8388596],[26,67108843],[27,134217702],[26,67108844],[26,67108845],[27, - 134217703],[27,134217704],[27,134217705],[27,134217706],[27,134217707],[28, - 268435454],[27,134217708],[27,134217709],[27,134217710],[27,134217711],[27, - 134217712],[26,67108846],[30,1073741823]]; - -},{}],196:[function(require,module,exports){ -exports.table = [ - { - "name": ":authority", - "value": "", - "nameSize": 10, - "totalSize": 42 - }, - { - "name": ":method", - "value": "GET", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": ":method", - "value": "POST", - "nameSize": 7, - "totalSize": 43 - }, - { - "name": ":path", - "value": "/", - "nameSize": 5, - "totalSize": 38 - }, - { - "name": ":path", - "value": "/index.html", - "nameSize": 5, - "totalSize": 48 - }, - { - "name": ":scheme", - "value": "http", - "nameSize": 7, - "totalSize": 43 - }, - { - "name": ":scheme", - "value": "https", - "nameSize": 7, - "totalSize": 44 - }, - { - "name": ":status", - "value": "200", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": ":status", - "value": "204", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": ":status", - "value": "206", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": ":status", - "value": "304", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": ":status", - "value": "400", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": ":status", - "value": "404", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": ":status", - "value": "500", - "nameSize": 7, - "totalSize": 42 - }, - { - "name": "accept-charset", - "value": "", - "nameSize": 14, - "totalSize": 46 - }, - { - "name": "accept-encoding", - "value": "gzip, deflate", - "nameSize": 15, - "totalSize": 60 - }, - { - "name": "accept-language", - "value": "", - "nameSize": 15, - "totalSize": 47 - }, - { - "name": "accept-ranges", - "value": "", - "nameSize": 13, - "totalSize": 45 - }, - { - "name": "accept", - "value": "", - "nameSize": 6, - "totalSize": 38 - }, - { - "name": "access-control-allow-origin", - "value": "", - "nameSize": 27, - "totalSize": 59 - }, - { - "name": "age", - "value": "", - "nameSize": 3, - "totalSize": 35 - }, - { - "name": "allow", - "value": "", - "nameSize": 5, - "totalSize": 37 - }, - { - "name": "authorization", - "value": "", - "nameSize": 13, - "totalSize": 45 - }, - { - "name": "cache-control", - "value": "", - "nameSize": 13, - "totalSize": 45 - }, - { - "name": "content-disposition", - "value": "", - "nameSize": 19, - "totalSize": 51 - }, - { - "name": "content-encoding", - "value": "", - "nameSize": 16, - "totalSize": 48 - }, - { - "name": "content-language", - "value": "", - "nameSize": 16, - "totalSize": 48 - }, - { - "name": "content-length", - "value": "", - "nameSize": 14, - "totalSize": 46 - }, - { - "name": "content-location", - "value": "", - "nameSize": 16, - "totalSize": 48 - }, - { - "name": "content-range", - "value": "", - "nameSize": 13, - "totalSize": 45 - }, - { - "name": "content-type", - "value": "", - "nameSize": 12, - "totalSize": 44 - }, - { - "name": "cookie", - "value": "", - "nameSize": 6, - "totalSize": 38 - }, - { - "name": "date", - "value": "", - "nameSize": 4, - "totalSize": 36 - }, - { - "name": "etag", - "value": "", - "nameSize": 4, - "totalSize": 36 - }, - { - "name": "expect", - "value": "", - "nameSize": 6, - "totalSize": 38 - }, - { - "name": "expires", - "value": "", - "nameSize": 7, - "totalSize": 39 - }, - { - "name": "from", - "value": "", - "nameSize": 4, - "totalSize": 36 - }, - { - "name": "host", - "value": "", - "nameSize": 4, - "totalSize": 36 - }, - { - "name": "if-match", - "value": "", - "nameSize": 8, - "totalSize": 40 - }, - { - "name": "if-modified-since", - "value": "", - "nameSize": 17, - "totalSize": 49 - }, - { - "name": "if-none-match", - "value": "", - "nameSize": 13, - "totalSize": 45 - }, - { - "name": "if-range", - "value": "", - "nameSize": 8, - "totalSize": 40 - }, - { - "name": "if-unmodified-since", - "value": "", - "nameSize": 19, - "totalSize": 51 - }, - { - "name": "last-modified", - "value": "", - "nameSize": 13, - "totalSize": 45 - }, - { - "name": "link", - "value": "", - "nameSize": 4, - "totalSize": 36 - }, - { - "name": "location", - "value": "", - "nameSize": 8, - "totalSize": 40 - }, - { - "name": "max-forwards", - "value": "", - "nameSize": 12, - "totalSize": 44 - }, - { - "name": "proxy-authenticate", - "value": "", - "nameSize": 18, - "totalSize": 50 - }, - { - "name": "proxy-authorization", - "value": "", - "nameSize": 19, - "totalSize": 51 - }, - { - "name": "range", - "value": "", - "nameSize": 5, - "totalSize": 37 - }, - { - "name": "referer", - "value": "", - "nameSize": 7, - "totalSize": 39 - }, - { - "name": "refresh", - "value": "", - "nameSize": 7, - "totalSize": 39 - }, - { - "name": "retry-after", - "value": "", - "nameSize": 11, - "totalSize": 43 - }, - { - "name": "server", - "value": "", - "nameSize": 6, - "totalSize": 38 - }, - { - "name": "set-cookie", - "value": "", - "nameSize": 10, - "totalSize": 42 - }, - { - "name": "strict-transport-security", - "value": "", - "nameSize": 25, - "totalSize": 57 - }, - { - "name": "transfer-encoding", - "value": "", - "nameSize": 17, - "totalSize": 49 - }, - { - "name": "user-agent", - "value": "", - "nameSize": 10, - "totalSize": 42 - }, - { - "name": "vary", - "value": "", - "nameSize": 4, - "totalSize": 36 - }, - { - "name": "via", - "value": "", - "nameSize": 3, - "totalSize": 35 - }, - { - "name": "www-authenticate", - "value": "", - "nameSize": 16, - "totalSize": 48 - } -]; -exports.map = { - ":authority": { - "index": 1, - "values": { - "": 1 - } - }, - ":method": { - "index": 2, - "values": { - "GET": 2, - "POST": 3 - } - }, - ":path": { - "index": 4, - "values": { - "/": 4, - "/index.html": 5 - } - }, - ":scheme": { - "index": 6, - "values": { - "http": 6, - "https": 7 - } - }, - ":status": { - "index": 8, - "values": { - "200": 8, - "204": 9, - "206": 10, - "304": 11, - "400": 12, - "404": 13, - "500": 14 - } - }, - "accept-charset": { - "index": 15, - "values": { - "": 15 - } - }, - "accept-encoding": { - "index": 16, - "values": { - "gzip, deflate": 16 - } - }, - "accept-language": { - "index": 17, - "values": { - "": 17 - } - }, - "accept-ranges": { - "index": 18, - "values": { - "": 18 - } - }, - "accept": { - "index": 19, - "values": { - "": 19 - } - }, - "access-control-allow-origin": { - "index": 20, - "values": { - "": 20 - } - }, - "age": { - "index": 21, - "values": { - "": 21 - } - }, - "allow": { - "index": 22, - "values": { - "": 22 - } - }, - "authorization": { - "index": 23, - "values": { - "": 23 - } - }, - "cache-control": { - "index": 24, - "values": { - "": 24 - } - }, - "content-disposition": { - "index": 25, - "values": { - "": 25 - } - }, - "content-encoding": { - "index": 26, - "values": { - "": 26 - } - }, - "content-language": { - "index": 27, - "values": { - "": 27 - } - }, - "content-length": { - "index": 28, - "values": { - "": 28 - } - }, - "content-location": { - "index": 29, - "values": { - "": 29 - } - }, - "content-range": { - "index": 30, - "values": { - "": 30 - } - }, - "content-type": { - "index": 31, - "values": { - "": 31 - } - }, - "cookie": { - "index": 32, - "values": { - "": 32 - } - }, - "date": { - "index": 33, - "values": { - "": 33 - } - }, - "etag": { - "index": 34, - "values": { - "": 34 - } - }, - "expect": { - "index": 35, - "values": { - "": 35 - } - }, - "expires": { - "index": 36, - "values": { - "": 36 - } - }, - "from": { - "index": 37, - "values": { - "": 37 - } - }, - "host": { - "index": 38, - "values": { - "": 38 - } - }, - "if-match": { - "index": 39, - "values": { - "": 39 - } - }, - "if-modified-since": { - "index": 40, - "values": { - "": 40 - } - }, - "if-none-match": { - "index": 41, - "values": { - "": 41 - } - }, - "if-range": { - "index": 42, - "values": { - "": 42 - } - }, - "if-unmodified-since": { - "index": 43, - "values": { - "": 43 - } - }, - "last-modified": { - "index": 44, - "values": { - "": 44 - } - }, - "link": { - "index": 45, - "values": { - "": 45 - } - }, - "location": { - "index": 46, - "values": { - "": 46 - } - }, - "max-forwards": { - "index": 47, - "values": { - "": 47 - } - }, - "proxy-authenticate": { - "index": 48, - "values": { - "": 48 - } - }, - "proxy-authorization": { - "index": 49, - "values": { - "": 49 - } - }, - "range": { - "index": 50, - "values": { - "": 50 - } - }, - "referer": { - "index": 51, - "values": { - "": 51 - } - }, - "refresh": { - "index": 52, - "values": { - "": 52 - } - }, - "retry-after": { - "index": 53, - "values": { - "": 53 - } - }, - "server": { - "index": 54, - "values": { - "": 54 - } - }, - "set-cookie": { - "index": 55, - "values": { - "": 55 - } - }, - "strict-transport-security": { - "index": 56, - "values": { - "": 56 - } - }, - "transfer-encoding": { - "index": 57, - "values": { - "": 57 - } - }, - "user-agent": { - "index": 58, - "values": { - "": 58 - } - }, - "vary": { - "index": 59, - "values": { - "": 59 - } - }, - "via": { - "index": 60, - "values": { - "": 60 - } - }, - "www-authenticate": { - "index": 61, - "values": { - "": 61 - } - } -}; - -},{}],197:[function(require,module,exports){ -var hpack = require('../hpack'); -var utils = hpack.utils; -var assert = utils.assert; - -function Table(options) { - this['static'] = hpack['static-table']; - this.dynamic = []; - this.size = 0; - this.maxSize = 0; - this.length = this['static'].table.length; - this.protocolMaxSize = options.maxSize; - this.maxSize = this.protocolMaxSize; - this.lookupDepth = options.lookupDepth || 32; -} -module.exports = Table; - -Table.create = function create(options) { - return new Table(options); -}; - -Table.prototype.lookup = function lookup(index) { - assert(index !== 0, 'Zero indexed field'); - assert(index <= this.length, 'Indexed field OOB') - - if (index <= this['static'].table.length) - return this['static'].table[index - 1]; - else - return this.dynamic[this.length - index]; -}; - -Table.prototype.reverseLookup = function reverseLookup(name, value) { - var staticEntry = this['static'].map[name]; - if (staticEntry && staticEntry.values[value]) - return staticEntry.values[value]; - - // Reverse search dynamic table (new items are at the end of it) - var limit = Math.max(0, this.dynamic.length - this.lookupDepth); - for (var i = this.dynamic.length - 1; i >= limit; i--) { - var entry = this.dynamic[i]; - if (entry.name === name && entry.value === value) - return this.length - i; - - if (entry.name === name) { - // Prefer smaller index - if (staticEntry) - break; - return -(this.length - i); - } - } - - if (staticEntry) - return -staticEntry.index; - - return 0; -}; - -Table.prototype.add = function add(name, value, nameSize, valueSize) { - var totalSize = nameSize + valueSize + 32; - - this.dynamic.push({ - name: name, - value: value, - nameSize: nameSize, - totalSize: totalSize - }); - this.size += totalSize; - this.length++; - - this.evict(); -}; - -Table.prototype.evict = function evict() { - while (this.size > this.maxSize) { - var entry = this.dynamic.shift(); - this.size -= entry.totalSize; - this.length--; - } - assert(this.size >= 0, 'Table size sanity check failed'); -}; - -Table.prototype.updateSize = function updateSize(size) { - assert(size <= this.protocolMaxSize, 'Table size bigger than maximum'); - this.maxSize = size; - this.evict(); -}; - -},{"../hpack":190}],198:[function(require,module,exports){ -exports.assert = function assert(cond, text) { - if (!cond) - throw new Error(text); -}; - -exports.stringify = function stringify(arr) { - var res = ''; - for (var i = 0; i < arr.length; i++) - res += String.fromCharCode(arr[i]); - return res; -}; - -exports.toArray = function toArray(str) { - var res = []; - for (var i = 0; i < str.length; i++) { - var c = str.charCodeAt(i); - var hi = c >>> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - return res; -}; - -},{}],199:[function(require,module,exports){ -arguments[4][134][0].apply(exports,arguments) -},{"./_stream_readable":201,"./_stream_writable":203,"core-util-is":99,"dup":134,"inherits":216,"process-nextick-args":568}],200:[function(require,module,exports){ -arguments[4][135][0].apply(exports,arguments) -},{"./_stream_transform":202,"core-util-is":99,"dup":135,"inherits":216}],201:[function(require,module,exports){ -arguments[4][136][0].apply(exports,arguments) -},{"./_stream_duplex":199,"./internal/streams/BufferList":204,"./internal/streams/destroy":205,"./internal/streams/stream":206,"_process":1009,"core-util-is":99,"dup":136,"events":989,"inherits":216,"isarray":342,"process-nextick-args":568,"safe-buffer":656,"string_decoder/":715,"util":984}],202:[function(require,module,exports){ -arguments[4][137][0].apply(exports,arguments) -},{"./_stream_duplex":199,"core-util-is":99,"dup":137,"inherits":216}],203:[function(require,module,exports){ -arguments[4][138][0].apply(exports,arguments) -},{"./_stream_duplex":199,"./internal/streams/destroy":205,"./internal/streams/stream":206,"_process":1009,"core-util-is":99,"dup":138,"inherits":216,"process-nextick-args":568,"safe-buffer":656,"util-deprecate":720}],204:[function(require,module,exports){ -arguments[4][139][0].apply(exports,arguments) -},{"dup":139,"safe-buffer":656}],205:[function(require,module,exports){ -arguments[4][140][0].apply(exports,arguments) -},{"dup":140,"process-nextick-args":568}],206:[function(require,module,exports){ -arguments[4][141][0].apply(exports,arguments) -},{"dup":141,"events":989}],207:[function(require,module,exports){ -arguments[4][142][0].apply(exports,arguments) -},{"./lib/_stream_duplex.js":199,"./lib/_stream_passthrough.js":200,"./lib/_stream_readable.js":201,"./lib/_stream_transform.js":202,"./lib/_stream_writable.js":203,"dup":142}],208:[function(require,module,exports){ -/** - * Copyright (c) 2016 Tim Kuijsten - * - * Permission to use, copy, modify, and/or distribute this software for any - * purpose with or without fee is hereby granted, provided that the above - * copyright notice and this permission notice appear in all copies. - * - * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES - * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF - * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR - * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES - * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN - * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF - * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. - */ - -'use strict' - -var stream = require('stream') - -var xtend = require('xtend') - -/** - * Iterate over an IndexedDB object store with a readable stream. - * - * @param {IDBDatabase} db - IndexedDB instance - * @param {String} storeName - name of the object store to iterate over - * @param {Object} [opts] - * - * Options: - * @param {IDBKeyRange} opts.range - a valid IndexedDB key range - * @param {IDBCursorDirection} opts.direction - one of "next", "nextunique", - * "prev", "prevunique" - * @param {Boolean} opts.snapshot=false - Iterate over a snapshot of the database - * by opening only one cursor. This disables any form of back pressure to prevent - * cursor timeout issues. - */ -function idbReadableStream(db, storeName, opts) { - if (typeof db !== 'object') throw new TypeError('db must be an object') - if (typeof storeName !== 'string') throw new TypeError('storeName must be a string') - if (opts == null) opts = {} - if (typeof opts !== 'object') throw new TypeError('opts must be an object') - - // use transform stream for buffering and back pressure - var transformer = new stream.Transform(xtend(opts, { - objectMode: true, - transform: function(obj, enc, cb) { - cb(null, obj) - } - })) - - opts = xtend({ - snapshot: false - }, opts) - - var lastIteratedKey = null - transformer._cursorsOpened = 0 - - function startCursor() { - var lower, upper, lowerOpen, upperOpen - - var direction = opts.direction || 'next' - var range = opts.range || {} - - lower = range.lower - upper = range.upper - lowerOpen = !!range.lowerOpen - upperOpen = !!range.upperOpen - - // if this is not the first iteration, use lastIteratedKey - if (lastIteratedKey) { - if (direction === 'next') { - lowerOpen = true // exclude the last iterated key itself - lower = lastIteratedKey - } else { - upperOpen = true // exclude the last iterated key itself - upper = lastIteratedKey - } - } - - var keyRange - if (lower && upper) - keyRange = IDBKeyRange.bound(lower, upper, lowerOpen, upperOpen) - else if (lower) - keyRange = IDBKeyRange.lowerBound(lower, lowerOpen) - else if (upper) - keyRange = IDBKeyRange.upperBound(upper, upperOpen) - - var tx = db.transaction(storeName, 'readonly') - var store = tx.objectStore(storeName) - - transformer._cursorsOpened++ - var req = store.openCursor(keyRange, opts.direction) - - function proceed(cursor) { - try { - cursor.continue() // throws a TransactionInactiveError if the cursor timed out - } catch(err) { - // either reopen a cursor or propagate the error - if (err.name === 'TransactionInactiveError' && !opts.snapshot) - startCursor() // IndexedDB timed out the cursor - else - transformer.emit('error', err) - } - } - - req.onsuccess = function() { - var cursor = req.result - if (cursor) { - lastIteratedKey = cursor.key - - var go = transformer.write({ key: cursor.key, value: cursor.value }) - if (opts.snapshot || go) - proceed(cursor) - else - transformer.once('drain', function() { - proceed(cursor) - }) - } else - transformer.end() - } - - tx.onabort = function() { - transformer.emit('error', tx.error) - } - tx.onerror = function() { - transformer.emit('error', tx.error) - } - } - - startCursor() - - return transformer -} - -module.exports = idbReadableStream - -},{"stream":1028,"xtend":732}],209:[function(require,module,exports){ -exports.read = function (buffer, offset, isLE, mLen, nBytes) { - var e, m - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var nBits = -7 - var i = isLE ? (nBytes - 1) : 0 - var d = isLE ? -1 : 1 - var s = buffer[offset + i] - - i += d - - e = s & ((1 << (-nBits)) - 1) - s >>= (-nBits) - nBits += eLen - for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - m = e & ((1 << (-nBits)) - 1) - e >>= (-nBits) - nBits += mLen - for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} - - if (e === 0) { - e = 1 - eBias - } else if (e === eMax) { - return m ? NaN : ((s ? -1 : 1) * Infinity) - } else { - m = m + Math.pow(2, mLen) - e = e - eBias - } - return (s ? -1 : 1) * m * Math.pow(2, e - mLen) -} - -exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { - var e, m, c - var eLen = nBytes * 8 - mLen - 1 - var eMax = (1 << eLen) - 1 - var eBias = eMax >> 1 - var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) - var i = isLE ? 0 : (nBytes - 1) - var d = isLE ? 1 : -1 - var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 - - value = Math.abs(value) - - if (isNaN(value) || value === Infinity) { - m = isNaN(value) ? 1 : 0 - e = eMax - } else { - e = Math.floor(Math.log(value) / Math.LN2) - if (value * (c = Math.pow(2, -e)) < 1) { - e-- - c *= 2 - } - if (e + eBias >= 1) { - value += rt / c - } else { - value += rt * Math.pow(2, 1 - eBias) - } - if (value * c >= 2) { - e++ - c /= 2 - } - - if (e + eBias >= eMax) { - m = 0 - e = eMax - } else if (e + eBias >= 1) { - m = (value * c - 1) * Math.pow(2, mLen) - e = e + eBias - } else { - m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) - e = 0 - } - } - - for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} - - e = (e << mLen) | m - eLen += mLen - for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} - - buffer[offset + i - d] |= s * 128 -} - -},{}],210:[function(require,module,exports){ -'use strict'; -var types = [ - require('./nextTick'), - require('./mutation.js'), - require('./messageChannel'), - require('./stateChange'), - require('./timeout') -]; -var draining; -var currentQueue; -var queueIndex = -1; -var queue = []; -var scheduled = false; -function cleanUpNextTick() { - if (!draining || !currentQueue) { - return; - } - draining = false; - if (currentQueue.length) { - queue = currentQueue.concat(queue); - } else { - queueIndex = -1; - } - if (queue.length) { - nextTick(); - } -} - -//named nextTick for less confusing stack traces -function nextTick() { - if (draining) { - return; - } - scheduled = false; - draining = true; - var len = queue.length; - var timeout = setTimeout(cleanUpNextTick); - while (len) { - currentQueue = queue; - queue = []; - while (currentQueue && ++queueIndex < len) { - currentQueue[queueIndex].run(); - } - queueIndex = -1; - len = queue.length; - } - currentQueue = null; - queueIndex = -1; - draining = false; - clearTimeout(timeout); -} -var scheduleDrain; -var i = -1; -var len = types.length; -while (++i < len) { - if (types[i] && types[i].test && types[i].test()) { - scheduleDrain = types[i].install(nextTick); - break; - } -} -// v8 likes predictible objects -function Item(fun, array) { - this.fun = fun; - this.array = array; -} -Item.prototype.run = function () { - var fun = this.fun; - var array = this.array; - switch (array.length) { - case 0: - return fun(); - case 1: - return fun(array[0]); - case 2: - return fun(array[0], array[1]); - case 3: - return fun(array[0], array[1], array[2]); - default: - return fun.apply(null, array); - } - -}; -module.exports = immediate; -function immediate(task) { - 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(task, args)); - if (!scheduled && !draining) { - scheduled = true; - scheduleDrain(); - } -} - -},{"./messageChannel":211,"./mutation.js":212,"./nextTick":213,"./stateChange":214,"./timeout":215}],211:[function(require,module,exports){ -(function (global){ -'use strict'; - -exports.test = function () { - if (global.setImmediate) { - // we can only get here in IE10 - // which doesn't handel postMessage well - return false; - } - return typeof global.MessageChannel !== 'undefined'; -}; - -exports.install = function (func) { - var channel = new global.MessageChannel(); - channel.port1.onmessage = func; - return function () { - channel.port2.postMessage(0); - }; -}; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],212:[function(require,module,exports){ -(function (global){ -'use strict'; -//based off rsvp https://github.com/tildeio/rsvp.js -//license https://github.com/tildeio/rsvp.js/blob/master/LICENSE -//https://github.com/tildeio/rsvp.js/blob/master/lib/rsvp/asap.js - -var Mutation = global.MutationObserver || global.WebKitMutationObserver; - -exports.test = function () { - return Mutation; -}; - -exports.install = function (handle) { - var called = 0; - var observer = new Mutation(handle); - var element = global.document.createTextNode(''); - observer.observe(element, { - characterData: true - }); - return function () { - element.data = (called = ++called % 2); - }; -}; -}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) -},{}],213:[function(require,module,exports){ -(function (process){ -'use strict'; -exports.test = function () { - // Don't get fooled by e.g. browserify environments. - return (typeof process !== 'undefined') && !process.browser; -}; - -exports.install = function (func) { - return function () { - process.nextTick(func); - }; -}; - -}).call(this,require('_process')) -},{"_process":1009}],214:[function(require,module,exports){ -(function (global){ -'use strict'; - -exports.test = function () { - return 'document' in global && 'onreadystatechange' in global.document.createElement('script'); -}; - -exports.install = function (handle) { - return function () { - - // Create a