diff --git a/dist/scatter.cjs.js b/dist/scatter.cjs.js
index 9938cf94..8a409b87 100644
--- a/dist/scatter.cjs.js
+++ b/dist/scatter.cjs.js
@@ -5,11 +5,6 @@ function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'defau
var io = _interopDefault(require('socket.io-client'));
var getRandomValues = _interopDefault(require('get-random-values'));
var Eos = _interopDefault(require('eosjs'));
-var ProviderEngine = _interopDefault(require('web3-provider-engine'));
-var RpcSubprovider = _interopDefault(require('web3-provider-engine/subproviders/rpc'));
-var WebsocketSubprovider = _interopDefault(require('web3-provider-engine/subproviders/websocket'));
-var HookedWalletSubprovider = _interopDefault(require('web3-provider-engine/subproviders/hooked-wallet'));
-var ethUtil = _interopDefault(require('ethereumjs-util'));
require('isomorphic-fetch');
let storage = {};
@@ -55,7 +50,7 @@ class StorageService {
const {ecc} = Eos.modules;
-const host = 'http://127.0.0.1:50005';
+const host = 'ws://127.0.0.1:50005/socket.io/?EIO=3&transport=websocket';
let socket = null;
let connected = false;
@@ -67,7 +62,7 @@ let openRequests = [];
let allowReconnects = true;
let reconnectionTimeout = null;
-const reconnectOnAbnormalDisconnection = async () => {
+const reconnectOnAbnormalDisconnection = () => {
if(!allowReconnects) return;
clearTimeout(reconnectionTimeout);
@@ -114,10 +109,10 @@ class SocketService {
this.timeout = timeout;
}
- static async link(){
+ static link(){
return Promise.race([
- new Promise((resolve, reject) => setTimeout(async () => {
+ new Promise((resolve, reject) => setTimeout(() => {
if(connected) return;
resolve(false);
@@ -128,17 +123,18 @@ class SocketService {
reconnectOnAbnormalDisconnection();
}, this.timeout)),
- new Promise(async (resolve, reject) => {
+ new Promise((resolve, reject) => {
socket = io.connect(`${host}/scatter`, { secure:true, reconnection: false, rejectUnauthorized : false });
- socket.on('connected', async () => {
+ socket.on('connected', () => {
clearTimeout(reconnectionTimeout);
connected = true;
- await pair(true);
- resolve(true);
+ pair(true).then(() => {
+ resolve(true);
+ });
});
- socket.on('paired', async result => {
+ socket.on('paired', result => {
paired = result;
if(paired) {
@@ -154,7 +150,7 @@ class SocketService {
pairingPromise.resolve(result);
});
- socket.on('rekey', async () => {
+ socket.on('rekey', () => {
appkey = 'appkey:'+random();
socket.emit('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin});
});
@@ -172,7 +168,7 @@ class SocketService {
else openRequest.resolve(result.result);
});
- socket.on('disconnect', async () => {
+ socket.on('disconnect', () => {
console.log('Disconnected');
connected = false;
socket = null;
@@ -181,12 +177,12 @@ class SocketService {
reconnectOnAbnormalDisconnection();
});
- socket.on('connect_error', async () => {
+ socket.on('connect_error', () => {
allowReconnects = false;
resolve(false);
});
- socket.on('rejected', async reason => {
+ socket.on('rejected', reason => {
console.error('reason', reason);
reject(reason);
});
@@ -198,37 +194,38 @@ class SocketService {
return connected;
}
- static async disconnect(){
+ static disconnect(){
socket.disconnect();
return true;
}
- static async sendApiRequest(request){
- return new Promise(async (resolve, reject) => {
+ static sendApiRequest(request){
+ return new Promise((resolve, reject) => {
if(request.type === 'identityFromPermissions' && !paired) return resolve(false);
- await pair();
- if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'});
+ pair().then(() => {
+ if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'});
- // Request ID used for resolving promises
- request.id = random();
+ // Request ID used for resolving promises
+ request.id = random();
- // Set Application Key
- request.appkey = appkey;
+ // Set Application Key
+ request.appkey = appkey;
- // Nonce used to authenticate this request
- request.nonce = StorageService.getNonce() || 0;
- // Next nonce used to authenticate the next request
- const nextNonce = random();
- request.nextNonce = ecc.sha256(nextNonce);
- StorageService.setNonce(nextNonce);
+ // Nonce used to authenticate this request
+ request.nonce = StorageService.getNonce() || 0;
+ // Next nonce used to authenticate the next request
+ const nextNonce = random();
+ request.nextNonce = ecc.sha256(nextNonce);
+ StorageService.setNonce(nextNonce);
- if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin'))
- request.payload.origin = getOrigin();
+ if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin'))
+ request.payload.origin = getOrigin();
- openRequests.push(Object.assign(request, {resolve, reject}));
- socket.emit('api', {data:request, plugin});
+ openRequests.push(Object.assign(request, {resolve, reject}));
+ socket.emit('api', {data:request, plugin});
+ });
});
}
@@ -390,87 +387,7 @@ class EOS extends Plugin {
}
}
-let ethNetwork;
-
-class ETH extends Plugin {
-
- constructor(){
- super(Blockchains.ETH, BLOCKCHAIN_SUPPORT);
- }
-
- signatureProvider(...args){
-
- return (_network, _web3) => {
- ethNetwork = Network.fromJson(_network);
- if(!ethNetwork.isValid()) throw Error.noNetwork();
-
- const rpcUrl = `${ethNetwork.protocol}://${ethNetwork.hostport()}`;
-
- const engine = new ProviderEngine();
- const web3 = new _web3(engine);
-
- const walletSubprovider = new HookedWalletSubprovider(new ScatterEthereumWallet());
- engine.addProvider(walletSubprovider);
-
- if(ethNetwork.protocol.indexOf('http') > -1) engine.addProvider(new RpcSubprovider({rpcUrl}));
- else engine.addProvider(new WebsocketSubprovider({rpcUrl}));
-
- engine.start();
-
- return web3;
- }
- }
-}
-
-
-
-class ScatterEthereumWallet {
- constructor(){
- this.getAccounts = this.getAccounts.bind(this);
- this.signTransaction = this.signTransaction.bind(this);
- }
-
- async getAccounts(callback) {
- const result = await SocketService.sendApiRequest({
- type:'identityFromPermissions',
- payload:{}
- });
- const accounts = !result ? [] : result.accounts
- .filter(account => account.blockchain === Blockchains.ETH)
- .map(account => account.address);
-
- callback(null, accounts);
- return accounts;
- }
-
- async signTransaction(transaction){
- if(!ethNetwork) throw Error.noNetwork();
-
- // Basic settings
- if (transaction.gas !== undefined) transaction.gasLimit = transaction.gas;
- transaction.value = transaction.value || '0x00';
- if(transaction.hasOwnProperty('data')) transaction.data = ethUtil.addHexPrefix(transaction.data);
-
- // Required Fields
- const requiredFields = transaction.hasOwnProperty('requiredFields') ? transaction.requiredFields : {};
-
- // Contract ABI
- const abi = transaction.hasOwnProperty('abi') ? transaction.abi : null;
- if(!abi && transaction.hasOwnProperty('data'))
- throw Error.signatureError('no_abi', 'You must provide a JSON ABI along with your transaction so that users can read the contract');
-
- const payload = Object.assign(transaction, { blockchain:Blockchains.ETH, network:ethNetwork, requiredFields });
- const {signatures, returnedFields} = await SocketService.sendApiRequest({
- type:'requestSignature',
- payload
- });
-
- if(transaction.hasOwnProperty('fieldsCallback'))
- transaction.fieldsCallback(returnedFields);
-
- return signatures[0];
- }
-}
+// import ETH from './defaults/eth';
/***
* Setting up for plugin based generators,
@@ -486,7 +403,7 @@ class PluginRepositorySingleton {
loadPlugins(){
this.plugins.push(new EOS());
- this.plugins.push(new ETH());
+ // this.plugins.push(new ETH());
}
signatureProviders(){
@@ -649,6 +566,22 @@ class Scatter {
});
}
+ getPublicKey(blockchain){
+ throwNoAuth();
+ return SocketService.sendApiRequest({
+ type:'getPublicKey',
+ payload:{ blockchain }
+ });
+ }
+
+ linkAccount(publicKey, account, network){
+ throwNoAuth();
+ return SocketService.sendApiRequest({
+ type:'linkAccount',
+ payload:{ publicKey, account, network }
+ });
+ }
+
suggestNetwork(network){
throwNoAuth();
return SocketService.sendApiRequest({
diff --git a/dist/scatter.esm.js b/dist/scatter.esm.js
index f846f227..a2a1354d 100644
--- a/dist/scatter.esm.js
+++ b/dist/scatter.esm.js
@@ -1,11 +1,6 @@
import io from 'socket.io-client';
import getRandomValues from 'get-random-values';
import Eos from 'eosjs';
-import ProviderEngine from 'web3-provider-engine';
-import RpcSubprovider from 'web3-provider-engine/subproviders/rpc';
-import WebsocketSubprovider from 'web3-provider-engine/subproviders/websocket';
-import HookedWalletSubprovider from 'web3-provider-engine/subproviders/hooked-wallet';
-import ethUtil from 'ethereumjs-util';
import 'isomorphic-fetch';
let storage = {};
@@ -51,7 +46,7 @@ class StorageService {
const {ecc} = Eos.modules;
-const host = 'http://127.0.0.1:50005';
+const host = 'ws://127.0.0.1:50005/socket.io/?EIO=3&transport=websocket';
let socket = null;
let connected = false;
@@ -63,7 +58,7 @@ let openRequests = [];
let allowReconnects = true;
let reconnectionTimeout = null;
-const reconnectOnAbnormalDisconnection = async () => {
+const reconnectOnAbnormalDisconnection = () => {
if(!allowReconnects) return;
clearTimeout(reconnectionTimeout);
@@ -110,10 +105,10 @@ class SocketService {
this.timeout = timeout;
}
- static async link(){
+ static link(){
return Promise.race([
- new Promise((resolve, reject) => setTimeout(async () => {
+ new Promise((resolve, reject) => setTimeout(() => {
if(connected) return;
resolve(false);
@@ -124,17 +119,18 @@ class SocketService {
reconnectOnAbnormalDisconnection();
}, this.timeout)),
- new Promise(async (resolve, reject) => {
+ new Promise((resolve, reject) => {
socket = io.connect(`${host}/scatter`, { secure:true, reconnection: false, rejectUnauthorized : false });
- socket.on('connected', async () => {
+ socket.on('connected', () => {
clearTimeout(reconnectionTimeout);
connected = true;
- await pair(true);
- resolve(true);
+ pair(true).then(() => {
+ resolve(true);
+ });
});
- socket.on('paired', async result => {
+ socket.on('paired', result => {
paired = result;
if(paired) {
@@ -150,7 +146,7 @@ class SocketService {
pairingPromise.resolve(result);
});
- socket.on('rekey', async () => {
+ socket.on('rekey', () => {
appkey = 'appkey:'+random();
socket.emit('rekeyed', {data:{ appkey, origin:getOrigin() }, plugin});
});
@@ -168,7 +164,7 @@ class SocketService {
else openRequest.resolve(result.result);
});
- socket.on('disconnect', async () => {
+ socket.on('disconnect', () => {
console.log('Disconnected');
connected = false;
socket = null;
@@ -177,12 +173,12 @@ class SocketService {
reconnectOnAbnormalDisconnection();
});
- socket.on('connect_error', async () => {
+ socket.on('connect_error', () => {
allowReconnects = false;
resolve(false);
});
- socket.on('rejected', async reason => {
+ socket.on('rejected', reason => {
console.error('reason', reason);
reject(reason);
});
@@ -194,37 +190,38 @@ class SocketService {
return connected;
}
- static async disconnect(){
+ static disconnect(){
socket.disconnect();
return true;
}
- static async sendApiRequest(request){
- return new Promise(async (resolve, reject) => {
+ static sendApiRequest(request){
+ return new Promise((resolve, reject) => {
if(request.type === 'identityFromPermissions' && !paired) return resolve(false);
- await pair();
- if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'});
+ pair().then(() => {
+ if(!paired) return reject({code:'not_paired', message:'The user did not allow this app to connect to their Scatter'});
- // Request ID used for resolving promises
- request.id = random();
+ // Request ID used for resolving promises
+ request.id = random();
- // Set Application Key
- request.appkey = appkey;
+ // Set Application Key
+ request.appkey = appkey;
- // Nonce used to authenticate this request
- request.nonce = StorageService.getNonce() || 0;
- // Next nonce used to authenticate the next request
- const nextNonce = random();
- request.nextNonce = ecc.sha256(nextNonce);
- StorageService.setNonce(nextNonce);
+ // Nonce used to authenticate this request
+ request.nonce = StorageService.getNonce() || 0;
+ // Next nonce used to authenticate the next request
+ const nextNonce = random();
+ request.nextNonce = ecc.sha256(nextNonce);
+ StorageService.setNonce(nextNonce);
- if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin'))
- request.payload.origin = getOrigin();
+ if(request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin'))
+ request.payload.origin = getOrigin();
- openRequests.push(Object.assign(request, {resolve, reject}));
- socket.emit('api', {data:request, plugin});
+ openRequests.push(Object.assign(request, {resolve, reject}));
+ socket.emit('api', {data:request, plugin});
+ });
});
}
@@ -386,87 +383,7 @@ class EOS extends Plugin {
}
}
-let ethNetwork;
-
-class ETH extends Plugin {
-
- constructor(){
- super(Blockchains.ETH, BLOCKCHAIN_SUPPORT);
- }
-
- signatureProvider(...args){
-
- return (_network, _web3) => {
- ethNetwork = Network.fromJson(_network);
- if(!ethNetwork.isValid()) throw Error.noNetwork();
-
- const rpcUrl = `${ethNetwork.protocol}://${ethNetwork.hostport()}`;
-
- const engine = new ProviderEngine();
- const web3 = new _web3(engine);
-
- const walletSubprovider = new HookedWalletSubprovider(new ScatterEthereumWallet());
- engine.addProvider(walletSubprovider);
-
- if(ethNetwork.protocol.indexOf('http') > -1) engine.addProvider(new RpcSubprovider({rpcUrl}));
- else engine.addProvider(new WebsocketSubprovider({rpcUrl}));
-
- engine.start();
-
- return web3;
- }
- }
-}
-
-
-
-class ScatterEthereumWallet {
- constructor(){
- this.getAccounts = this.getAccounts.bind(this);
- this.signTransaction = this.signTransaction.bind(this);
- }
-
- async getAccounts(callback) {
- const result = await SocketService.sendApiRequest({
- type:'identityFromPermissions',
- payload:{}
- });
- const accounts = !result ? [] : result.accounts
- .filter(account => account.blockchain === Blockchains.ETH)
- .map(account => account.address);
-
- callback(null, accounts);
- return accounts;
- }
-
- async signTransaction(transaction){
- if(!ethNetwork) throw Error.noNetwork();
-
- // Basic settings
- if (transaction.gas !== undefined) transaction.gasLimit = transaction.gas;
- transaction.value = transaction.value || '0x00';
- if(transaction.hasOwnProperty('data')) transaction.data = ethUtil.addHexPrefix(transaction.data);
-
- // Required Fields
- const requiredFields = transaction.hasOwnProperty('requiredFields') ? transaction.requiredFields : {};
-
- // Contract ABI
- const abi = transaction.hasOwnProperty('abi') ? transaction.abi : null;
- if(!abi && transaction.hasOwnProperty('data'))
- throw Error.signatureError('no_abi', 'You must provide a JSON ABI along with your transaction so that users can read the contract');
-
- const payload = Object.assign(transaction, { blockchain:Blockchains.ETH, network:ethNetwork, requiredFields });
- const {signatures, returnedFields} = await SocketService.sendApiRequest({
- type:'requestSignature',
- payload
- });
-
- if(transaction.hasOwnProperty('fieldsCallback'))
- transaction.fieldsCallback(returnedFields);
-
- return signatures[0];
- }
-}
+// import ETH from './defaults/eth';
/***
* Setting up for plugin based generators,
@@ -482,7 +399,7 @@ class PluginRepositorySingleton {
loadPlugins(){
this.plugins.push(new EOS());
- this.plugins.push(new ETH());
+ // this.plugins.push(new ETH());
}
signatureProviders(){
@@ -645,6 +562,22 @@ class Scatter {
});
}
+ getPublicKey(blockchain){
+ throwNoAuth();
+ return SocketService.sendApiRequest({
+ type:'getPublicKey',
+ payload:{ blockchain }
+ });
+ }
+
+ linkAccount(publicKey, account, network){
+ throwNoAuth();
+ return SocketService.sendApiRequest({
+ type:'linkAccount',
+ payload:{ publicKey, account, network }
+ });
+ }
+
suggestNetwork(network){
throwNoAuth();
return SocketService.sendApiRequest({
diff --git a/dist/scatter.min.js b/dist/scatter.min.js
index 755bed9d..d165c706 100644
--- a/dist/scatter.min.js
+++ b/dist/scatter.min.js
@@ -60,7 +60,7 @@
/******/ __webpack_require__.p = "";
/******/
/******/ // Load entry module and return exports
-/******/ return __webpack_require__(__webpack_require__.s = 185);
+/******/ return __webpack_require__(__webpack_require__.s = 141);
/******/ })
/************************************************************************/
/******/ ([
@@ -175,9 +175,9 @@ if (typeof Object.create === 'function') {
-var base64 = __webpack_require__(222)
-var ieee754 = __webpack_require__(223)
-var isArray = __webpack_require__(224)
+var base64 = __webpack_require__(179)
+var ieee754 = __webpack_require__(180)
+var isArray = __webpack_require__(181)
exports.Buffer = Buffer
exports.SlowBuffer = SlowBuffer
@@ -2057,7 +2057,7 @@ function isBuffer(b) {
// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
-var util = __webpack_require__(8);
+var util = __webpack_require__(235);
var hasOwn = Object.prototype.hasOwnProperty;
var pSlice = Array.prototype.slice;
var functionsHaveNames = (function () {
@@ -2506,8 +2506,8 @@ if (typeof __g == 'number') __g = global; // eslint-disable-line no-undef
/* 7 */
/***/ (function(module, exports, __webpack_require__) {
-var store = __webpack_require__(75)('wks');
-var uid = __webpack_require__(54);
+var store = __webpack_require__(56)('wks');
+var uid = __webpack_require__(41);
var Symbol = __webpack_require__(6).Symbol;
var USE_SYMBOL = typeof Symbol == 'function';
@@ -2523,49924 +2523,35956 @@ $exports.store = store;
/* 8 */
/***/ (function(module, exports, __webpack_require__) {
-/* WEBPACK VAR INJECTION */(function(global, process) {// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
+var isObject = __webpack_require__(14);
+module.exports = function (it) {
+ if (!isObject(it)) throw TypeError(it + ' is not an object!');
+ return it;
+};
-var formatRegExp = /%[sdj%]/g;
-exports.format = function(f) {
- if (!isString(f)) {
- var objects = [];
- for (var i = 0; i < arguments.length; i++) {
- objects.push(inspect(arguments[i]));
- }
- return objects.join(' ');
- }
- var i = 1;
- var args = arguments;
- var len = args.length;
- var str = String(f).replace(formatRegExp, function(x) {
- if (x === '%%') return '%';
- if (i >= len) return x;
- switch (x) {
- case '%s': return String(args[i++]);
- case '%d': return Number(args[i++]);
- case '%j':
- try {
- return JSON.stringify(args[i++]);
- } catch (_) {
- return '[Circular]';
- }
- default:
- return x;
- }
- });
- for (var x = args[i]; i < len; x = args[++i]) {
- if (isNull(x) || !isObject(x)) {
- str += ' ' + x;
- } else {
- str += ' ' + inspect(x);
- }
- }
- return str;
-};
+/***/ }),
+/* 9 */
+/***/ (function(module, exports, __webpack_require__) {
+/* WEBPACK VAR INJECTION */(function(process) {/**
+ * This is the web browser implementation of `debug()`.
+ *
+ * Expose `debug()` as the module.
+ */
-// Mark that a method should not be used.
-// Returns a modified function which warns once by default.
-// If --no-deprecation is set, then it is a no-op.
-exports.deprecate = function(fn, msg) {
- // Allow for deprecating things in the process of starting up.
- if (isUndefined(global.process)) {
- return function() {
- return exports.deprecate(fn, msg).apply(this, arguments);
- };
- }
+exports = module.exports = __webpack_require__(171);
+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();
- if (process.noDeprecation === true) {
- return fn;
+/**
+ * Colors.
+ */
+
+exports.colors = [
+ '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',
+ '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',
+ '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',
+ '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',
+ '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',
+ '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',
+ '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',
+ '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',
+ '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',
+ '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',
+ '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'
+];
+
+/**
+ * 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;
}
- var warned = false;
- function deprecated() {
- if (!warned) {
- if (process.throwDeprecation) {
- throw new Error(msg);
- } else if (process.traceDeprecation) {
- console.trace(msg);
- } else {
- console.error(msg);
- }
- warned = true;
- }
- return fn.apply(this, arguments);
+ // Internet Explorer and Edge do not support colors.
+ if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
+ return false;
}
- return deprecated;
-};
+ // 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.
+ */
-var debugs = {};
-var debugEnviron;
-exports.debuglog = function(set) {
- if (isUndefined(debugEnviron))
- debugEnviron = process.env.NODE_DEBUG || '';
- set = set.toUpperCase();
- if (!debugs[set]) {
- if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
- var pid = process.pid;
- debugs[set] = function() {
- var msg = exports.format.apply(exports, arguments);
- console.error('%s %d: %s', set, pid, msg);
- };
- } else {
- debugs[set] = function() {};
- }
+exports.formatters.j = function(v) {
+ try {
+ return JSON.stringify(v);
+ } catch (err) {
+ return '[UnexpectedJSONParseError]: ' + err.message;
}
- return debugs[set];
};
/**
- * Echos the value of a value. Trys to print the value out
- * in the best way possible given the different types.
+ * Colorize log arguments if enabled.
*
- * @param {Object} obj The object to print out.
- * @param {Object} opts Optional options object that alters the output.
+ * @api public
*/
-/* legacy: obj, showHidden, depth, colors*/
-function inspect(obj, opts) {
- // default options
- var ctx = {
- seen: [],
- stylize: stylizeNoColor
- };
- // legacy...
- if (arguments.length >= 3) ctx.depth = arguments[2];
- if (arguments.length >= 4) ctx.colors = arguments[3];
- if (isBoolean(opts)) {
- // legacy...
- ctx.showHidden = opts;
- } else if (opts) {
- // got an "options" object
- exports._extend(ctx, opts);
- }
- // set default options
- if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
- if (isUndefined(ctx.depth)) ctx.depth = 2;
- if (isUndefined(ctx.colors)) ctx.colors = false;
- if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
- if (ctx.colors) ctx.stylize = stylizeWithColor;
- return formatValue(ctx, obj, ctx.depth);
-}
-exports.inspect = inspect;
+function formatArgs(args) {
+ var useColors = this.useColors;
-// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
-inspect.colors = {
- 'bold' : [1, 22],
- 'italic' : [3, 23],
- 'underline' : [4, 24],
- 'inverse' : [7, 27],
- 'white' : [37, 39],
- 'grey' : [90, 39],
- 'black' : [30, 39],
- 'blue' : [34, 39],
- 'cyan' : [36, 39],
- 'green' : [32, 39],
- 'magenta' : [35, 39],
- 'red' : [31, 39],
- 'yellow' : [33, 39]
-};
+ args[0] = (useColors ? '%c' : '')
+ + this.namespace
+ + (useColors ? ' %c' : ' ')
+ + args[0]
+ + (useColors ? '%c ' : ' ')
+ + '+' + exports.humanize(this.diff);
-// Don't use 'blue' not visible on cmd.exe
-inspect.styles = {
- 'special': 'cyan',
- 'number': 'yellow',
- 'boolean': 'yellow',
- 'undefined': 'grey',
- 'null': 'bold',
- 'string': 'green',
- 'date': 'magenta',
- // "name": intentionally not styling
- 'regexp': 'red'
-};
+ if (!useColors) return;
+ var c = 'color: ' + this.color;
+ args.splice(1, 0, c, 'color: inherit')
-function stylizeWithColor(str, styleType) {
- var style = inspect.styles[styleType];
+ // 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;
+ }
+ });
- if (style) {
- return '\u001b[' + inspect.colors[style][0] + 'm' + str +
- '\u001b[' + inspect.colors[style][1] + 'm';
- } else {
- return str;
- }
+ args.splice(lastC, 0, c);
}
+/**
+ * Invokes `console.log()` when available.
+ * No-op when `console.log` is not a "function".
+ *
+ * @api public
+ */
-function stylizeNoColor(str, styleType) {
- return str;
+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 arrayToHash(array) {
- var hash = {};
-
- array.forEach(function(val, idx) {
- hash[val] = true;
- });
-
- return hash;
+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 formatValue(ctx, value, recurseTimes) {
- // Provide a hook for user-specified inspect functions.
- // Check that value is an object with an inspect function on it
- if (ctx.customInspect &&
- value &&
- isFunction(value.inspect) &&
- // Filter out the util module, it's inspect function is special
- value.inspect !== exports.inspect &&
- // Also filter out any prototype objects using the circular check.
- !(value.constructor && value.constructor.prototype === value)) {
- var ret = value.inspect(recurseTimes, ctx);
- if (!isString(ret)) {
- ret = formatValue(ctx, ret, recurseTimes);
- }
- return ret;
- }
+function load() {
+ var r;
+ try {
+ r = exports.storage.debug;
+ } catch(e) {}
- // Primitive types cannot have properties
- var primitive = formatPrimitive(ctx, value);
- if (primitive) {
- return primitive;
+ // 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;
}
- // Look up the keys of the object.
- var keys = Object.keys(value);
- var visibleKeys = arrayToHash(keys);
+ return r;
+}
- if (ctx.showHidden) {
- keys = Object.getOwnPropertyNames(value);
- }
+/**
+ * Enable namespaces listed in `localStorage.debug` initially.
+ */
- // IE doesn't make error fields non-enumerable
- // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
- if (isError(value)
- && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
- return formatError(value);
- }
+exports.enable(load());
- // Some type of object without properties can be shortcutted.
- if (keys.length === 0) {
- if (isFunction(value)) {
- var name = value.name ? ': ' + value.name : '';
- return ctx.stylize('[Function' + name + ']', 'special');
- }
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- }
- if (isDate(value)) {
- return ctx.stylize(Date.prototype.toString.call(value), 'date');
- }
- if (isError(value)) {
- return formatError(value);
- }
- }
+/**
+ * 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
+ */
- var base = '', array = false, braces = ['{', '}'];
+function localstorage() {
+ try {
+ return window.localStorage;
+ } catch (e) {}
+}
- // Make Array say that they are Array
- if (isArray(value)) {
- array = true;
- braces = ['[', ']'];
- }
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(17)))
- // Make functions say that they are functions
- if (isFunction(value)) {
- var n = value.name ? ': ' + value.name : '';
- base = ' [Function' + n + ']';
- }
+/***/ }),
+/* 10 */
+/***/ (function(module, exports, __webpack_require__) {
- // Make RegExps say that they are RegExps
- if (isRegExp(value)) {
- base = ' ' + RegExp.prototype.toString.call(value);
- }
+var BigInteger = __webpack_require__(126)
- // Make dates with properties first say the date
- if (isDate(value)) {
- base = ' ' + Date.prototype.toUTCString.call(value);
- }
+//addons
+__webpack_require__(238)
- // Make error with message first say the error
- if (isError(value)) {
- base = ' ' + formatError(value);
- }
+module.exports = BigInteger
- if (keys.length === 0 && (!array || value.length == 0)) {
- return braces[0] + base + braces[1];
- }
+/***/ }),
+/* 11 */
+/***/ (function(module, exports, __webpack_require__) {
- if (recurseTimes < 0) {
- if (isRegExp(value)) {
- return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
- } else {
- return ctx.stylize('[Object]', 'special');
+var global = __webpack_require__(6);
+var core = __webpack_require__(5);
+var ctx = __webpack_require__(38);
+var hide = __webpack_require__(12);
+var has = __webpack_require__(16);
+var PROTOTYPE = 'prototype';
+
+var $export = function (type, name, source) {
+ var IS_FORCED = type & $export.F;
+ var IS_GLOBAL = type & $export.G;
+ var IS_STATIC = type & $export.S;
+ var IS_PROTO = type & $export.P;
+ var IS_BIND = type & $export.B;
+ var IS_WRAP = type & $export.W;
+ var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
+ var expProto = exports[PROTOTYPE];
+ var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
+ var key, own, out;
+ if (IS_GLOBAL) source = name;
+ for (key in source) {
+ // contains in native
+ own = !IS_FORCED && target && target[key] !== undefined;
+ if (own && has(exports, key)) continue;
+ // export native or passed
+ out = own ? target[key] : source[key];
+ // prevent global pollution for namespaces
+ exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
+ // bind timers to global for call from export context
+ : IS_BIND && own ? ctx(out, global)
+ // wrap global constructors for prevent change them in library
+ : IS_WRAP && target[key] == out ? (function (C) {
+ var F = function (a, b, c) {
+ if (this instanceof C) {
+ switch (arguments.length) {
+ case 0: return new C();
+ case 1: return new C(a);
+ case 2: return new C(a, b);
+ } return new C(a, b, c);
+ } return C.apply(this, arguments);
+ };
+ F[PROTOTYPE] = C[PROTOTYPE];
+ return F;
+ // make static versions for prototype methods
+ })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
+ // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
+ if (IS_PROTO) {
+ (exports.virtual || (exports.virtual = {}))[key] = out;
+ // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
+ if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
}
}
+};
+// type bitmap
+$export.F = 1; // forced
+$export.G = 2; // global
+$export.S = 4; // static
+$export.P = 8; // proto
+$export.B = 16; // bind
+$export.W = 32; // wrap
+$export.U = 64; // safe
+$export.R = 128; // real proto method for `library`
+module.exports = $export;
- ctx.seen.push(value);
- var output;
- if (array) {
- output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
- } else {
- output = keys.map(function(key) {
- return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
- });
- }
+/***/ }),
+/* 12 */
+/***/ (function(module, exports, __webpack_require__) {
- ctx.seen.pop();
+var dP = __webpack_require__(13);
+var createDesc = __webpack_require__(40);
+module.exports = __webpack_require__(15) ? function (object, key, value) {
+ return dP.f(object, key, createDesc(1, value));
+} : function (object, key, value) {
+ object[key] = value;
+ return object;
+};
- return reduceToSingleString(output, base, braces);
-}
+/***/ }),
+/* 13 */
+/***/ (function(module, exports, __webpack_require__) {
-function formatPrimitive(ctx, value) {
- if (isUndefined(value))
- return ctx.stylize('undefined', 'undefined');
- if (isString(value)) {
- var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
- .replace(/'/g, "\\'")
- .replace(/\\"/g, '"') + '\'';
- return ctx.stylize(simple, 'string');
- }
- if (isNumber(value))
- return ctx.stylize('' + value, 'number');
- if (isBoolean(value))
- return ctx.stylize('' + value, 'boolean');
- // For some reason typeof null is "object", so special case here.
- if (isNull(value))
- return ctx.stylize('null', 'null');
-}
-
-
-function formatError(value) {
- return '[' + Error.prototype.toString.call(value) + ']';
-}
-
-
-function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
- var output = [];
- for (var i = 0, l = value.length; i < l; ++i) {
- if (hasOwnProperty(value, String(i))) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- String(i), true));
- } else {
- output.push('');
- }
- }
- keys.forEach(function(key) {
- if (!key.match(/^\d+$/)) {
- output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
- key, true));
- }
- });
- return output;
-}
+var anObject = __webpack_require__(8);
+var IE8_DOM_DEFINE = __webpack_require__(80);
+var toPrimitive = __webpack_require__(52);
+var dP = Object.defineProperty;
+exports.f = __webpack_require__(15) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
+ anObject(O);
+ P = toPrimitive(P, true);
+ anObject(Attributes);
+ if (IE8_DOM_DEFINE) try {
+ return dP(O, P, Attributes);
+ } catch (e) { /* empty */ }
+ if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
+ if ('value' in Attributes) O[P] = Attributes.value;
+ return O;
+};
-function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
- var name, str, desc;
- desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
- if (desc.get) {
- if (desc.set) {
- str = ctx.stylize('[Getter/Setter]', 'special');
- } else {
- str = ctx.stylize('[Getter]', 'special');
- }
- } else {
- if (desc.set) {
- str = ctx.stylize('[Setter]', 'special');
- }
- }
- if (!hasOwnProperty(visibleKeys, key)) {
- name = '[' + key + ']';
- }
- if (!str) {
- if (ctx.seen.indexOf(desc.value) < 0) {
- if (isNull(recurseTimes)) {
- str = formatValue(ctx, desc.value, null);
- } else {
- str = formatValue(ctx, desc.value, recurseTimes - 1);
- }
- if (str.indexOf('\n') > -1) {
- if (array) {
- str = str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n').substr(2);
- } else {
- str = '\n' + str.split('\n').map(function(line) {
- return ' ' + line;
- }).join('\n');
- }
- }
- } else {
- str = ctx.stylize('[Circular]', 'special');
- }
- }
- if (isUndefined(name)) {
- if (array && key.match(/^\d+$/)) {
- return str;
- }
- name = JSON.stringify('' + key);
- if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
- name = name.substr(1, name.length - 2);
- name = ctx.stylize(name, 'name');
- } else {
- name = name.replace(/'/g, "\\'")
- .replace(/\\"/g, '"')
- .replace(/(^"|"$)/g, "'");
- name = ctx.stylize(name, 'string');
- }
- }
- return name + ': ' + str;
-}
+/***/ }),
+/* 14 */
+/***/ (function(module, exports) {
+module.exports = function (it) {
+ return typeof it === 'object' ? it !== null : typeof it === 'function';
+};
-function reduceToSingleString(output, base, braces) {
- var numLinesEst = 0;
- var length = output.reduce(function(prev, cur) {
- numLinesEst++;
- if (cur.indexOf('\n') >= 0) numLinesEst++;
- return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
- }, 0);
- if (length > 60) {
- return braces[0] +
- (base === '' ? '' : base + '\n ') +
- ' ' +
- output.join(',\n ') +
- ' ' +
- braces[1];
- }
+/***/ }),
+/* 15 */
+/***/ (function(module, exports, __webpack_require__) {
- return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
-}
+// Thank's IE8 for his funny defineProperty
+module.exports = !__webpack_require__(21)(function () {
+ return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
+});
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-function isArray(ar) {
- return Array.isArray(ar);
-}
-exports.isArray = isArray;
+/***/ }),
+/* 16 */
+/***/ (function(module, exports) {
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
+var hasOwnProperty = {}.hasOwnProperty;
+module.exports = function (it, key) {
+ return hasOwnProperty.call(it, key);
+};
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
+/***/ }),
+/* 17 */
+/***/ (function(module, exports) {
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
+// shim for using process in browser
+var process = module.exports = {};
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
+// cached from whatever global is present so that test runners that stub it
+// don't break things. But we need to wrap it in a try catch in case it is
+// wrapped in strict mode code which doesn't define any globals. It's inside a
+// function because try/catches deoptimize in certain engines.
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
+var cachedSetTimeout;
+var cachedClearTimeout;
-function isUndefined(arg) {
- return arg === void 0;
+function defaultSetTimout() {
+ throw new Error('setTimeout has not been defined');
}
-exports.isUndefined = isUndefined;
-
-function isRegExp(re) {
- return isObject(re) && objectToString(re) === '[object RegExp]';
+function defaultClearTimeout () {
+ throw new Error('clearTimeout has not been defined');
}
-exports.isRegExp = isRegExp;
+(function () {
+ try {
+ if (typeof setTimeout === 'function') {
+ cachedSetTimeout = setTimeout;
+ } else {
+ cachedSetTimeout = defaultSetTimout;
+ }
+ } catch (e) {
+ cachedSetTimeout = defaultSetTimout;
+ }
+ try {
+ if (typeof clearTimeout === 'function') {
+ cachedClearTimeout = clearTimeout;
+ } else {
+ cachedClearTimeout = defaultClearTimeout;
+ }
+ } catch (e) {
+ cachedClearTimeout = defaultClearTimeout;
+ }
+} ())
+function runTimeout(fun) {
+ if (cachedSetTimeout === setTimeout) {
+ //normal enviroments in sane situations
+ return setTimeout(fun, 0);
+ }
+ // if setTimeout wasn't available but was latter defined
+ if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
+ cachedSetTimeout = setTimeout;
+ return setTimeout(fun, 0);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedSetTimeout(fun, 0);
+ } catch(e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedSetTimeout.call(null, fun, 0);
+ } catch(e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
+ return cachedSetTimeout.call(this, fun, 0);
+ }
+ }
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
-function isDate(d) {
- return isObject(d) && objectToString(d) === '[object Date]';
}
-exports.isDate = isDate;
+function runClearTimeout(marker) {
+ if (cachedClearTimeout === clearTimeout) {
+ //normal enviroments in sane situations
+ return clearTimeout(marker);
+ }
+ // if clearTimeout wasn't available but was latter defined
+ if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
+ cachedClearTimeout = clearTimeout;
+ return clearTimeout(marker);
+ }
+ try {
+ // when when somebody has screwed with setTimeout but no I.E. maddness
+ return cachedClearTimeout(marker);
+ } catch (e){
+ try {
+ // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
+ return cachedClearTimeout.call(null, marker);
+ } catch (e){
+ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
+ // Some versions of I.E. have different rules for clearTimeout vs setTimeout
+ return cachedClearTimeout.call(this, marker);
+ }
+ }
-function isError(e) {
- return isObject(e) &&
- (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
}
-exports.isPrimitive = isPrimitive;
-
-exports.isBuffer = __webpack_require__(276);
+var queue = [];
+var draining = false;
+var currentQueue;
+var queueIndex = -1;
-function objectToString(o) {
- return Object.prototype.toString.call(o);
+function cleanUpNextTick() {
+ if (!draining || !currentQueue) {
+ return;
+ }
+ draining = false;
+ if (currentQueue.length) {
+ queue = currentQueue.concat(queue);
+ } else {
+ queueIndex = -1;
+ }
+ if (queue.length) {
+ drainQueue();
+ }
}
+function drainQueue() {
+ if (draining) {
+ return;
+ }
+ var timeout = runTimeout(cleanUpNextTick);
+ draining = true;
-function pad(n) {
- return n < 10 ? '0' + n.toString(10) : n.toString(10);
+ var len = queue.length;
+ while(len) {
+ currentQueue = queue;
+ queue = [];
+ while (++queueIndex < len) {
+ if (currentQueue) {
+ currentQueue[queueIndex].run();
+ }
+ }
+ queueIndex = -1;
+ len = queue.length;
+ }
+ currentQueue = null;
+ draining = false;
+ runClearTimeout(timeout);
}
+process.nextTick = function (fun) {
+ var args = new Array(arguments.length - 1);
+ if (arguments.length > 1) {
+ for (var i = 1; i < arguments.length; i++) {
+ args[i - 1] = arguments[i];
+ }
+ }
+ queue.push(new Item(fun, args));
+ if (queue.length === 1 && !draining) {
+ runTimeout(drainQueue);
+ }
+};
-var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
- 'Oct', 'Nov', 'Dec'];
-
-// 26 Feb 16:19:34
-function timestamp() {
- var d = new Date();
- var time = [pad(d.getHours()),
- pad(d.getMinutes()),
- pad(d.getSeconds())].join(':');
- return [d.getDate(), months[d.getMonth()], time].join(' ');
+// v8 likes predictible objects
+function Item(fun, array) {
+ this.fun = fun;
+ this.array = array;
}
-
-
-// log is just a thin wrapper to console.log that prepends a timestamp
-exports.log = function() {
- console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
+Item.prototype.run = function () {
+ this.fun.apply(null, this.array);
};
+process.title = 'browser';
+process.browser = true;
+process.env = {};
+process.argv = [];
+process.version = ''; // empty string to avoid regexp issues
+process.versions = {};
+function noop() {}
-/**
- * Inherit the prototype methods from one constructor into another.
- *
- * The Function.prototype.inherits from lang.js rewritten as a standalone
- * function (not on Function.prototype). NOTE: If this file is to be loaded
- * during bootstrapping this function needs to be rewritten using some native
- * functions as prototype setup using normal JavaScript does not work as
- * expected during bootstrapping (see mirror.js in r114903).
- *
- * @param {function} ctor Constructor function which needs to inherit the
- * prototype.
- * @param {function} superCtor Constructor function to inherit prototype from.
- */
-exports.inherits = __webpack_require__(1);
+process.on = noop;
+process.addListener = noop;
+process.once = noop;
+process.off = noop;
+process.removeListener = noop;
+process.removeAllListeners = noop;
+process.emit = noop;
+process.prependListener = noop;
+process.prependOnceListener = noop;
-exports._extend = function(origin, add) {
- // Don't do anything if add isn't an object
- if (!add || !isObject(add)) return origin;
+process.listeners = function (name) { return [] }
- var keys = Object.keys(add);
- var i = keys.length;
- while (i--) {
- origin[keys[i]] = add[keys[i]];
- }
- return origin;
+process.binding = function (name) {
+ throw new Error('process.binding is not supported');
};
-function hasOwnProperty(obj, prop) {
- return Object.prototype.hasOwnProperty.call(obj, prop);
-}
+process.cwd = function () { return '/' };
+process.chdir = function (dir) {
+ throw new Error('process.chdir is not supported');
+};
+process.umask = function() { return 0; };
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3), __webpack_require__(11)))
/***/ }),
-/* 9 */
+/* 18 */
/***/ (function(module, exports, __webpack_require__) {
-/* WEBPACK VAR INJECTION */(function(module) {(function (module, exports) {
- 'use strict';
+var Buffer = __webpack_require__(0).Buffer
+var Transform = __webpack_require__(117).Transform
+var StringDecoder = __webpack_require__(73).StringDecoder
+var inherits = __webpack_require__(1)
- // Utils
- function assert (val, msg) {
- if (!val) throw new Error(msg || 'Assertion failed');
+function CipherBase (hashMode) {
+ Transform.call(this)
+ this.hashMode = typeof hashMode === 'string'
+ if (this.hashMode) {
+ this[hashMode] = this._finalOrDigest
+ } else {
+ this.final = this._finalOrDigest
}
+ if (this._final) {
+ this.__final = this._final
+ this._final = null
+ }
+ this._decoder = null
+ this._encoding = null
+}
+inherits(CipherBase, Transform)
- // 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;
+CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
+ if (typeof data === 'string') {
+ data = Buffer.from(data, inputEnc)
}
- // BN
+ var outData = this._update(data)
+ if (this.hashMode) return this
- function BN (number, base, endian) {
- if (BN.isBN(number)) {
- return number;
- }
+ if (outputEnc) {
+ outData = this._toString(outData, outputEnc)
+ }
- this.negative = 0;
- this.words = null;
- this.length = 0;
+ return outData
+}
- // Reduction context
- this.red = null;
+CipherBase.prototype.setAutoPadding = function () {}
+CipherBase.prototype.getAuthTag = function () {
+ throw new Error('trying to get auth tag in unsupported state')
+}
- if (number !== null) {
- if (base === 'le' || base === 'be') {
- endian = base;
- base = 10;
- }
+CipherBase.prototype.setAuthTag = function () {
+ throw new Error('trying to set auth tag in unsupported state')
+}
- this._init(number || 0, base || 10, endian || 'be');
+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)
}
- if (typeof module === 'object') {
- module.exports = BN;
- } else {
- exports.BN = BN;
- }
-
- BN.BN = BN;
- BN.wordSize = 26;
-
- var Buffer;
+}
+CipherBase.prototype._flush = function (done) {
+ var err
try {
- Buffer = __webpack_require__(295).Buffer;
+ this.push(this.__final())
} catch (e) {
+ err = 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;
- };
+ done(err)
+}
+CipherBase.prototype._finalOrDigest = function (outputEnc) {
+ var outData = this.__final() || Buffer.alloc(0)
+ if (outputEnc) {
+ outData = this._toString(outData, outputEnc, true)
+ }
+ return outData
+}
- BN.min = function min (left, right) {
- if (left.cmp(right) < 0) return left;
- return right;
- };
+CipherBase.prototype._toString = function (value, enc, fin) {
+ if (!this._decoder) {
+ this._decoder = new StringDecoder(enc)
+ this._encoding = enc
+ }
- BN.prototype._init = function init (number, base, endian) {
- if (typeof number === 'number') {
- return this._initNumber(number, base, endian);
- }
+ if (this._encoding !== enc) throw new Error('can\'t switch encodings')
- if (typeof number === 'object') {
- return this._initArray(number, base, endian);
- }
+ var out = this._decoder.write(value)
+ if (fin) {
+ out += this._decoder.end()
+ }
- if (base === 'hex') {
- base = 16;
- }
- assert(base === (base | 0) && base >= 2 && base <= 36);
+ return out
+}
- number = number.toString().replace(/\s+/g, '');
- var start = 0;
- if (number[0] === '-') {
- start++;
- }
+module.exports = CipherBase
- if (base === 16) {
- this._parseHex(number, start);
- } else {
- this._parseBase(number, base, start);
- }
- if (number[0] === '-') {
- this.negative = 1;
- }
+/***/ }),
+/* 19 */
+/***/ (function(module, exports, __webpack_require__) {
- this.strip();
+"use strict";
+// Copyright Joyent, Inc. and other Node contributors.
+//
+// Permission is hereby granted, free of charge, to any person obtaining a
+// copy of this software and associated documentation files (the
+// "Software"), to deal in the Software without restriction, including
+// without limitation the rights to use, copy, modify, merge, publish,
+// distribute, sublicense, and/or sell copies of the Software, and to permit
+// persons to whom the Software is furnished to do so, subject to the
+// following conditions:
+//
+// The above copyright notice and this permission notice shall be included
+// in all copies or substantial portions of the Software.
+//
+// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
+// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
+// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
+// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
+// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
+// USE OR OTHER DEALINGS IN THE SOFTWARE.
- if (endian !== 'le') return;
+// 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.
- 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);
- };
+var pna = __webpack_require__(49);
+/**/
- 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;
- }
+/**/
+var objectKeys = Object.keys || function (obj) {
+ var keys = [];
+ for (var key in obj) {
+ keys.push(key);
+ }return keys;
+};
+/**/
- 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;
- }
+module.exports = Duplex;
- 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();
- };
+/**/
+var util = __webpack_require__(34);
+util.inherits = __webpack_require__(1);
+/**/
- 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;
+var Readable = __webpack_require__(118);
+var Writable = __webpack_require__(72);
- r <<= 4;
+util.inherits(Duplex, Readable);
- // 'a' - 'f'
- if (c >= 49 && c <= 54) {
- r |= c - 49 + 0xa;
+{
+ // avoid scope creep, the keys array can then be collected
+ 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];
+ }
+}
- // 'A' - 'F'
- } else if (c >= 17 && c <= 22) {
- r |= c - 17 + 0xa;
+function Duplex(options) {
+ if (!(this instanceof Duplex)) return new Duplex(options);
- // '0' - '9'
- } else {
- r |= c & 0xf;
- }
- }
- return r;
- }
+ Readable.call(this, options);
+ Writable.call(this, options);
- 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;
- }
+ if (options && options.readable === false) this.readable = false;
- 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();
- };
+ if (options && options.writable === false) this.writable = false;
- 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;
+ this.allowHalfOpen = true;
+ if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
- r *= mul;
+ this.once('end', onend);
+}
- // 'a'
- if (c >= 49) {
- r += c - 49 + 0xa;
+Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
+ // making it explicit this property is not enumerable
+ // because otherwise some prototype manipulation in
+ // userland will fail
+ enumerable: false,
+ get: function () {
+ return this._writableState.highWaterMark;
+ }
+});
- // 'A'
- } else if (c >= 17) {
- r += c - 17 + 0xa;
+// 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;
- // '0' - '9'
- } else {
- r += c;
- }
+ // no more data can be written.
+ // But allow more writes to happen in this tick.
+ pna.nextTick(onEndNT, this);
+}
+
+function onEndNT(self) {
+ self.end();
+}
+
+Object.defineProperty(Duplex.prototype, 'destroyed', {
+ get: function () {
+ if (this._readableState === undefined || this._writableState === undefined) {
+ return false;
}
- return r;
+ 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;
}
+});
- BN.prototype._parseBase = function _parseBase (number, base, start) {
- // Initialize as zero
- this.words = [ 0 ];
- this.length = 1;
+Duplex.prototype._destroy = function (err, cb) {
+ this.push(null);
+ this.end();
- // Find length of limb in base
- for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
- limbLen++;
- }
- limbLen--;
- limbPow = (limbPow / base) | 0;
+ pna.nextTick(cb, err);
+};
- var total = number.length - start;
- var mod = total % limbLen;
- var end = Math.min(total, total - mod) + start;
+/***/ }),
+/* 20 */
+/***/ (function(module, exports, __webpack_require__) {
- var word = 0;
- for (var i = start; i < end; i += limbLen) {
- word = parseBase(number, i, i + limbLen, base);
+"use strict";
- 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);
+var createHash = __webpack_require__(76);
+var createHmac = __webpack_require__(245);
- for (i = 0; i < mod; i++) {
- pow *= base;
- }
+/** @namespace hash */
- this.imuln(pow);
- if (this.words[0] + word < 0x4000000) {
- this.words[0] += word;
- } else {
- this._iaddn(word);
- }
- }
- };
+/** @arg {string|Buffer} data
+ @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'
+ @return {string|Buffer} - Buffer when resultEncoding is null, or string
+*/
+function sha1(data, resultEncoding) {
+ return createHash('sha1').update(data).digest(resultEncoding);
+}
- 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;
- };
+/** @arg {string|Buffer} data
+ @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'
+ @return {string|Buffer} - Buffer when resultEncoding is null, or string
+*/
+function sha256(data, resultEncoding) {
+ return createHash('sha256').update(data).digest(resultEncoding);
+}
- BN.prototype.clone = function clone () {
- var r = new BN(null);
- this.copy(r);
- return r;
- };
+/** @arg {string|Buffer} data
+ @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'
+ @return {string|Buffer} - Buffer when resultEncoding is null, or string
+*/
+function sha512(data, resultEncoding) {
+ return createHash('sha512').update(data).digest(resultEncoding);
+}
- BN.prototype._expand = function _expand (size) {
- while (this.length < size) {
- this.words[this.length++] = 0;
- }
- return this;
- };
+function HmacSHA256(buffer, secret) {
+ return createHmac('sha256', secret).update(buffer).digest();
+}
- // 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();
- };
+function ripemd160(data) {
+ return createHash('rmd160').update(data).digest();
+}
- BN.prototype._normSign = function _normSign () {
- // -0 = 0
- if (this.length === 1 && this.words[0] === 0) {
- this.negative = 0;
- }
- return this;
- };
+// function hash160(buffer) {
+// return ripemd160(sha256(buffer))
+// }
+//
+// function hash256(buffer) {
+// return sha256(sha256(buffer))
+// }
- BN.prototype.inspect = function inspect () {
- return (this.red ? '';
- };
+//
+// function HmacSHA512(buffer, secret) {
+// return crypto.createHmac('sha512', secret).update(buffer).digest()
+// }
- /*
+module.exports = {
+ sha1: sha1,
+ sha256: sha256,
+ sha512: sha512,
+ HmacSHA256: HmacSHA256,
+ ripemd160: ripemd160
+ // hash160: hash160,
+ // hash256: hash256,
+ // HmacSHA512: HmacSHA512
+};
- var zeros = [];
- var groupSizes = [];
- var groupBases = [];
+/***/ }),
+/* 21 */
+/***/ (function(module, exports) {
- 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;
+module.exports = function (exec) {
+ try {
+ return !!exec();
+ } catch (e) {
+ return true;
}
+};
- */
-
- 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
- ];
+/***/ }),
+/* 22 */
+/***/ (function(module, exports, __webpack_require__) {
- 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
- ];
+// to indexed object, toObject with fallback for non-array-like ES3 strings
+var IObject = __webpack_require__(82);
+var defined = __webpack_require__(53);
+module.exports = function (it) {
+ return IObject(defined(it));
+};
- 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;
- }
+/***/ }),
+/* 23 */
+/***/ (function(module, exports) {
- 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);
+module.exports = {};
- 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');
- };
+/***/ }),
+/* 24 */
+/***/ (function(module, exports, __webpack_require__) {
- 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;
- };
+
+/**
+ * Expose `Emitter`.
+ */
+
+if (true) {
+ module.exports = Emitter;
+}
+
+/**
+ * Initialize a new `Emitter`.
+ *
+ * @api public
+ */
+
+function Emitter(obj) {
+ if (obj) return mixin(obj);
+};
+
+/**
+ * Mixin the emitter properties.
+ *
+ * @param {Object} obj
+ * @return {Object}
+ * @api private
+ */
+
+function mixin(obj) {
+ for (var key in Emitter.prototype) {
+ obj[key] = Emitter.prototype[key];
+ }
+ return obj;
+}
+
+/**
+ * Listen on the given `event` with `fn`.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.on =
+Emitter.prototype.addEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+ (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
+ .push(fn);
+ return this;
+};
+
+/**
+ * Adds an `event` listener that will be invoked a single
+ * time then automatically removed.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.once = function(event, fn){
+ function on() {
+ this.off(event, on);
+ fn.apply(this, arguments);
+ }
+
+ on.fn = fn;
+ this.on(event, on);
+ return this;
+};
+
+/**
+ * Remove the given callback for `event` or all
+ * registered callbacks.
+ *
+ * @param {String} event
+ * @param {Function} fn
+ * @return {Emitter}
+ * @api public
+ */
+
+Emitter.prototype.off =
+Emitter.prototype.removeListener =
+Emitter.prototype.removeAllListeners =
+Emitter.prototype.removeEventListener = function(event, fn){
+ this._callbacks = this._callbacks || {};
+
+ // all
+ if (0 == arguments.length) {
+ this._callbacks = {};
+ return this;
+ }
+
+ // specific event
+ var callbacks = this._callbacks['$' + event];
+ if (!callbacks) return this;
+
+ // remove all handlers
+ if (1 == arguments.length) {
+ delete this._callbacks['$' + event];
+ return this;
+ }
+
+ // remove specific handler
+ var cb;
+ for (var i = 0; i < callbacks.length; i++) {
+ cb = callbacks[i];
+ if (cb === fn || cb.fn === fn) {
+ callbacks.splice(i, 1);
+ break;
+ }
+ }
+ return this;
+};
+
+/**
+ * Emit `event` with the given args.
+ *
+ * @param {String} event
+ * @param {Mixed} ...
+ * @return {Emitter}
+ */
+
+Emitter.prototype.emit = function(event){
+ this._callbacks = this._callbacks || {};
+ var args = [].slice.call(arguments, 1)
+ , callbacks = this._callbacks['$' + event];
+
+ if (callbacks) {
+ callbacks = callbacks.slice(0);
+ for (var i = 0, len = callbacks.length; i < len; ++i) {
+ callbacks[i].apply(this, args);
+ }
+ }
+
+ return this;
+};
+
+/**
+ * Return array of callbacks for `event`.
+ *
+ * @param {String} event
+ * @return {Array}
+ * @api public
+ */
+
+Emitter.prototype.listeners = function(event){
+ this._callbacks = this._callbacks || {};
+ return this._callbacks['$' + event] || [];
+};
+
+/**
+ * Check if this emitter has `event` handlers.
+ *
+ * @param {String} event
+ * @return {Boolean}
+ * @api public
+ */
+
+Emitter.prototype.hasListeners = function(event){
+ return !! this.listeners(event).length;
+};
- 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);
- };
+/***/ }),
+/* 25 */
+/***/ (function(module, exports, __webpack_require__) {
- BN.prototype.toArray = function toArray (endian, length) {
- return this.toArrayLike(Array, endian, length);
- };
+/* WEBPACK VAR INJECTION */(function(global) {/**
+ * Module dependencies.
+ */
- 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');
+var keys = __webpack_require__(178);
+var hasBinary = __webpack_require__(101);
+var sliceBuffer = __webpack_require__(182);
+var after = __webpack_require__(183);
+var utf8 = __webpack_require__(184);
- this.strip();
- var littleEndian = endian === 'le';
- var res = new ArrayType(reqLength);
+var base64encoder;
+if (global && global.ArrayBuffer) {
+ base64encoder = __webpack_require__(185);
+}
- var b, i;
- var q = this.clone();
- if (!littleEndian) {
- // Assume big-endian
- for (i = 0; i < reqLength - byteLength; i++) {
- res[i] = 0;
- }
+/**
+ * Check if we are running an android browser. That requires us to use
+ * ArrayBuffer with polling transports...
+ *
+ * http://ghinda.net/jpeg-blob-ajax-android/
+ */
- for (i = 0; !q.isZero(); i++) {
- b = q.andln(0xff);
- q.iushrn(8);
+var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
- res[reqLength - i - 1] = b;
- }
- } else {
- for (i = 0; !q.isZero(); i++) {
- b = q.andln(0xff);
- q.iushrn(8);
+/**
+ * Check if we are running in PhantomJS.
+ * Uploading a Blob with PhantomJS does not work correctly, as reported here:
+ * https://github.com/ariya/phantomjs/issues/11395
+ * @type boolean
+ */
+var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
- res[i] = b;
- }
+/**
+ * When true, avoids using Blobs to encode payloads.
+ * @type boolean
+ */
+var dontSendBlobs = isAndroid || isPhantomJS;
- for (; i < reqLength; i++) {
- res[i] = 0;
- }
- }
+/**
+ * Current protocol version.
+ */
- return res;
- };
+exports.protocol = 3;
- 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;
- };
- }
+/**
+ * Packet types.
+ */
- BN.prototype._zeroBits = function _zeroBits (w) {
- // Short-cut
- if (w === 0) return 26;
+var packets = exports.packets = {
+ open: 0 // non-ws
+ , close: 1 // non-ws
+ , ping: 2
+ , pong: 3
+ , message: 4
+ , upgrade: 5
+ , noop: 6
+};
- 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;
- };
+var packetslist = keys(packets);
- // 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;
- };
+/**
+ * Premade error packet.
+ */
- function toBitArray (num) {
- var w = new Array(num.bitLength());
+var err = { type: 'error', data: 'parser error' };
- for (var bit = 0; bit < w.length; bit++) {
- var off = (bit / 26) | 0;
- var wbit = bit % 26;
+/**
+ * Create a blob api even for blob builder when vendor prefixes exist
+ */
- w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
- }
+var Blob = __webpack_require__(186);
- return w;
+/**
+ * Encodes a packet.
+ *
+ * [ ]
+ *
+ * Example:
+ *
+ * 5hello world
+ * 3
+ * 4
+ *
+ * Binary is encoded in an identical principle
+ *
+ * @api private
+ */
+
+exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
+ if (typeof supportsBinary === 'function') {
+ callback = supportsBinary;
+ supportsBinary = false;
}
- // Number of trailing zero bits
- BN.prototype.zeroBits = function zeroBits () {
- if (this.isZero()) return 0;
+ if (typeof utf8encode === 'function') {
+ callback = utf8encode;
+ utf8encode = null;
+ }
- 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;
- };
+ var data = (packet.data === undefined)
+ ? undefined
+ : packet.data.buffer || packet.data;
- BN.prototype.byteLength = function byteLength () {
- return Math.ceil(this.bitLength() / 8);
- };
+ if (global.ArrayBuffer && data instanceof ArrayBuffer) {
+ return encodeArrayBuffer(packet, supportsBinary, callback);
+ } else if (Blob && data instanceof global.Blob) {
+ return encodeBlob(packet, supportsBinary, callback);
+ }
- BN.prototype.toTwos = function toTwos (width) {
- if (this.negative !== 0) {
- return this.abs().inotn(width).iaddn(1);
- }
- return this.clone();
- };
+ // might be an object with { base64: true, data: dataAsBase64String }
+ if (data && data.base64) {
+ return encodeBase64Object(packet, callback);
+ }
- BN.prototype.fromTwos = function fromTwos (width) {
- if (this.testn(width - 1)) {
- return this.notn(width).iaddn(1).ineg();
- }
- return this.clone();
- };
+ // Sending data as a utf-8 string
+ var encoded = packets[packet.type];
- BN.prototype.isNeg = function isNeg () {
- return this.negative !== 0;
- };
+ // data fragment is optional
+ if (undefined !== packet.data) {
+ encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
+ }
- // Return negative clone of `this`
- BN.prototype.neg = function neg () {
- return this.clone().ineg();
- };
+ return callback('' + encoded);
- BN.prototype.ineg = function ineg () {
- if (!this.isZero()) {
- this.negative ^= 1;
- }
+};
- return this;
- };
+function encodeBase64Object(packet, callback) {
+ // packet data is an object { base64: true, data: dataAsBase64String }
+ var message = 'b' + exports.packets[packet.type] + packet.data.data;
+ return callback(message);
+}
- // Or `num` with `this` in-place
- BN.prototype.iuor = function iuor (num) {
- while (this.length < num.length) {
- this.words[this.length++] = 0;
- }
+/**
+ * Encode packet helpers for binary types
+ */
- for (var i = 0; i < num.length; i++) {
- this.words[i] = this.words[i] | num.words[i];
- }
+function encodeArrayBuffer(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
- return this.strip();
- };
+ var data = packet.data;
+ var contentArray = new Uint8Array(data);
+ var resultBuffer = new Uint8Array(1 + data.byteLength);
- BN.prototype.ior = function ior (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuor(num);
- };
+ resultBuffer[0] = packets[packet.type];
+ for (var i = 0; i < contentArray.length; i++) {
+ resultBuffer[i+1] = contentArray[i];
+ }
- // 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);
- };
+ return callback(resultBuffer.buffer);
+}
- BN.prototype.uor = function uor (num) {
- if (this.length > num.length) return this.clone().iuor(num);
- return num.clone().iuor(this);
- };
+function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
- // 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;
- }
+ var fr = new FileReader();
+ fr.onload = function() {
+ packet.data = fr.result;
+ exports.encodePacket(packet, supportsBinary, true, callback);
+ };
+ return fr.readAsArrayBuffer(packet.data);
+}
- for (var i = 0; i < b.length; i++) {
- this.words[i] = this.words[i] & num.words[i];
- }
+function encodeBlob(packet, supportsBinary, callback) {
+ if (!supportsBinary) {
+ return exports.encodeBase64Packet(packet, callback);
+ }
- this.length = b.length;
+ if (dontSendBlobs) {
+ return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
+ }
- return this.strip();
- };
+ var length = new Uint8Array(1);
+ length[0] = packets[packet.type];
+ var blob = new Blob([length.buffer, packet.data]);
- BN.prototype.iand = function iand (num) {
- assert((this.negative | num.negative) === 0);
- return this.iuand(num);
- };
+ return callback(blob);
+}
- // 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);
- };
+/**
+ * Encodes a packet with binary data in a base64 string
+ *
+ * @param {Object} packet, has `type` and `data`
+ * @return {String} base64 encoded message
+ */
- BN.prototype.uand = function uand (num) {
- if (this.length > num.length) return this.clone().iuand(num);
- return num.clone().iuand(this);
- };
+exports.encodeBase64Packet = function(packet, callback) {
+ var message = 'b' + exports.packets[packet.type];
+ if (Blob && packet.data instanceof global.Blob) {
+ var fr = new FileReader();
+ fr.onload = function() {
+ var b64 = fr.result.split(',')[1];
+ callback(message + b64);
+ };
+ return fr.readAsDataURL(packet.data);
+ }
- // 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;
+ var b64data;
+ try {
+ b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
+ } catch (e) {
+ // iPhone Safari doesn't let you apply with typed arrays
+ var typed = new Uint8Array(packet.data);
+ var basic = new Array(typed.length);
+ for (var i = 0; i < typed.length; i++) {
+ basic[i] = typed[i];
}
+ b64data = String.fromCharCode.apply(null, basic);
+ }
+ message += global.btoa(b64data);
+ return callback(message);
+};
- for (var i = 0; i < b.length; i++) {
- this.words[i] = a.words[i] ^ b.words[i];
+/**
+ * Decodes a packet. Changes format to Blob if requested.
+ *
+ * @return {Object} with `type` and `data` (if any)
+ * @api private
+ */
+
+exports.decodePacket = function (data, binaryType, utf8decode) {
+ if (data === undefined) {
+ return err;
+ }
+ // String data
+ if (typeof data === 'string') {
+ if (data.charAt(0) === 'b') {
+ return exports.decodeBase64Packet(data.substr(1), binaryType);
}
- if (this !== a) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
+ if (utf8decode) {
+ data = tryDecode(data);
+ if (data === false) {
+ return err;
}
}
+ var type = data.charAt(0);
- 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);
- };
+ if (Number(type) != type || !packetslist[type]) {
+ return err;
+ }
- // Not ``this`` with ``width`` bitwidth
- BN.prototype.inotn = function inotn (width) {
- assert(typeof width === 'number' && width >= 0);
+ if (data.length > 1) {
+ return { type: packetslist[type], data: data.substring(1) };
+ } else {
+ return { type: packetslist[type] };
+ }
+ }
- var bytesNeeded = Math.ceil(width / 26) | 0;
- var bitsLeft = width % 26;
+ var asArray = new Uint8Array(data);
+ var type = asArray[0];
+ var rest = sliceBuffer(data, 1);
+ if (Blob && binaryType === 'blob') {
+ rest = new Blob([rest]);
+ }
+ return { type: packetslist[type], data: rest };
+};
- // Extend the buffer with leading zeroes
- this._expand(bytesNeeded);
+function tryDecode(data) {
+ try {
+ data = utf8.decode(data, { strict: false });
+ } catch (e) {
+ return false;
+ }
+ return data;
+}
- if (bitsLeft > 0) {
- bytesNeeded--;
- }
+/**
+ * Decodes a packet encoded in a base64 string
+ *
+ * @param {String} base64 encoded message
+ * @return {Object} with `type` and `data` (if any)
+ */
- // Handle complete words
- for (var i = 0; i < bytesNeeded; i++) {
- this.words[i] = ~this.words[i] & 0x3ffffff;
- }
+exports.decodeBase64Packet = function(msg, binaryType) {
+ var type = packetslist[msg.charAt(0)];
+ if (!base64encoder) {
+ return { type: type, data: { base64: true, data: msg.substr(1) } };
+ }
- // Handle the residue
- if (bitsLeft > 0) {
- this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
- }
+ var data = base64encoder.decode(msg.substr(1));
- // And remove leading zeroes
- return this.strip();
- };
+ if (binaryType === 'blob' && Blob) {
+ data = new Blob([data]);
+ }
- BN.prototype.notn = function notn (width) {
- return this.clone().inotn(width);
- };
+ return { type: type, data: data };
+};
- // Set `bit` of `this`
- BN.prototype.setn = function setn (bit, val) {
- assert(typeof bit === 'number' && bit >= 0);
+/**
+ * Encodes multiple messages (payload).
+ *
+ * :data
+ *
+ * Example:
+ *
+ * 11:hello world2:hi
+ *
+ * If any contents are binary, they will be encoded as base64 strings. Base64
+ * encoded strings are marked with a b before the length specifier
+ *
+ * @param {Array} packets
+ * @api private
+ */
- var off = (bit / 26) | 0;
- var wbit = bit % 26;
+exports.encodePayload = function (packets, supportsBinary, callback) {
+ if (typeof supportsBinary === 'function') {
+ callback = supportsBinary;
+ supportsBinary = null;
+ }
- this._expand(off + 1);
+ var isBinary = hasBinary(packets);
- if (val) {
- this.words[off] = this.words[off] | (1 << wbit);
- } else {
- this.words[off] = this.words[off] & ~(1 << wbit);
+ if (supportsBinary && isBinary) {
+ if (Blob && !dontSendBlobs) {
+ return exports.encodePayloadAsBlob(packets, callback);
}
- return this.strip();
- };
+ return exports.encodePayloadAsArrayBuffer(packets, callback);
+ }
- // Add `num` to `this` in-place
- BN.prototype.iadd = function iadd (num) {
- var r;
+ if (!packets.length) {
+ return callback('0:');
+ }
- // negative + positive
- if (this.negative !== 0 && num.negative === 0) {
- this.negative = 0;
- r = this.isub(num);
- this.negative ^= 1;
- return this._normSign();
+ function setLengthHeader(message) {
+ return message.length + ':' + message;
+ }
- // positive + negative
- } else if (this.negative === 0 && num.negative !== 0) {
- num.negative = 0;
- r = this.isub(num);
- num.negative = 1;
- return r._normSign();
- }
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
+ doneCallback(null, setLengthHeader(message));
+ });
+ }
- // a.length > b.length
- var a, b;
- if (this.length > num.length) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
- }
+ map(packets, encodeOne, function(err, results) {
+ return callback(results.join(''));
+ });
+};
- 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;
- }
+/**
+ * Async array map using after
+ */
- 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];
- }
- }
+function map(ary, each, done) {
+ var result = new Array(ary.length);
+ var next = after(ary.length, done);
- return this;
+ var eachWithIndex = function(i, el, cb) {
+ each(el, function(error, msg) {
+ result[i] = msg;
+ cb(error, result);
+ });
};
- // 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;
- }
+ for (var i = 0; i < ary.length; i++) {
+ eachWithIndex(i, ary[i], next);
+ }
+}
- if (this.length > num.length) return this.clone().iadd(num);
+/*
+ * Decodes data when a payload is maybe expected. Possible binary contents are
+ * decoded from their base64 representation
+ *
+ * @param {String} data, callback method
+ * @api public
+ */
- return num.clone().iadd(this);
- };
+exports.decodePayload = function (data, binaryType, callback) {
+ if (typeof data !== 'string') {
+ return exports.decodePayloadAsBinary(data, binaryType, callback);
+ }
- // 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();
+ if (typeof binaryType === 'function') {
+ callback = binaryType;
+ binaryType = null;
+ }
- // -this - num = -(this + num)
- } else if (this.negative !== 0) {
- this.negative = 0;
- this.iadd(num);
- this.negative = 1;
- return this._normSign();
- }
+ var packet;
+ if (data === '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
- // At this point both numbers are positive
- var cmp = this.cmp(num);
+ var length = '', n, msg;
- // Optimization - zeroify
- if (cmp === 0) {
- this.negative = 0;
- this.length = 1;
- this.words[0] = 0;
- return this;
- }
+ for (var i = 0, l = data.length; i < l; i++) {
+ var chr = data.charAt(i);
- // a > b
- var a, b;
- if (cmp > 0) {
- a = this;
- b = num;
- } else {
- a = num;
- b = this;
+ if (chr !== ':') {
+ length += chr;
+ continue;
}
- 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;
+ if (length === '' || (length != (n = Number(length)))) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
}
- for (; carry !== 0 && i < a.length; i++) {
- r = (a.words[i] | 0) + carry;
- carry = r >> 26;
- this.words[i] = r & 0x3ffffff;
+
+ msg = data.substr(i + 1, n);
+
+ if (length != msg.length) {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
}
- // Copy rest of the words
- if (carry === 0 && i < a.length && a !== this) {
- for (; i < a.length; i++) {
- this.words[i] = a.words[i];
+ if (msg.length) {
+ packet = exports.decodePacket(msg, binaryType, false);
+
+ if (err.type === packet.type && err.data === packet.data) {
+ // parser error in individual packet - ignoring payload
+ return callback(err, 0, 1);
}
+
+ var ret = callback(packet, i + n, l);
+ if (false === ret) return;
}
- this.length = Math.max(this.length, i);
+ // advance cursor
+ i += n;
+ length = '';
+ }
- if (a !== this) {
- this.negative = 1;
- }
+ if (length !== '') {
+ // parser error - ignoring payload
+ return callback(err, 0, 1);
+ }
- return this.strip();
- };
+};
- // Subtract `num` from `this`
- BN.prototype.sub = function sub (num) {
- return this.clone().isub(num);
- };
+/**
+ * Encodes multiple messages (payload) as binary.
+ *
+ * <1 = binary, 0 = string>[...]
+ *
+ * Example:
+ * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
+ *
+ * @param {Array} packets
+ * @return {ArrayBuffer} encoded payload
+ * @api private
+ */
- 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;
+exports.encodePayloadAsArrayBuffer = function(packets, callback) {
+ if (!packets.length) {
+ return callback(new ArrayBuffer(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;
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, true, true, function(data) {
+ return doneCallback(null, data);
+ });
+ }
- var lo = r & 0x3ffffff;
- var carry = (r / 0x4000000) | 0;
- out.words[0] = lo;
+ map(packets, encodeOne, function(err, encodedPackets) {
+ var totalLength = encodedPackets.reduce(function(acc, p) {
+ var len;
+ if (typeof p === 'string'){
+ len = p.length;
+ } else {
+ len = p.byteLength;
+ }
+ return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
+ }, 0);
- 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;
+ var resultArray = new Uint8Array(totalLength);
+
+ var bufferIndex = 0;
+ encodedPackets.forEach(function(p) {
+ var isString = typeof p === 'string';
+ var ab = p;
+ if (isString) {
+ var view = new Uint8Array(p.length);
+ for (var i = 0; i < p.length; i++) {
+ view[i] = p.charCodeAt(i);
+ }
+ ab = view.buffer;
}
- out.words[k] = rword | 0;
- carry = ncarry | 0;
+
+ if (isString) { // not true binary
+ resultArray[bufferIndex++] = 0;
+ } else { // true binary
+ resultArray[bufferIndex++] = 1;
+ }
+
+ var lenStr = ab.byteLength.toString();
+ for (var i = 0; i < lenStr.length; i++) {
+ resultArray[bufferIndex++] = parseInt(lenStr[i]);
+ }
+ resultArray[bufferIndex++] = 255;
+
+ var view = new Uint8Array(ab);
+ for (var i = 0; i < view.length; i++) {
+ resultArray[bufferIndex++] = view[i];
+ }
+ });
+
+ return callback(resultArray.buffer);
+ });
+};
+
+/**
+ * Encode as Blob
+ */
+
+exports.encodePayloadAsBlob = function(packets, callback) {
+ function encodeOne(packet, doneCallback) {
+ exports.encodePacket(packet, true, true, function(encoded) {
+ var binaryIdentifier = new Uint8Array(1);
+ binaryIdentifier[0] = 1;
+ if (typeof encoded === 'string') {
+ var view = new Uint8Array(encoded.length);
+ for (var i = 0; i < encoded.length; i++) {
+ view[i] = encoded.charCodeAt(i);
+ }
+ encoded = view.buffer;
+ binaryIdentifier[0] = 0;
+ }
+
+ var len = (encoded instanceof ArrayBuffer)
+ ? encoded.byteLength
+ : encoded.size;
+
+ var lenStr = len.toString();
+ var lengthAry = new Uint8Array(lenStr.length + 1);
+ for (var i = 0; i < lenStr.length; i++) {
+ lengthAry[i] = parseInt(lenStr[i]);
+ }
+ lengthAry[lenStr.length] = 255;
+
+ if (Blob) {
+ var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
+ doneCallback(null, blob);
+ }
+ });
+ }
+
+ map(packets, encodeOne, function(err, results) {
+ return callback(new Blob(results));
+ });
+};
+
+/*
+ * Decodes data when a payload is maybe expected. Strings are decoded by
+ * interpreting each byte as a key code for entries marked to start with 0. See
+ * description of encodePayloadAsBinary
+ *
+ * @param {ArrayBuffer} data, callback method
+ * @api public
+ */
+
+exports.decodePayloadAsBinary = function (data, binaryType, callback) {
+ if (typeof binaryType === 'function') {
+ callback = binaryType;
+ binaryType = null;
+ }
+
+ var bufferTail = data;
+ var buffers = [];
+
+ while (bufferTail.byteLength > 0) {
+ var tailArray = new Uint8Array(bufferTail);
+ var isString = tailArray[0] === 0;
+ var msgLength = '';
+
+ for (var i = 1; ; i++) {
+ if (tailArray[i] === 255) break;
+
+ // 310 = char length of Number.MAX_VALUE
+ if (msgLength.length > 310) {
+ return callback(err, 0, 1);
+ }
+
+ msgLength += tailArray[i];
}
- if (carry !== 0) {
- out.words[k] = carry | 0;
- } else {
- out.length--;
+
+ bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
+ msgLength = parseInt(msgLength);
+
+ var msg = sliceBuffer(bufferTail, 0, msgLength);
+ if (isString) {
+ try {
+ msg = String.fromCharCode.apply(null, new Uint8Array(msg));
+ } catch (e) {
+ // iPhone Safari doesn't let you apply to typed arrays
+ var typed = new Uint8Array(msg);
+ msg = '';
+ for (var i = 0; i < typed.length; i++) {
+ msg += String.fromCharCode(typed[i]);
+ }
+ }
}
- return out.strip();
+ buffers.push(msg);
+ bufferTail = sliceBuffer(bufferTail, msgLength);
}
- // 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;
+ var total = buffers.length;
+ buffers.forEach(function(buffer, i) {
+ callback(exports.decodePacket(buffer, binaryType, true), i, total);
+ });
+};
- 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);
+/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
- // 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;
- }
+/***/ }),
+/* 26 */
+/***/ (function(module, exports, __webpack_require__) {
- if (carry !== 0) {
- this.words[i] = carry;
- this.length++;
- }
-
- return this;
- };
-
- BN.prototype.muln = function muln (num) {
- return this.clone().imuln(num);
- };
-
- // `this` * `this`
- BN.prototype.sqr = function sqr () {
- return this.mul(this);
- };
-
- // `this` * `this` in-place
- BN.prototype.isqr = function isqr () {
- return this.imul(this.clone());
- };
-
- // Math.pow(`this`, `num`)
- BN.prototype.pow = function pow (num) {
- var w = toBitArray(num);
- if (w.length === 0) return new BN(1);
-
- // Skip leading zeroes
- var res = this;
- for (var i = 0; i < w.length; i++, res = res.sqr()) {
- if (w[i] !== 0) break;
- }
-
- if (++i < w.length) {
- for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
- if (w[i] === 0) continue;
-
- res = res.mul(q);
- }
- }
-
- return res;
- };
-
- // Shift-left in-place
- BN.prototype.iushln = function iushln (bits) {
- assert(typeof bits === 'number' && bits >= 0);
- var r = bits % 26;
- var s = (bits - r) / 26;
- var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
- var i;
-
- if (r !== 0) {
- var carry = 0;
-
- for (i = 0; i < this.length; i++) {
- var newCarry = this.words[i] & carryMask;
- var c = ((this.words[i] | 0) - newCarry) << r;
- this.words[i] = c | carry;
- carry = newCarry >>> (26 - r);
- }
-
- if (carry) {
- this.words[i] = carry;
- this.length++;
- }
- }
-
- if (s !== 0) {
- for (i = this.length - 1; i >= 0; i--) {
- this.words[i + s] = this.words[i];
- }
-
- for (i = 0; i < s; i++) {
- this.words[i] = 0;
- }
-
- this.length += s;
- }
-
- return this.strip();
- };
-
- BN.prototype.ishln = function ishln (bits) {
- // TODO(indutny): implement me
- assert(this.negative === 0);
- return this.iushln(bits);
- };
-
- // Shift-right in-place
- // NOTE: `hint` is a lowest bit before trailing zeroes
- // NOTE: if `extended` is present - it will be filled with destroyed bits
- BN.prototype.iushrn = function iushrn (bits, hint, extended) {
- assert(typeof bits === 'number' && bits >= 0);
- var h;
- if (hint) {
- h = (hint - (hint % 26)) / 26;
- } else {
- h = 0;
- }
-
- var r = bits % 26;
- var s = Math.min((bits - r) / 26, this.length);
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
- var maskedWords = extended;
-
- h -= s;
- h = Math.max(0, h);
-
- // Extended mode, copy masked part
- if (maskedWords) {
- for (var i = 0; i < s; i++) {
- maskedWords.words[i] = this.words[i];
- }
- maskedWords.length = s;
- }
-
- if (s === 0) {
- // No-op, we should not move anything at all
- } else if (this.length > s) {
- this.length -= s;
- for (i = 0; i < this.length; i++) {
- this.words[i] = this.words[i + s];
- }
- } else {
- this.words[0] = 0;
- this.length = 1;
- }
-
- var carry = 0;
- for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
- var word = this.words[i] | 0;
- this.words[i] = (carry << (26 - r)) | (word >>> r);
- carry = word & mask;
- }
-
- // Push carried bits as a mask
- if (maskedWords && carry !== 0) {
- maskedWords.words[maskedWords.length++] = carry;
- }
-
- if (this.length === 0) {
- this.words[0] = 0;
- this.length = 1;
- }
-
- return this.strip();
- };
-
- BN.prototype.ishrn = function ishrn (bits, hint, extended) {
- // TODO(indutny): implement me
- assert(this.negative === 0);
- return this.iushrn(bits, hint, extended);
- };
-
- // Shift-left
- BN.prototype.shln = function shln (bits) {
- return this.clone().ishln(bits);
- };
-
- BN.prototype.ushln = function ushln (bits) {
- return this.clone().iushln(bits);
- };
-
- // Shift-right
- BN.prototype.shrn = function shrn (bits) {
- return this.clone().ishrn(bits);
- };
-
- BN.prototype.ushrn = function ushrn (bits) {
- return this.clone().iushrn(bits);
- };
-
- // Test if n bit is set
- BN.prototype.testn = function testn (bit) {
- assert(typeof bit === 'number' && bit >= 0);
- var r = bit % 26;
- var s = (bit - r) / 26;
- var q = 1 << r;
-
- // Fast case: bit is much higher than all existing words
- if (this.length <= s) return false;
-
- // Check bit and return
- var w = this.words[s];
-
- return !!(w & q);
- };
-
- // Return only lowers bits of number (in-place)
- BN.prototype.imaskn = function imaskn (bits) {
- assert(typeof bits === 'number' && bits >= 0);
- var r = bits % 26;
- var s = (bits - r) / 26;
-
- assert(this.negative === 0, 'imaskn works only with positive numbers');
-
- if (this.length <= s) {
- return this;
- }
-
- if (r !== 0) {
- s++;
- }
- this.length = Math.min(s, this.length);
-
- if (r !== 0) {
- var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
- this.words[this.length - 1] &= mask;
- }
-
- return this.strip();
- };
-
- // Return only lowers bits of number
- BN.prototype.maskn = function maskn (bits) {
- return this.clone().imaskn(bits);
- };
-
- // Add plain number `num` to `this`
- BN.prototype.iaddn = function iaddn (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
- if (num < 0) return this.isubn(-num);
-
- // Possible sign change
- if (this.negative !== 0) {
- if (this.length === 1 && (this.words[0] | 0) < num) {
- this.words[0] = num - (this.words[0] | 0);
- this.negative = 0;
- return this;
- }
-
- this.negative = 0;
- this.isubn(num);
- this.negative = 1;
- return this;
- }
-
- // Add without checks
- return this._iaddn(num);
- };
-
- BN.prototype._iaddn = function _iaddn (num) {
- this.words[0] += num;
-
- // Carry
- for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
- this.words[i] -= 0x4000000;
- if (i === this.length - 1) {
- this.words[i + 1] = 1;
- } else {
- this.words[i + 1]++;
- }
- }
- this.length = Math.max(this.length, i + 1);
-
- return this;
- };
-
- // Subtract plain number `num` from `this`
- BN.prototype.isubn = function isubn (num) {
- assert(typeof num === 'number');
- assert(num < 0x4000000);
- if (num < 0) return this.iaddn(-num);
-
- if (this.negative !== 0) {
- this.negative = 0;
- this.iaddn(num);
- this.negative = 1;
- return this;
- }
-
- this.words[0] -= num;
-
- if (this.length === 1 && this.words[0] < 0) {
- this.words[0] = -this.words[0];
- this.negative = 1;
- } else {
- // Carry
- for (var i = 0; i < this.length && this.words[i] < 0; i++) {
- this.words[i] += 0x4000000;
- this.words[i + 1] -= 1;
- }
- }
-
- return this.strip();
- };
-
- BN.prototype.addn = function addn (num) {
- return this.clone().iaddn(num);
- };
-
- BN.prototype.subn = function subn (num) {
- return this.clone().isubn(num);
- };
-
- BN.prototype.iabs = function iabs () {
- this.negative = 0;
-
- return this;
- };
-
- BN.prototype.abs = function abs () {
- return this.clone().iabs();
- };
-
- BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
- var len = num.length + shift;
- var i;
-
- this._expand(len);
-
- var w;
- var carry = 0;
- for (i = 0; i < num.length; i++) {
- w = (this.words[i + shift] | 0) + carry;
- var right = (num.words[i] | 0) * mul;
- w -= right & 0x3ffffff;
- carry = (w >> 26) - ((right / 0x4000000) | 0);
- this.words[i + shift] = w & 0x3ffffff;
- }
- for (; i < this.length - shift; i++) {
- w = (this.words[i + shift] | 0) + carry;
- carry = w >> 26;
- this.words[i + shift] = w & 0x3ffffff;
- }
-
- if (carry === 0) return this.strip();
-
- // Subtraction overflow
- assert(carry === -1);
- carry = 0;
- for (i = 0; i < this.length; i++) {
- w = -(this.words[i] | 0) + carry;
- carry = w >> 26;
- this.words[i] = w & 0x3ffffff;
- }
- this.negative = 1;
-
- return this.strip();
- };
-
- BN.prototype._wordDiv = function _wordDiv (num, mode) {
- var shift = this.length - num.length;
-
- var a = this.clone();
- var b = num;
-
- // Normalize
- var bhi = b.words[b.length - 1] | 0;
- var bhiBits = this._countBits(bhi);
- shift = 26 - bhiBits;
- if (shift !== 0) {
- b = b.ushln(shift);
- a.iushln(shift);
- bhi = b.words[b.length - 1] | 0;
- }
-
- // Initialize quotient
- var m = a.length - b.length;
- var q;
-
- if (mode !== 'mod') {
- q = new BN(null);
- q.length = m + 1;
- q.words = new Array(q.length);
- for (var i = 0; i < q.length; i++) {
- q.words[i] = 0;
- }
- }
-
- var diff = a.clone()._ishlnsubmul(b, 1, m);
- if (diff.negative === 0) {
- a = diff;
- if (q) {
- q.words[m] = 1;
- }
- }
-
- for (var j = m - 1; j >= 0; j--) {
- var qj = (a.words[b.length + j] | 0) * 0x4000000 +
- (a.words[b.length + j - 1] | 0);
-
- // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
- // (0x7ffffff)
- qj = Math.min((qj / bhi) | 0, 0x3ffffff);
-
- a._ishlnsubmul(b, qj, j);
- while (a.negative !== 0) {
- qj--;
- a.negative = 0;
- a._ishlnsubmul(b, 1, j);
- if (!a.isZero()) {
- a.negative ^= 1;
- }
- }
- if (q) {
- q.words[j] = qj;
- }
- }
- if (q) {
- q.strip();
- }
- a.strip();
-
- // Denormalize
- if (mode !== 'div' && shift !== 0) {
- a.iushrn(shift);
- }
-
- return {
- div: q || null,
- mod: a
- };
- };
-
- // NOTE: 1) `mode` can be set to `mod` to request mod only,
- // to `div` to request div only, or be absent to
- // request both div & mod
- // 2) `positive` is true if unsigned mod is requested
- BN.prototype.divmod = function divmod (num, mode, positive) {
- assert(!num.isZero());
-
- if (this.isZero()) {
- return {
- div: new BN(0),
- mod: new BN(0)
- };
- }
-
- var div, mod, res;
- if (this.negative !== 0 && num.negative === 0) {
- res = this.neg().divmod(num, mode);
-
- if (mode !== 'mod') {
- div = res.div.neg();
- }
-
- if (mode !== 'div') {
- mod = res.mod.neg();
- if (positive && mod.negative !== 0) {
- mod.iadd(num);
- }
- }
-
- return {
- div: div,
- mod: mod
- };
- }
-
- if (this.negative === 0 && num.negative !== 0) {
- res = this.divmod(num.neg(), mode);
-
- if (mode !== 'mod') {
- div = res.div.neg();
- }
-
- return {
- div: div,
- mod: res.mod
- };
- }
-
- if ((this.negative & num.negative) !== 0) {
- res = this.neg().divmod(num.neg(), mode);
-
- if (mode !== 'div') {
- mod = res.mod.neg();
- if (positive && mod.negative !== 0) {
- mod.isub(num);
- }
- }
-
- return {
- div: res.div,
- mod: mod
- };
- }
-
- // Both numbers are positive at this point
-
- // Strip both numbers to approximate shift value
- if (num.length > this.length || this.cmp(num) < 0) {
- return {
- div: new BN(0),
- mod: this
- };
- }
-
- // Very short reduction
- if (num.length === 1) {
- if (mode === 'div') {
- return {
- div: this.divn(num.words[0]),
- mod: null
- };
- }
-
- if (mode === 'mod') {
- return {
- div: null,
- mod: new BN(this.modn(num.words[0]))
- };
- }
-
- return {
- div: this.divn(num.words[0]),
- mod: new BN(this.modn(num.words[0]))
- };
- }
-
- return this._wordDiv(num, mode);
- };
-
- // Find `this` / `num`
- BN.prototype.div = function div (num) {
- return this.divmod(num, 'div', false).div;
- };
-
- // Find `this` % `num`
- BN.prototype.mod = function mod (num) {
- return this.divmod(num, 'mod', false).mod;
- };
-
- BN.prototype.umod = function umod (num) {
- return this.divmod(num, 'mod', true).mod;
- };
-
- // Find Round(`this` / `num`)
- BN.prototype.divRound = function divRound (num) {
- var dm = this.divmod(num);
-
- // Fast case - exact division
- if (dm.mod.isZero()) return dm.div;
-
- var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
-
- var half = num.ushrn(1);
- var r2 = num.andln(1);
- var cmp = mod.cmp(half);
-
- // Round down
- if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
-
- // Round up
- return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
- };
-
- BN.prototype.modn = function modn (num) {
- assert(num <= 0x3ffffff);
- var p = (1 << 26) % num;
-
- var acc = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- acc = (p * acc + (this.words[i] | 0)) % num;
- }
-
- return acc;
- };
-
- // In-place division by number
- BN.prototype.idivn = function idivn (num) {
- assert(num <= 0x3ffffff);
-
- var carry = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- var w = (this.words[i] | 0) + carry * 0x4000000;
- this.words[i] = (w / num) | 0;
- carry = w % num;
- }
-
- return this.strip();
- };
-
- BN.prototype.divn = function divn (num) {
- return this.clone().idivn(num);
- };
-
- BN.prototype.egcd = function egcd (p) {
- assert(p.negative === 0);
- assert(!p.isZero());
-
- var x = this;
- var y = p.clone();
-
- if (x.negative !== 0) {
- x = x.umod(p);
- } else {
- x = x.clone();
- }
-
- // A * x + B * y = x
- var A = new BN(1);
- var B = new BN(0);
-
- // C * x + D * y = y
- var C = new BN(0);
- var D = new BN(1);
-
- var g = 0;
-
- while (x.isEven() && y.isEven()) {
- x.iushrn(1);
- y.iushrn(1);
- ++g;
- }
-
- var yp = y.clone();
- var xp = x.clone();
-
- while (!x.isZero()) {
- for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
- if (i > 0) {
- x.iushrn(i);
- while (i-- > 0) {
- if (A.isOdd() || B.isOdd()) {
- A.iadd(yp);
- B.isub(xp);
- }
-
- A.iushrn(1);
- B.iushrn(1);
- }
- }
-
- for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
- if (j > 0) {
- y.iushrn(j);
- while (j-- > 0) {
- if (C.isOdd() || D.isOdd()) {
- C.iadd(yp);
- D.isub(xp);
- }
-
- C.iushrn(1);
- D.iushrn(1);
- }
- }
-
- if (x.cmp(y) >= 0) {
- x.isub(y);
- A.isub(C);
- B.isub(D);
- } else {
- y.isub(x);
- C.isub(A);
- D.isub(B);
- }
- }
-
- return {
- a: C,
- b: D,
- gcd: y.iushln(g)
- };
- };
-
- // This is reduced incarnation of the binary EEA
- // above, designated to invert members of the
- // _prime_ fields F(p) at a maximal speed
- BN.prototype._invmp = function _invmp (p) {
- assert(p.negative === 0);
- assert(!p.isZero());
-
- var a = this;
- var b = p.clone();
-
- if (a.negative !== 0) {
- a = a.umod(p);
- } else {
- a = a.clone();
- }
-
- var x1 = new BN(1);
- var x2 = new BN(0);
-
- var delta = b.clone();
-
- while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
- for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
- if (i > 0) {
- a.iushrn(i);
- while (i-- > 0) {
- if (x1.isOdd()) {
- x1.iadd(delta);
- }
-
- x1.iushrn(1);
- }
- }
-
- for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
- if (j > 0) {
- b.iushrn(j);
- while (j-- > 0) {
- if (x2.isOdd()) {
- x2.iadd(delta);
- }
-
- x2.iushrn(1);
- }
- }
-
- if (a.cmp(b) >= 0) {
- a.isub(b);
- x1.isub(x2);
- } else {
- b.isub(a);
- x2.isub(x1);
- }
- }
-
- var res;
- if (a.cmpn(1) === 0) {
- res = x1;
- } else {
- res = x2;
- }
-
- if (res.cmpn(0) < 0) {
- res.iadd(p);
- }
-
- return res;
- };
-
- BN.prototype.gcd = function gcd (num) {
- if (this.isZero()) return num.abs();
- if (num.isZero()) return this.abs();
-
- var a = this.clone();
- var b = num.clone();
- a.negative = 0;
- b.negative = 0;
-
- // Remove common factor of two
- for (var shift = 0; a.isEven() && b.isEven(); shift++) {
- a.iushrn(1);
- b.iushrn(1);
- }
-
- do {
- while (a.isEven()) {
- a.iushrn(1);
- }
- while (b.isEven()) {
- b.iushrn(1);
- }
-
- var r = a.cmp(b);
- if (r < 0) {
- // Swap `a` and `b` to make `a` always bigger than `b`
- var t = a;
- a = b;
- b = t;
- } else if (r === 0 || b.cmpn(1) === 0) {
- break;
- }
-
- a.isub(b);
- } while (true);
-
- return b.iushln(shift);
- };
-
- // Invert number in the field F(num)
- BN.prototype.invm = function invm (num) {
- return this.egcd(num).a.umod(num);
- };
-
- BN.prototype.isEven = function isEven () {
- return (this.words[0] & 1) === 0;
- };
-
- BN.prototype.isOdd = function isOdd () {
- return (this.words[0] & 1) === 1;
- };
-
- // And first word and num
- BN.prototype.andln = function andln (num) {
- return this.words[0] & num;
- };
-
- // Increment at the bit position in-line
- BN.prototype.bincn = function bincn (bit) {
- assert(typeof bit === 'number');
- var r = bit % 26;
- var s = (bit - r) / 26;
- var q = 1 << r;
-
- // Fast case: bit is much higher than all existing words
- if (this.length <= s) {
- this._expand(s + 1);
- this.words[s] |= q;
- return this;
- }
-
- // Add bit and propagate, if needed
- var carry = q;
- for (var i = s; carry !== 0 && i < this.length; i++) {
- var w = this.words[i] | 0;
- w += carry;
- carry = w >>> 26;
- w &= 0x3ffffff;
- this.words[i] = w;
- }
- if (carry !== 0) {
- this.words[i] = carry;
- this.length++;
- }
- return this;
- };
-
- BN.prototype.isZero = function isZero () {
- return this.length === 1 && this.words[0] === 0;
- };
-
- BN.prototype.cmpn = function cmpn (num) {
- var negative = num < 0;
-
- if (this.negative !== 0 && !negative) return -1;
- if (this.negative === 0 && negative) return 1;
-
- this.strip();
-
- var res;
- if (this.length > 1) {
- res = 1;
- } else {
- if (negative) {
- num = -num;
- }
-
- assert(num <= 0x3ffffff, 'Number is too big');
-
- var w = this.words[0] | 0;
- res = w === num ? 0 : w < num ? -1 : 1;
- }
- if (this.negative !== 0) return -res | 0;
- return res;
- };
-
- // Compare two numbers and return:
- // 1 - if `this` > `num`
- // 0 - if `this` == `num`
- // -1 - if `this` < `num`
- BN.prototype.cmp = function cmp (num) {
- if (this.negative !== 0 && num.negative === 0) return -1;
- if (this.negative === 0 && num.negative !== 0) return 1;
-
- var res = this.ucmp(num);
- if (this.negative !== 0) return -res | 0;
- return res;
- };
-
- // Unsigned comparison
- BN.prototype.ucmp = function ucmp (num) {
- // At this point both numbers have the same sign
- if (this.length > num.length) return 1;
- if (this.length < num.length) return -1;
-
- var res = 0;
- for (var i = this.length - 1; i >= 0; i--) {
- var a = this.words[i] | 0;
- var b = num.words[i] | 0;
-
- if (a === b) continue;
- if (a < b) {
- res = -1;
- } else if (a > b) {
- res = 1;
- }
- break;
- }
- return res;
- };
-
- BN.prototype.gtn = function gtn (num) {
- return this.cmpn(num) === 1;
- };
-
- BN.prototype.gt = function gt (num) {
- return this.cmp(num) === 1;
- };
-
- BN.prototype.gten = function gten (num) {
- return this.cmpn(num) >= 0;
- };
-
- BN.prototype.gte = function gte (num) {
- return this.cmp(num) >= 0;
- };
-
- BN.prototype.ltn = function ltn (num) {
- return this.cmpn(num) === -1;
- };
-
- BN.prototype.lt = function lt (num) {
- return this.cmp(num) === -1;
- };
-
- BN.prototype.lten = function lten (num) {
- return this.cmpn(num) <= 0;
- };
-
- BN.prototype.lte = function lte (num) {
- return this.cmp(num) <= 0;
- };
-
- BN.prototype.eqn = function eqn (num) {
- return this.cmpn(num) === 0;
- };
-
- BN.prototype.eq = function eq (num) {
- return this.cmp(num) === 0;
- };
-
- //
- // A reduce context, could be using montgomery or something better, depending
- // on the `m` itself.
- //
- BN.red = function red (num) {
- return new Red(num);
- };
-
- BN.prototype.toRed = function toRed (ctx) {
- assert(!this.red, 'Already a number in reduction context');
- assert(this.negative === 0, 'red works only with positives');
- return ctx.convertTo(this)._forceRed(ctx);
- };
-
- BN.prototype.fromRed = function fromRed () {
- assert(this.red, 'fromRed works only with numbers in reduction context');
- return this.red.convertFrom(this);
- };
-
- BN.prototype._forceRed = function _forceRed (ctx) {
- this.red = ctx;
- return this;
- };
-
- BN.prototype.forceRed = function forceRed (ctx) {
- assert(!this.red, 'Already a number in reduction context');
- return this._forceRed(ctx);
- };
-
- BN.prototype.redAdd = function redAdd (num) {
- assert(this.red, 'redAdd works only with red numbers');
- return this.red.add(this, num);
- };
-
- BN.prototype.redIAdd = function redIAdd (num) {
- assert(this.red, 'redIAdd works only with red numbers');
- return this.red.iadd(this, num);
- };
-
- BN.prototype.redSub = function redSub (num) {
- assert(this.red, 'redSub works only with red numbers');
- return this.red.sub(this, num);
- };
-
- BN.prototype.redISub = function redISub (num) {
- assert(this.red, 'redISub works only with red numbers');
- return this.red.isub(this, num);
- };
-
- BN.prototype.redShl = function redShl (num) {
- assert(this.red, 'redShl works only with red numbers');
- return this.red.shl(this, num);
- };
-
- BN.prototype.redMul = function redMul (num) {
- assert(this.red, 'redMul works only with red numbers');
- this.red._verify2(this, num);
- return this.red.mul(this, num);
- };
-
- BN.prototype.redIMul = function redIMul (num) {
- assert(this.red, 'redMul works only with red numbers');
- this.red._verify2(this, num);
- return this.red.imul(this, num);
- };
-
- BN.prototype.redSqr = function redSqr () {
- assert(this.red, 'redSqr works only with red numbers');
- this.red._verify1(this);
- return this.red.sqr(this);
- };
-
- BN.prototype.redISqr = function redISqr () {
- assert(this.red, 'redISqr works only with red numbers');
- this.red._verify1(this);
- return this.red.isqr(this);
- };
-
- // Square root over p
- BN.prototype.redSqrt = function redSqrt () {
- assert(this.red, 'redSqrt works only with red numbers');
- this.red._verify1(this);
- return this.red.sqrt(this);
- };
-
- BN.prototype.redInvm = function redInvm () {
- assert(this.red, 'redInvm works only with red numbers');
- this.red._verify1(this);
- return this.red.invm(this);
- };
-
- // Return negative clone of `this` % `red modulo`
- BN.prototype.redNeg = function redNeg () {
- assert(this.red, 'redNeg works only with red numbers');
- this.red._verify1(this);
- return this.red.neg(this);
- };
-
- BN.prototype.redPow = function redPow (num) {
- assert(this.red && !num.red, 'redPow(normalNum)');
- this.red._verify1(this);
- return this.red.pow(this, num);
- };
-
- // Prime numbers with efficient reduction
- var primes = {
- k256: null,
- p224: null,
- p192: null,
- p25519: null
- };
-
- // Pseudo-Mersenne prime
- function MPrime (name, p) {
- // P = 2 ^ N - K
- this.name = name;
- this.p = new BN(p, 16);
- this.n = this.p.bitLength();
- this.k = new BN(1).iushln(this.n).isub(this.p);
-
- this.tmp = this._tmp();
- }
-
- MPrime.prototype._tmp = function _tmp () {
- var tmp = new BN(null);
- tmp.words = new Array(Math.ceil(this.n / 13));
- return tmp;
- };
-
- MPrime.prototype.ireduce = function ireduce (num) {
- // Assumes that `num` is less than `P^2`
- // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
- var r = num;
- var rlen;
-
- do {
- this.split(r, this.tmp);
- r = this.imulK(r);
- r = r.iadd(this.tmp);
- rlen = r.bitLength();
- } while (rlen > this.n);
-
- var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
- if (cmp === 0) {
- r.words[0] = 0;
- r.length = 1;
- } else if (cmp > 0) {
- r.isub(this.p);
- } else {
- r.strip();
- }
-
- return r;
- };
-
- MPrime.prototype.split = function split (input, out) {
- input.iushrn(this.n, 0, out);
- };
-
- MPrime.prototype.imulK = function imulK (num) {
- return num.imul(this.k);
- };
-
- function K256 () {
- MPrime.call(
- this,
- 'k256',
- 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
- }
- inherits(K256, MPrime);
-
- K256.prototype.split = function split (input, output) {
- // 256 = 9 * 26 + 22
- var mask = 0x3fffff;
-
- var outLen = Math.min(input.length, 9);
- for (var i = 0; i < outLen; i++) {
- output.words[i] = input.words[i];
- }
- output.length = outLen;
-
- if (input.length <= 9) {
- input.words[0] = 0;
- input.length = 1;
- return;
- }
-
- // Shift by 9 limbs
- var prev = input.words[9];
- output.words[output.length++] = prev & mask;
-
- for (i = 10; i < input.length; i++) {
- var next = input.words[i] | 0;
- input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
- prev = next;
- }
- prev >>>= 22;
- input.words[i - 10] = prev;
- if (prev === 0 && input.length > 10) {
- input.length -= 10;
- } else {
- input.length -= 9;
- }
- };
-
- K256.prototype.imulK = function imulK (num) {
- // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
- num.words[num.length] = 0;
- num.words[num.length + 1] = 0;
- num.length += 2;
-
- // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
- var lo = 0;
- for (var i = 0; i < num.length; i++) {
- var w = num.words[i] | 0;
- lo += w * 0x3d1;
- num.words[i] = lo & 0x3ffffff;
- lo = w * 0x40 + ((lo / 0x4000000) | 0);
- }
-
- // Fast length reduction
- if (num.words[num.length - 1] === 0) {
- num.length--;
- if (num.words[num.length - 1] === 0) {
- num.length--;
- }
- }
- return num;
- };
-
- function P224 () {
- MPrime.call(
- this,
- 'p224',
- 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
- }
- inherits(P224, MPrime);
-
- function P192 () {
- MPrime.call(
- this,
- 'p192',
- 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
- }
- inherits(P192, MPrime);
-
- function P25519 () {
- // 2 ^ 255 - 19
- MPrime.call(
- this,
- '25519',
- '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
- }
- inherits(P25519, MPrime);
-
- P25519.prototype.imulK = function imulK (num) {
- // K = 0x13
- var carry = 0;
- for (var i = 0; i < num.length; i++) {
- var hi = (num.words[i] | 0) * 0x13 + carry;
- var lo = hi & 0x3ffffff;
- hi >>>= 26;
-
- num.words[i] = lo;
- carry = hi;
- }
- if (carry !== 0) {
- num.words[num.length++] = carry;
- }
- return num;
- };
-
- // Exported mostly for testing purposes, use plain name instead
- BN._prime = function prime (name) {
- // Cached version of prime
- if (primes[name]) return primes[name];
-
- var prime;
- if (name === 'k256') {
- prime = new K256();
- } else if (name === 'p224') {
- prime = new P224();
- } else if (name === 'p192') {
- prime = new P192();
- } else if (name === 'p25519') {
- prime = new P25519();
- } else {
- throw new Error('Unknown prime ' + name);
- }
- primes[name] = prime;
-
- return prime;
- };
-
- //
- // Base reduction engine
- //
- function Red (m) {
- if (typeof m === 'string') {
- var prime = BN._prime(m);
- this.m = prime.p;
- this.prime = prime;
- } else {
- assert(m.gtn(1), 'modulus must be greater than 1');
- this.m = m;
- this.prime = null;
- }
- }
-
- Red.prototype._verify1 = function _verify1 (a) {
- assert(a.negative === 0, 'red works only with positives');
- assert(a.red, 'red works only with red numbers');
- };
-
- Red.prototype._verify2 = function _verify2 (a, b) {
- assert((a.negative | b.negative) === 0, 'red works only with positives');
- assert(a.red && a.red === b.red,
- 'red works only with red numbers');
- };
-
- Red.prototype.imod = function imod (a) {
- if (this.prime) return this.prime.ireduce(a)._forceRed(this);
- return a.umod(this.m)._forceRed(this);
- };
-
- Red.prototype.neg = function neg (a) {
- if (a.isZero()) {
- return a.clone();
- }
-
- return this.m.sub(a)._forceRed(this);
- };
-
- Red.prototype.add = function add (a, b) {
- this._verify2(a, b);
-
- var res = a.add(b);
- if (res.cmp(this.m) >= 0) {
- res.isub(this.m);
- }
- return res._forceRed(this);
- };
-
- Red.prototype.iadd = function iadd (a, b) {
- this._verify2(a, b);
-
- var res = a.iadd(b);
- if (res.cmp(this.m) >= 0) {
- res.isub(this.m);
- }
- return res;
- };
-
- Red.prototype.sub = function sub (a, b) {
- this._verify2(a, b);
-
- var res = a.sub(b);
- if (res.cmpn(0) < 0) {
- res.iadd(this.m);
- }
- return res._forceRed(this);
- };
-
- Red.prototype.isub = function isub (a, b) {
- this._verify2(a, b);
-
- var res = a.isub(b);
- if (res.cmpn(0) < 0) {
- res.iadd(this.m);
- }
- return res;
- };
-
- Red.prototype.shl = function shl (a, num) {
- this._verify1(a);
- return this.imod(a.ushln(num));
- };
-
- Red.prototype.imul = function imul (a, b) {
- this._verify2(a, b);
- return this.imod(a.imul(b));
- };
-
- Red.prototype.mul = function mul (a, b) {
- this._verify2(a, b);
- return this.imod(a.mul(b));
- };
-
- Red.prototype.isqr = function isqr (a) {
- return this.imul(a, a.clone());
- };
-
- Red.prototype.sqr = function sqr (a) {
- return this.mul(a, a);
- };
-
- Red.prototype.sqrt = function sqrt (a) {
- if (a.isZero()) return a.clone();
-
- var mod3 = this.m.andln(3);
- assert(mod3 % 2 === 1);
-
- // Fast case
- if (mod3 === 3) {
- var pow = this.m.add(new BN(1)).iushrn(2);
- return this.pow(a, pow);
- }
-
- // Tonelli-Shanks algorithm (Totally unoptimized and slow)
- //
- // Find Q and S, that Q * 2 ^ S = (P - 1)
- var q = this.m.subn(1);
- var s = 0;
- while (!q.isZero() && q.andln(1) === 0) {
- s++;
- q.iushrn(1);
- }
- assert(!q.isZero());
-
- var one = new BN(1).toRed(this);
- var nOne = one.redNeg();
-
- // Find quadratic non-residue
- // NOTE: Max is such because of generalized Riemann hypothesis.
- var lpow = this.m.subn(1).iushrn(1);
- var z = this.m.bitLength();
- z = new BN(2 * z * z).toRed(this);
-
- while (this.pow(z, lpow).cmp(nOne) !== 0) {
- z.redIAdd(nOne);
- }
-
- var c = this.pow(z, q);
- var r = this.pow(a, q.addn(1).iushrn(1));
- var t = this.pow(a, q);
- var m = s;
- while (t.cmp(one) !== 0) {
- var tmp = t;
- for (var i = 0; tmp.cmp(one) !== 0; i++) {
- tmp = tmp.redSqr();
- }
- assert(i < m);
- var b = this.pow(c, new BN(1).iushln(m - i - 1));
-
- r = r.redMul(b);
- c = b.redSqr();
- t = t.redMul(c);
- m = i;
- }
-
- return r;
- };
-
- Red.prototype.invm = function invm (a) {
- var inv = a._invmp(this.m);
- if (inv.negative !== 0) {
- inv.negative = 0;
- return this.imod(inv).redNeg();
- } else {
- return this.imod(inv);
- }
- };
-
- Red.prototype.pow = function pow (a, num) {
- if (num.isZero()) return new BN(1).toRed(this);
- if (num.cmpn(1) === 0) return a.clone();
-
- var windowSize = 4;
- var wnd = new Array(1 << windowSize);
- wnd[0] = new BN(1).toRed(this);
- wnd[1] = a;
- for (var i = 2; i < wnd.length; i++) {
- wnd[i] = this.mul(wnd[i - 1], a);
- }
-
- var res = wnd[0];
- var current = 0;
- var currentLen = 0;
- var start = num.bitLength() % 26;
- if (start === 0) {
- start = 26;
- }
-
- for (i = num.length - 1; i >= 0; i--) {
- var word = num.words[i];
- for (var j = start - 1; j >= 0; j--) {
- var bit = (word >> j) & 1;
- if (res !== wnd[0]) {
- res = this.sqr(res);
- }
-
- if (bit === 0 && current === 0) {
- currentLen = 0;
- continue;
- }
-
- current <<= 1;
- current |= bit;
- currentLen++;
- if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
-
- res = this.mul(res, wnd[current]);
- currentLen = 0;
- current = 0;
- }
- start = 26;
- }
-
- return res;
- };
-
- Red.prototype.convertTo = function convertTo (num) {
- var r = num.umod(this.m);
-
- return r === num ? r.clone() : r;
- };
-
- Red.prototype.convertFrom = function convertFrom (num) {
- var res = num.clone();
- res.red = null;
- return res;
- };
-
- //
- // Montgomery method engine
- //
-
- BN.mont = function mont (num) {
- return new Mont(num);
- };
-
- function Mont (m) {
- Red.call(this, m);
-
- this.shift = this.m.bitLength();
- if (this.shift % 26 !== 0) {
- this.shift += 26 - (this.shift % 26);
- }
-
- this.r = new BN(1).iushln(this.shift);
- this.r2 = this.imod(this.r.sqr());
- this.rinv = this.r._invmp(this.m);
-
- this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
- this.minv = this.minv.umod(this.r);
- this.minv = this.r.sub(this.minv);
- }
- inherits(Mont, Red);
-
- Mont.prototype.convertTo = function convertTo (num) {
- return this.imod(num.ushln(this.shift));
- };
-
- Mont.prototype.convertFrom = function convertFrom (num) {
- var r = this.imod(num.mul(this.rinv));
- r.red = null;
- return r;
- };
-
- Mont.prototype.imul = function imul (a, b) {
- if (a.isZero() || b.isZero()) {
- a.words[0] = 0;
- a.length = 1;
- return a;
- }
-
- var t = a.imul(b);
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
- var u = t.isub(c).iushrn(this.shift);
- var res = u;
-
- if (u.cmp(this.m) >= 0) {
- res = u.isub(this.m);
- } else if (u.cmpn(0) < 0) {
- res = u.iadd(this.m);
- }
-
- return res._forceRed(this);
- };
-
- Mont.prototype.mul = function mul (a, b) {
- if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
-
- var t = a.mul(b);
- var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
- var u = t.isub(c).iushrn(this.shift);
- var res = u;
- if (u.cmp(this.m) >= 0) {
- res = u.isub(this.m);
- } else if (u.cmpn(0) < 0) {
- res = u.iadd(this.m);
- }
-
- return res._forceRed(this);
- };
-
- Mont.prototype.invm = function invm (a) {
- // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
- var res = this.imod(a._invmp(this.m).mul(this.r2));
- return res._forceRed(this);
- };
-})(typeof module === 'undefined' || module, this);
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(59)(module)))
-
-/***/ }),
-/* 10 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-var elliptic = exports;
-
-elliptic.version = __webpack_require__(345).version;
-elliptic.utils = __webpack_require__(346);
-elliptic.rand = __webpack_require__(347);
-elliptic.curve = __webpack_require__(66);
-elliptic.curves = __webpack_require__(353);
-
-// Protocols
-elliptic.ec = __webpack_require__(361);
-elliptic.eddsa = __webpack_require__(365);
-
-
-/***/ }),
-/* 11 */
-/***/ (function(module, exports) {
-
-// shim for using process in browser
-var process = module.exports = {};
-
-// cached from whatever global is present so that test runners that stub it
-// don't break things. But we need to wrap it in a try catch in case it is
-// wrapped in strict mode code which doesn't define any globals. It's inside a
-// function because try/catches deoptimize in certain engines.
-
-var cachedSetTimeout;
-var cachedClearTimeout;
-
-function defaultSetTimout() {
- throw new Error('setTimeout has not been defined');
-}
-function defaultClearTimeout () {
- throw new Error('clearTimeout has not been defined');
-}
-(function () {
- try {
- if (typeof setTimeout === 'function') {
- cachedSetTimeout = setTimeout;
- } else {
- cachedSetTimeout = defaultSetTimout;
- }
- } catch (e) {
- cachedSetTimeout = defaultSetTimout;
- }
- try {
- if (typeof clearTimeout === 'function') {
- cachedClearTimeout = clearTimeout;
- } else {
- cachedClearTimeout = defaultClearTimeout;
- }
- } catch (e) {
- cachedClearTimeout = defaultClearTimeout;
- }
-} ())
-function runTimeout(fun) {
- if (cachedSetTimeout === setTimeout) {
- //normal enviroments in sane situations
- return setTimeout(fun, 0);
- }
- // if setTimeout wasn't available but was latter defined
- if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
- cachedSetTimeout = setTimeout;
- return setTimeout(fun, 0);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedSetTimeout(fun, 0);
- } catch(e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedSetTimeout.call(null, fun, 0);
- } catch(e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error
- return cachedSetTimeout.call(this, fun, 0);
- }
- }
-
-
-}
-function runClearTimeout(marker) {
- if (cachedClearTimeout === clearTimeout) {
- //normal enviroments in sane situations
- return clearTimeout(marker);
- }
- // if clearTimeout wasn't available but was latter defined
- if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
- cachedClearTimeout = clearTimeout;
- return clearTimeout(marker);
- }
- try {
- // when when somebody has screwed with setTimeout but no I.E. maddness
- return cachedClearTimeout(marker);
- } catch (e){
- try {
- // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
- return cachedClearTimeout.call(null, marker);
- } catch (e){
- // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error.
- // Some versions of I.E. have different rules for clearTimeout vs setTimeout
- return cachedClearTimeout.call(this, marker);
- }
- }
-
-
-
-}
-var queue = [];
-var draining = false;
-var currentQueue;
-var queueIndex = -1;
-
-function cleanUpNextTick() {
- if (!draining || !currentQueue) {
- return;
- }
- draining = false;
- if (currentQueue.length) {
- queue = currentQueue.concat(queue);
- } else {
- queueIndex = -1;
- }
- if (queue.length) {
- drainQueue();
- }
-}
-
-function drainQueue() {
- if (draining) {
- return;
- }
- var timeout = runTimeout(cleanUpNextTick);
- draining = true;
-
- var len = queue.length;
- while(len) {
- currentQueue = queue;
- queue = [];
- while (++queueIndex < len) {
- if (currentQueue) {
- currentQueue[queueIndex].run();
- }
- }
- queueIndex = -1;
- len = queue.length;
- }
- currentQueue = null;
- draining = false;
- runClearTimeout(timeout);
-}
-
-process.nextTick = function (fun) {
- var args = new Array(arguments.length - 1);
- if (arguments.length > 1) {
- for (var i = 1; i < arguments.length; i++) {
- args[i - 1] = arguments[i];
- }
- }
- queue.push(new Item(fun, args));
- if (queue.length === 1 && !draining) {
- runTimeout(drainQueue);
- }
-};
-
-// v8 likes predictible objects
-function Item(fun, array) {
- this.fun = fun;
- this.array = array;
-}
-Item.prototype.run = function () {
- this.fun.apply(null, this.array);
-};
-process.title = 'browser';
-process.browser = true;
-process.env = {};
-process.argv = [];
-process.version = ''; // empty string to avoid regexp issues
-process.versions = {};
-
-function noop() {}
-
-process.on = noop;
-process.addListener = noop;
-process.once = noop;
-process.off = noop;
-process.removeListener = noop;
-process.removeAllListeners = noop;
-process.emit = noop;
-process.prependListener = noop;
-process.prependOnceListener = noop;
-
-process.listeners = function (name) { return [] }
-
-process.binding = function (name) {
- throw new Error('process.binding is not supported');
-};
-
-process.cwd = function () { return '/' };
-process.chdir = function (dir) {
- throw new Error('process.chdir is not supported');
-};
-process.umask = function() { return 0; };
-
-
-/***/ }),
-/* 12 */
-/***/ (function(module, exports) {
-
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-function EventEmitter() {
- this._events = this._events || {};
- this._maxListeners = this._maxListeners || undefined;
-}
-module.exports = EventEmitter;
-
-// Backwards-compat with node 0.10.x
-EventEmitter.EventEmitter = EventEmitter;
-
-EventEmitter.prototype._events = undefined;
-EventEmitter.prototype._maxListeners = undefined;
-
-// By default EventEmitters will print a warning if more than 10 listeners are
-// added to it. This is a useful default which helps finding memory leaks.
-EventEmitter.defaultMaxListeners = 10;
-
-// Obviously not all Emitters should be limited to 10. This function allows
-// that to be increased. Set to zero for unlimited.
-EventEmitter.prototype.setMaxListeners = function(n) {
- if (!isNumber(n) || n < 0 || isNaN(n))
- throw TypeError('n must be a positive number');
- this._maxListeners = n;
- return this;
-};
-
-EventEmitter.prototype.emit = function(type) {
- var er, handler, len, args, i, listeners;
-
- if (!this._events)
- this._events = {};
-
- // If there is no 'error' event listener then throw.
- if (type === 'error') {
- if (!this._events.error ||
- (isObject(this._events.error) && !this._events.error.length)) {
- er = arguments[1];
- if (er instanceof Error) {
- throw er; // Unhandled 'error' event
- } else {
- // At least give some kind of context to the user
- var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
- err.context = er;
- throw err;
- }
- }
- }
-
- handler = this._events[type];
-
- if (isUndefined(handler))
- return false;
-
- if (isFunction(handler)) {
- switch (arguments.length) {
- // fast cases
- case 1:
- handler.call(this);
- break;
- case 2:
- handler.call(this, arguments[1]);
- break;
- case 3:
- handler.call(this, arguments[1], arguments[2]);
- break;
- // slower
- default:
- args = Array.prototype.slice.call(arguments, 1);
- handler.apply(this, args);
- }
- } else if (isObject(handler)) {
- args = Array.prototype.slice.call(arguments, 1);
- listeners = handler.slice();
- len = listeners.length;
- for (i = 0; i < len; i++)
- listeners[i].apply(this, args);
- }
-
- return true;
-};
-
-EventEmitter.prototype.addListener = function(type, listener) {
- var m;
-
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
-
- if (!this._events)
- this._events = {};
-
- // To avoid recursion in the case that type === "newListener"! Before
- // adding it to the listeners, first emit "newListener".
- if (this._events.newListener)
- this.emit('newListener', type,
- isFunction(listener.listener) ?
- listener.listener : listener);
-
- if (!this._events[type])
- // Optimize the case of one listener. Don't need the extra array object.
- this._events[type] = listener;
- else if (isObject(this._events[type]))
- // If we've already got an array, just append.
- this._events[type].push(listener);
- else
- // Adding the second element, need to change to array.
- this._events[type] = [this._events[type], listener];
-
- // Check for listener leak
- if (isObject(this._events[type]) && !this._events[type].warned) {
- if (!isUndefined(this._maxListeners)) {
- m = this._maxListeners;
- } else {
- m = EventEmitter.defaultMaxListeners;
- }
-
- if (m && m > 0 && this._events[type].length > m) {
- this._events[type].warned = true;
- console.error('(node) warning: possible EventEmitter memory ' +
- 'leak detected. %d listeners added. ' +
- 'Use emitter.setMaxListeners() to increase limit.',
- this._events[type].length);
- if (typeof console.trace === 'function') {
- // not supported in IE 10
- console.trace();
- }
- }
- }
-
- return this;
-};
-
-EventEmitter.prototype.on = EventEmitter.prototype.addListener;
-
-EventEmitter.prototype.once = function(type, listener) {
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
-
- var fired = false;
-
- function g() {
- this.removeListener(type, g);
-
- if (!fired) {
- fired = true;
- listener.apply(this, arguments);
- }
- }
-
- g.listener = listener;
- this.on(type, g);
-
- return this;
-};
-
-// emits a 'removeListener' event iff the listener was removed
-EventEmitter.prototype.removeListener = function(type, listener) {
- var list, position, length, i;
-
- if (!isFunction(listener))
- throw TypeError('listener must be a function');
-
- if (!this._events || !this._events[type])
- return this;
-
- list = this._events[type];
- length = list.length;
- position = -1;
-
- if (list === listener ||
- (isFunction(list.listener) && list.listener === listener)) {
- delete this._events[type];
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
-
- } else if (isObject(list)) {
- for (i = length; i-- > 0;) {
- if (list[i] === listener ||
- (list[i].listener && list[i].listener === listener)) {
- position = i;
- break;
- }
- }
-
- if (position < 0)
- return this;
-
- if (list.length === 1) {
- list.length = 0;
- delete this._events[type];
- } else {
- list.splice(position, 1);
- }
-
- if (this._events.removeListener)
- this.emit('removeListener', type, listener);
- }
-
- return this;
-};
-
-EventEmitter.prototype.removeAllListeners = function(type) {
- var key, listeners;
-
- if (!this._events)
- return this;
-
- // not listening for removeListener, no need to emit
- if (!this._events.removeListener) {
- if (arguments.length === 0)
- this._events = {};
- else if (this._events[type])
- delete this._events[type];
- return this;
- }
-
- // emit removeListener for all listeners on all events
- if (arguments.length === 0) {
- for (key in this._events) {
- if (key === 'removeListener') continue;
- this.removeAllListeners(key);
- }
- this.removeAllListeners('removeListener');
- this._events = {};
- return this;
- }
-
- listeners = this._events[type];
-
- if (isFunction(listeners)) {
- this.removeListener(type, listeners);
- } else if (listeners) {
- // LIFO order
- while (listeners.length)
- this.removeListener(type, listeners[listeners.length - 1]);
- }
- delete this._events[type];
-
- return this;
-};
-
-EventEmitter.prototype.listeners = function(type) {
- var ret;
- if (!this._events || !this._events[type])
- ret = [];
- else if (isFunction(this._events[type]))
- ret = [this._events[type]];
- else
- ret = this._events[type].slice();
- return ret;
-};
-
-EventEmitter.prototype.listenerCount = function(type) {
- if (this._events) {
- var evlistener = this._events[type];
-
- if (isFunction(evlistener))
- return 1;
- else if (evlistener)
- return evlistener.length;
- }
- return 0;
-};
-
-EventEmitter.listenerCount = function(emitter, type) {
- return emitter.listenerCount(type);
-};
-
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-
-function isUndefined(arg) {
- return arg === void 0;
-}
-
-
-/***/ }),
-/* 13 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-var assert = __webpack_require__(26);
-var inherits = __webpack_require__(1);
-
-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;
-
-
-/***/ }),
-/* 14 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var isObject = __webpack_require__(20);
-module.exports = function (it) {
- if (!isObject(it)) throw TypeError(it + ' is not an object!');
- return it;
-};
-
-
-/***/ }),
-/* 15 */
-/***/ (function(module, exports, __webpack_require__) {
-
-/* WEBPACK VAR INJECTION */(function(process) {/**
- * This is the web browser implementation of `debug()`.
- *
- * Expose `debug()` as the module.
- */
-
-exports = module.exports = __webpack_require__(214);
-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 = [
- '#0000CC', '#0000FF', '#0033CC', '#0033FF', '#0066CC', '#0066FF', '#0099CC',
- '#0099FF', '#00CC00', '#00CC33', '#00CC66', '#00CC99', '#00CCCC', '#00CCFF',
- '#3300CC', '#3300FF', '#3333CC', '#3333FF', '#3366CC', '#3366FF', '#3399CC',
- '#3399FF', '#33CC00', '#33CC33', '#33CC66', '#33CC99', '#33CCCC', '#33CCFF',
- '#6600CC', '#6600FF', '#6633CC', '#6633FF', '#66CC00', '#66CC33', '#9900CC',
- '#9900FF', '#9933CC', '#9933FF', '#99CC00', '#99CC33', '#CC0000', '#CC0033',
- '#CC0066', '#CC0099', '#CC00CC', '#CC00FF', '#CC3300', '#CC3333', '#CC3366',
- '#CC3399', '#CC33CC', '#CC33FF', '#CC6600', '#CC6633', '#CC9900', '#CC9933',
- '#CCCC00', '#CCCC33', '#FF0000', '#FF0033', '#FF0066', '#FF0099', '#FF00CC',
- '#FF00FF', '#FF3300', '#FF3333', '#FF3366', '#FF3399', '#FF33CC', '#FF33FF',
- '#FF6600', '#FF6633', '#FF9900', '#FF9933', '#FFCC00', '#FFCC33'
-];
-
-/**
- * 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;
- }
-
- // Internet Explorer and Edge do not support colors.
- if (typeof navigator !== 'undefined' && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) {
- return false;
- }
-
- // 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) {}
-}
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11)))
-
-/***/ }),
-/* 16 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var BigInteger = __webpack_require__(150)
-
-//addons
-__webpack_require__(278)
-
-module.exports = BigInteger
-
-/***/ }),
-/* 17 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var global = __webpack_require__(6);
-var core = __webpack_require__(5);
-var ctx = __webpack_require__(51);
-var hide = __webpack_require__(18);
-var has = __webpack_require__(22);
-var PROTOTYPE = 'prototype';
-
-var $export = function (type, name, source) {
- var IS_FORCED = type & $export.F;
- var IS_GLOBAL = type & $export.G;
- var IS_STATIC = type & $export.S;
- var IS_PROTO = type & $export.P;
- var IS_BIND = type & $export.B;
- var IS_WRAP = type & $export.W;
- var exports = IS_GLOBAL ? core : core[name] || (core[name] = {});
- var expProto = exports[PROTOTYPE];
- var target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE];
- var key, own, out;
- if (IS_GLOBAL) source = name;
- for (key in source) {
- // contains in native
- own = !IS_FORCED && target && target[key] !== undefined;
- if (own && has(exports, key)) continue;
- // export native or passed
- out = own ? target[key] : source[key];
- // prevent global pollution for namespaces
- exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
- // bind timers to global for call from export context
- : IS_BIND && own ? ctx(out, global)
- // wrap global constructors for prevent change them in library
- : IS_WRAP && target[key] == out ? (function (C) {
- var F = function (a, b, c) {
- if (this instanceof C) {
- switch (arguments.length) {
- case 0: return new C();
- case 1: return new C(a);
- case 2: return new C(a, b);
- } return new C(a, b, c);
- } return C.apply(this, arguments);
- };
- F[PROTOTYPE] = C[PROTOTYPE];
- return F;
- // make static versions for prototype methods
- })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
- // export proto methods to core.%CONSTRUCTOR%.methods.%NAME%
- if (IS_PROTO) {
- (exports.virtual || (exports.virtual = {}))[key] = out;
- // export proto methods to core.%CONSTRUCTOR%.prototype.%NAME%
- if (type & $export.R && expProto && !expProto[key]) hide(expProto, key, out);
- }
- }
-};
-// type bitmap
-$export.F = 1; // forced
-$export.G = 2; // global
-$export.S = 4; // static
-$export.P = 8; // proto
-$export.B = 16; // bind
-$export.W = 32; // wrap
-$export.U = 64; // safe
-$export.R = 128; // real proto method for `library`
-module.exports = $export;
-
-
-/***/ }),
-/* 18 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var dP = __webpack_require__(19);
-var createDesc = __webpack_require__(53);
-module.exports = __webpack_require__(21) ? function (object, key, value) {
- return dP.f(object, key, createDesc(1, value));
-} : function (object, key, value) {
- object[key] = value;
- return object;
-};
-
-
-/***/ }),
-/* 19 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var anObject = __webpack_require__(14);
-var IE8_DOM_DEFINE = __webpack_require__(106);
-var toPrimitive = __webpack_require__(71);
-var dP = Object.defineProperty;
-
-exports.f = __webpack_require__(21) ? Object.defineProperty : function defineProperty(O, P, Attributes) {
- anObject(O);
- P = toPrimitive(P, true);
- anObject(Attributes);
- if (IE8_DOM_DEFINE) try {
- return dP(O, P, Attributes);
- } catch (e) { /* empty */ }
- if ('get' in Attributes || 'set' in Attributes) throw TypeError('Accessors not supported!');
- if ('value' in Attributes) O[P] = Attributes.value;
- return O;
-};
-
-
-/***/ }),
-/* 20 */
-/***/ (function(module, exports) {
-
-module.exports = function (it) {
- return typeof it === 'object' ? it !== null : typeof it === 'function';
-};
-
-
-/***/ }),
-/* 21 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// Thank's IE8 for his funny defineProperty
-module.exports = !__webpack_require__(28)(function () {
- return Object.defineProperty({}, 'a', { get: function () { return 7; } }).a != 7;
-});
-
-
-/***/ }),
-/* 22 */
-/***/ (function(module, exports) {
-
-var hasOwnProperty = {}.hasOwnProperty;
-module.exports = function (it, key) {
- return hasOwnProperty.call(it, key);
-};
-
-
-/***/ }),
-/* 23 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var Buffer = __webpack_require__(0).Buffer
-var Transform = __webpack_require__(63).Transform
-var StringDecoder = __webpack_require__(91).StringDecoder
-var inherits = __webpack_require__(1)
-
-function CipherBase (hashMode) {
- Transform.call(this)
- this.hashMode = typeof hashMode === 'string'
- if (this.hashMode) {
- this[hashMode] = this._finalOrDigest
- } else {
- this.final = this._finalOrDigest
- }
- if (this._final) {
- this.__final = this._final
- this._final = null
- }
- this._decoder = null
- this._encoding = null
-}
-inherits(CipherBase, Transform)
-
-CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
- if (typeof data === 'string') {
- data = Buffer.from(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
- }
-
- done(err)
-}
-CipherBase.prototype._finalOrDigest = function (outputEnc) {
- var outData = this.__final() || Buffer.alloc(0)
- 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
-}
-
-module.exports = CipherBase
-
-
-/***/ }),
-/* 24 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// a duplex stream is just a stream that is both readable and writable.
-// Since JS doesn't have multiple prototypal inheritance, this class
-// prototypally inherits from Readable, and then parasitically from
-// Writable.
-
-
-
-/**/
-
-var pna = __webpack_require__(64);
-/**/
-
-/**/
-var objectKeys = Object.keys || function (obj) {
- var keys = [];
- for (var key in obj) {
- keys.push(key);
- }return keys;
-};
-/**/
-
-module.exports = Duplex;
-
-/**/
-var util = __webpack_require__(43);
-util.inherits = __webpack_require__(1);
-/**/
-
-var Readable = __webpack_require__(141);
-var Writable = __webpack_require__(90);
-
-util.inherits(Duplex, Readable);
-
-{
- // avoid scope creep, the keys array can then be collected
- 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);
-}
-
-Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._writableState.highWaterMark;
- }
-});
-
-// 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.
- pna.nextTick(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();
-
- pna.nextTick(cb, err);
-};
-
-/***/ }),
-/* 25 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-var createHash = __webpack_require__(45);
-var createHmac = __webpack_require__(285);
-
-/** @namespace hash */
-
-/** @arg {string|Buffer} data
- @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'
- @return {string|Buffer} - Buffer when resultEncoding is null, or string
-*/
-function sha1(data, resultEncoding) {
- return createHash('sha1').update(data).digest(resultEncoding);
-}
-
-/** @arg {string|Buffer} data
- @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'
- @return {string|Buffer} - Buffer when resultEncoding is null, or string
-*/
-function sha256(data, resultEncoding) {
- return createHash('sha256').update(data).digest(resultEncoding);
-}
-
-/** @arg {string|Buffer} data
- @arg {string} [resultEncoding = null] - 'hex', 'binary' or 'base64'
- @return {string|Buffer} - Buffer when resultEncoding is null, or string
-*/
-function sha512(data, resultEncoding) {
- return createHash('sha512').update(data).digest(resultEncoding);
-}
-
-function HmacSHA256(buffer, secret) {
- return createHmac('sha256', secret).update(buffer).digest();
-}
-
-function ripemd160(data) {
- return createHash('rmd160').update(data).digest();
-}
-
-// function hash160(buffer) {
-// return ripemd160(sha256(buffer))
-// }
-//
-// function hash256(buffer) {
-// return sha256(sha256(buffer))
-// }
-
-//
-// function HmacSHA512(buffer, secret) {
-// return crypto.createHmac('sha512', secret).update(buffer).digest()
-// }
-
-module.exports = {
- sha1: sha1,
- sha256: sha256,
- sha512: sha512,
- HmacSHA256: HmacSHA256,
- ripemd160: ripemd160
- // hash160: hash160,
- // hash256: hash256,
- // HmacSHA512: HmacSHA512
-};
-
-/***/ }),
-/* 26 */
-/***/ (function(module, exports) {
-
-module.exports = assert;
-
-function assert(val, msg) {
- if (!val)
- throw new Error(msg || 'Assertion failed');
-}
-
-assert.equal = function assertEqual(l, r, msg) {
- if (l != r)
- throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
-};
-
-
-/***/ }),
-/* 27 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-exports.isAsync = undefined;
-
-var _asyncify = __webpack_require__(399);
-
-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;
-
-/***/ }),
-/* 28 */
-/***/ (function(module, exports) {
-
-module.exports = function (exec) {
- try {
- return !!exec();
- } catch (e) {
- return true;
- }
-};
-
-
-/***/ }),
-/* 29 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// to indexed object, toObject with fallback for non-array-like ES3 strings
-var IObject = __webpack_require__(108);
-var defined = __webpack_require__(72);
-module.exports = function (it) {
- return IObject(defined(it));
-};
-
-
-/***/ }),
-/* 30 */
-/***/ (function(module, exports) {
-
-module.exports = {};
-
-
-/***/ }),
-/* 31 */
-/***/ (function(module, exports, __webpack_require__) {
-
-
-/**
- * Expose `Emitter`.
- */
-
-if (true) {
- module.exports = Emitter;
-}
-
-/**
- * Initialize a new `Emitter`.
- *
- * @api public
- */
-
-function Emitter(obj) {
- if (obj) return mixin(obj);
-};
-
-/**
- * Mixin the emitter properties.
- *
- * @param {Object} obj
- * @return {Object}
- * @api private
- */
-
-function mixin(obj) {
- for (var key in Emitter.prototype) {
- obj[key] = Emitter.prototype[key];
- }
- return obj;
-}
-
-/**
- * Listen on the given `event` with `fn`.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
-
-Emitter.prototype.on =
-Emitter.prototype.addEventListener = function(event, fn){
- this._callbacks = this._callbacks || {};
- (this._callbacks['$' + event] = this._callbacks['$' + event] || [])
- .push(fn);
- return this;
-};
-
-/**
- * Adds an `event` listener that will be invoked a single
- * time then automatically removed.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
-
-Emitter.prototype.once = function(event, fn){
- function on() {
- this.off(event, on);
- fn.apply(this, arguments);
- }
-
- on.fn = fn;
- this.on(event, on);
- return this;
-};
-
-/**
- * Remove the given callback for `event` or all
- * registered callbacks.
- *
- * @param {String} event
- * @param {Function} fn
- * @return {Emitter}
- * @api public
- */
-
-Emitter.prototype.off =
-Emitter.prototype.removeListener =
-Emitter.prototype.removeAllListeners =
-Emitter.prototype.removeEventListener = function(event, fn){
- this._callbacks = this._callbacks || {};
-
- // all
- if (0 == arguments.length) {
- this._callbacks = {};
- return this;
- }
-
- // specific event
- var callbacks = this._callbacks['$' + event];
- if (!callbacks) return this;
-
- // remove all handlers
- if (1 == arguments.length) {
- delete this._callbacks['$' + event];
- return this;
- }
-
- // remove specific handler
- var cb;
- for (var i = 0; i < callbacks.length; i++) {
- cb = callbacks[i];
- if (cb === fn || cb.fn === fn) {
- callbacks.splice(i, 1);
- break;
- }
- }
- return this;
-};
-
-/**
- * Emit `event` with the given args.
- *
- * @param {String} event
- * @param {Mixed} ...
- * @return {Emitter}
- */
-
-Emitter.prototype.emit = function(event){
- this._callbacks = this._callbacks || {};
- var args = [].slice.call(arguments, 1)
- , callbacks = this._callbacks['$' + event];
-
- if (callbacks) {
- callbacks = callbacks.slice(0);
- for (var i = 0, len = callbacks.length; i < len; ++i) {
- callbacks[i].apply(this, args);
- }
- }
-
- return this;
-};
-
-/**
- * Return array of callbacks for `event`.
- *
- * @param {String} event
- * @return {Array}
- * @api public
- */
-
-Emitter.prototype.listeners = function(event){
- this._callbacks = this._callbacks || {};
- return this._callbacks['$' + event] || [];
-};
-
-/**
- * Check if this emitter has `event` handlers.
- *
- * @param {String} event
- * @return {Boolean}
- * @api public
- */
-
-Emitter.prototype.hasListeners = function(event){
- return !! this.listeners(event).length;
-};
-
-
-/***/ }),
-/* 32 */
-/***/ (function(module, exports, __webpack_require__) {
-
-/* WEBPACK VAR INJECTION */(function(global) {/**
- * Module dependencies.
- */
-
-var keys = __webpack_require__(221);
-var hasBinary = __webpack_require__(125);
-var sliceBuffer = __webpack_require__(225);
-var after = __webpack_require__(226);
-var utf8 = __webpack_require__(227);
-
-var base64encoder;
-if (global && global.ArrayBuffer) {
- base64encoder = __webpack_require__(228);
-}
-
-/**
- * Check if we are running an android browser. That requires us to use
- * ArrayBuffer with polling transports...
- *
- * http://ghinda.net/jpeg-blob-ajax-android/
- */
-
-var isAndroid = typeof navigator !== 'undefined' && /Android/i.test(navigator.userAgent);
-
-/**
- * Check if we are running in PhantomJS.
- * Uploading a Blob with PhantomJS does not work correctly, as reported here:
- * https://github.com/ariya/phantomjs/issues/11395
- * @type boolean
- */
-var isPhantomJS = typeof navigator !== 'undefined' && /PhantomJS/i.test(navigator.userAgent);
-
-/**
- * When true, avoids using Blobs to encode payloads.
- * @type boolean
- */
-var dontSendBlobs = isAndroid || isPhantomJS;
-
-/**
- * Current protocol version.
- */
-
-exports.protocol = 3;
-
-/**
- * Packet types.
- */
-
-var packets = exports.packets = {
- open: 0 // non-ws
- , close: 1 // non-ws
- , ping: 2
- , pong: 3
- , message: 4
- , upgrade: 5
- , noop: 6
-};
-
-var packetslist = keys(packets);
-
-/**
- * Premade error packet.
- */
-
-var err = { type: 'error', data: 'parser error' };
-
-/**
- * Create a blob api even for blob builder when vendor prefixes exist
- */
-
-var Blob = __webpack_require__(229);
-
-/**
- * Encodes a packet.
- *
- * [ ]
- *
- * Example:
- *
- * 5hello world
- * 3
- * 4
- *
- * Binary is encoded in an identical principle
- *
- * @api private
- */
-
-exports.encodePacket = function (packet, supportsBinary, utf8encode, callback) {
- if (typeof supportsBinary === 'function') {
- callback = supportsBinary;
- supportsBinary = false;
- }
-
- if (typeof utf8encode === 'function') {
- callback = utf8encode;
- utf8encode = null;
- }
-
- var data = (packet.data === undefined)
- ? undefined
- : packet.data.buffer || packet.data;
-
- if (global.ArrayBuffer && data instanceof ArrayBuffer) {
- return encodeArrayBuffer(packet, supportsBinary, callback);
- } else if (Blob && data instanceof global.Blob) {
- return encodeBlob(packet, supportsBinary, callback);
- }
-
- // might be an object with { base64: true, data: dataAsBase64String }
- if (data && data.base64) {
- return encodeBase64Object(packet, callback);
- }
-
- // Sending data as a utf-8 string
- var encoded = packets[packet.type];
-
- // data fragment is optional
- if (undefined !== packet.data) {
- encoded += utf8encode ? utf8.encode(String(packet.data), { strict: false }) : String(packet.data);
- }
-
- return callback('' + encoded);
-
-};
-
-function encodeBase64Object(packet, callback) {
- // packet data is an object { base64: true, data: dataAsBase64String }
- var message = 'b' + exports.packets[packet.type] + packet.data.data;
- return callback(message);
-}
-
-/**
- * Encode packet helpers for binary types
- */
-
-function encodeArrayBuffer(packet, supportsBinary, callback) {
- if (!supportsBinary) {
- return exports.encodeBase64Packet(packet, callback);
- }
-
- var data = packet.data;
- var contentArray = new Uint8Array(data);
- var resultBuffer = new Uint8Array(1 + data.byteLength);
-
- resultBuffer[0] = packets[packet.type];
- for (var i = 0; i < contentArray.length; i++) {
- resultBuffer[i+1] = contentArray[i];
- }
-
- return callback(resultBuffer.buffer);
-}
-
-function encodeBlobAsArrayBuffer(packet, supportsBinary, callback) {
- if (!supportsBinary) {
- return exports.encodeBase64Packet(packet, callback);
- }
-
- var fr = new FileReader();
- fr.onload = function() {
- packet.data = fr.result;
- exports.encodePacket(packet, supportsBinary, true, callback);
- };
- return fr.readAsArrayBuffer(packet.data);
-}
-
-function encodeBlob(packet, supportsBinary, callback) {
- if (!supportsBinary) {
- return exports.encodeBase64Packet(packet, callback);
- }
-
- if (dontSendBlobs) {
- return encodeBlobAsArrayBuffer(packet, supportsBinary, callback);
- }
-
- var length = new Uint8Array(1);
- length[0] = packets[packet.type];
- var blob = new Blob([length.buffer, packet.data]);
-
- return callback(blob);
-}
-
-/**
- * Encodes a packet with binary data in a base64 string
- *
- * @param {Object} packet, has `type` and `data`
- * @return {String} base64 encoded message
- */
-
-exports.encodeBase64Packet = function(packet, callback) {
- var message = 'b' + exports.packets[packet.type];
- if (Blob && packet.data instanceof global.Blob) {
- var fr = new FileReader();
- fr.onload = function() {
- var b64 = fr.result.split(',')[1];
- callback(message + b64);
- };
- return fr.readAsDataURL(packet.data);
- }
-
- var b64data;
- try {
- b64data = String.fromCharCode.apply(null, new Uint8Array(packet.data));
- } catch (e) {
- // iPhone Safari doesn't let you apply with typed arrays
- var typed = new Uint8Array(packet.data);
- var basic = new Array(typed.length);
- for (var i = 0; i < typed.length; i++) {
- basic[i] = typed[i];
- }
- b64data = String.fromCharCode.apply(null, basic);
- }
- message += global.btoa(b64data);
- return callback(message);
-};
-
-/**
- * Decodes a packet. Changes format to Blob if requested.
- *
- * @return {Object} with `type` and `data` (if any)
- * @api private
- */
-
-exports.decodePacket = function (data, binaryType, utf8decode) {
- if (data === undefined) {
- return err;
- }
- // String data
- if (typeof data === 'string') {
- if (data.charAt(0) === 'b') {
- return exports.decodeBase64Packet(data.substr(1), binaryType);
- }
-
- if (utf8decode) {
- data = tryDecode(data);
- if (data === false) {
- return err;
- }
- }
- var type = data.charAt(0);
-
- if (Number(type) != type || !packetslist[type]) {
- return err;
- }
-
- if (data.length > 1) {
- return { type: packetslist[type], data: data.substring(1) };
- } else {
- return { type: packetslist[type] };
- }
- }
-
- var asArray = new Uint8Array(data);
- var type = asArray[0];
- var rest = sliceBuffer(data, 1);
- if (Blob && binaryType === 'blob') {
- rest = new Blob([rest]);
- }
- return { type: packetslist[type], data: rest };
-};
-
-function tryDecode(data) {
- try {
- data = utf8.decode(data, { strict: false });
- } catch (e) {
- return false;
- }
- return data;
-}
-
-/**
- * Decodes a packet encoded in a base64 string
- *
- * @param {String} base64 encoded message
- * @return {Object} with `type` and `data` (if any)
- */
-
-exports.decodeBase64Packet = function(msg, binaryType) {
- var type = packetslist[msg.charAt(0)];
- if (!base64encoder) {
- return { type: type, data: { base64: true, data: msg.substr(1) } };
- }
-
- var data = base64encoder.decode(msg.substr(1));
-
- if (binaryType === 'blob' && Blob) {
- data = new Blob([data]);
- }
-
- return { type: type, data: data };
-};
-
-/**
- * Encodes multiple messages (payload).
- *
- * :data
- *
- * Example:
- *
- * 11:hello world2:hi
- *
- * If any contents are binary, they will be encoded as base64 strings. Base64
- * encoded strings are marked with a b before the length specifier
- *
- * @param {Array} packets
- * @api private
- */
-
-exports.encodePayload = function (packets, supportsBinary, callback) {
- if (typeof supportsBinary === 'function') {
- callback = supportsBinary;
- supportsBinary = null;
- }
-
- var isBinary = hasBinary(packets);
-
- if (supportsBinary && isBinary) {
- if (Blob && !dontSendBlobs) {
- return exports.encodePayloadAsBlob(packets, callback);
- }
-
- return exports.encodePayloadAsArrayBuffer(packets, callback);
- }
-
- if (!packets.length) {
- return callback('0:');
- }
-
- function setLengthHeader(message) {
- return message.length + ':' + message;
- }
-
- function encodeOne(packet, doneCallback) {
- exports.encodePacket(packet, !isBinary ? false : supportsBinary, false, function(message) {
- doneCallback(null, setLengthHeader(message));
- });
- }
-
- map(packets, encodeOne, function(err, results) {
- return callback(results.join(''));
- });
-};
-
-/**
- * Async array map using after
- */
-
-function map(ary, each, done) {
- var result = new Array(ary.length);
- var next = after(ary.length, done);
-
- var eachWithIndex = function(i, el, cb) {
- each(el, function(error, msg) {
- result[i] = msg;
- cb(error, result);
- });
- };
-
- for (var i = 0; i < ary.length; i++) {
- eachWithIndex(i, ary[i], next);
- }
-}
-
-/*
- * Decodes data when a payload is maybe expected. Possible binary contents are
- * decoded from their base64 representation
- *
- * @param {String} data, callback method
- * @api public
- */
-
-exports.decodePayload = function (data, binaryType, callback) {
- if (typeof data !== 'string') {
- return exports.decodePayloadAsBinary(data, binaryType, callback);
- }
-
- if (typeof binaryType === 'function') {
- callback = binaryType;
- binaryType = null;
- }
-
- var packet;
- if (data === '') {
- // parser error - ignoring payload
- return callback(err, 0, 1);
- }
-
- var length = '', n, msg;
-
- for (var i = 0, l = data.length; i < l; i++) {
- var chr = data.charAt(i);
-
- if (chr !== ':') {
- length += chr;
- continue;
- }
-
- if (length === '' || (length != (n = Number(length)))) {
- // parser error - ignoring payload
- return callback(err, 0, 1);
- }
-
- msg = data.substr(i + 1, n);
-
- if (length != msg.length) {
- // parser error - ignoring payload
- return callback(err, 0, 1);
- }
-
- if (msg.length) {
- packet = exports.decodePacket(msg, binaryType, false);
-
- if (err.type === packet.type && err.data === packet.data) {
- // parser error in individual packet - ignoring payload
- return callback(err, 0, 1);
- }
-
- var ret = callback(packet, i + n, l);
- if (false === ret) return;
- }
-
- // advance cursor
- i += n;
- length = '';
- }
-
- if (length !== '') {
- // parser error - ignoring payload
- return callback(err, 0, 1);
- }
-
-};
-
-/**
- * Encodes multiple messages (payload) as binary.
- *
- * <1 = binary, 0 = string>[...]
- *
- * Example:
- * 1 3 255 1 2 3, if the binary contents are interpreted as 8 bit integers
- *
- * @param {Array} packets
- * @return {ArrayBuffer} encoded payload
- * @api private
- */
-
-exports.encodePayloadAsArrayBuffer = function(packets, callback) {
- if (!packets.length) {
- return callback(new ArrayBuffer(0));
- }
-
- function encodeOne(packet, doneCallback) {
- exports.encodePacket(packet, true, true, function(data) {
- return doneCallback(null, data);
- });
- }
-
- map(packets, encodeOne, function(err, encodedPackets) {
- var totalLength = encodedPackets.reduce(function(acc, p) {
- var len;
- if (typeof p === 'string'){
- len = p.length;
- } else {
- len = p.byteLength;
- }
- return acc + len.toString().length + len + 2; // string/binary identifier + separator = 2
- }, 0);
-
- var resultArray = new Uint8Array(totalLength);
-
- var bufferIndex = 0;
- encodedPackets.forEach(function(p) {
- var isString = typeof p === 'string';
- var ab = p;
- if (isString) {
- var view = new Uint8Array(p.length);
- for (var i = 0; i < p.length; i++) {
- view[i] = p.charCodeAt(i);
- }
- ab = view.buffer;
- }
-
- if (isString) { // not true binary
- resultArray[bufferIndex++] = 0;
- } else { // true binary
- resultArray[bufferIndex++] = 1;
- }
-
- var lenStr = ab.byteLength.toString();
- for (var i = 0; i < lenStr.length; i++) {
- resultArray[bufferIndex++] = parseInt(lenStr[i]);
- }
- resultArray[bufferIndex++] = 255;
-
- var view = new Uint8Array(ab);
- for (var i = 0; i < view.length; i++) {
- resultArray[bufferIndex++] = view[i];
- }
- });
-
- return callback(resultArray.buffer);
- });
-};
-
-/**
- * Encode as Blob
- */
-
-exports.encodePayloadAsBlob = function(packets, callback) {
- function encodeOne(packet, doneCallback) {
- exports.encodePacket(packet, true, true, function(encoded) {
- var binaryIdentifier = new Uint8Array(1);
- binaryIdentifier[0] = 1;
- if (typeof encoded === 'string') {
- var view = new Uint8Array(encoded.length);
- for (var i = 0; i < encoded.length; i++) {
- view[i] = encoded.charCodeAt(i);
- }
- encoded = view.buffer;
- binaryIdentifier[0] = 0;
- }
-
- var len = (encoded instanceof ArrayBuffer)
- ? encoded.byteLength
- : encoded.size;
-
- var lenStr = len.toString();
- var lengthAry = new Uint8Array(lenStr.length + 1);
- for (var i = 0; i < lenStr.length; i++) {
- lengthAry[i] = parseInt(lenStr[i]);
- }
- lengthAry[lenStr.length] = 255;
-
- if (Blob) {
- var blob = new Blob([binaryIdentifier.buffer, lengthAry.buffer, encoded]);
- doneCallback(null, blob);
- }
- });
- }
-
- map(packets, encodeOne, function(err, results) {
- return callback(new Blob(results));
- });
-};
-
-/*
- * Decodes data when a payload is maybe expected. Strings are decoded by
- * interpreting each byte as a key code for entries marked to start with 0. See
- * description of encodePayloadAsBinary
- *
- * @param {ArrayBuffer} data, callback method
- * @api public
- */
-
-exports.decodePayloadAsBinary = function (data, binaryType, callback) {
- if (typeof binaryType === 'function') {
- callback = binaryType;
- binaryType = null;
- }
-
- var bufferTail = data;
- var buffers = [];
-
- while (bufferTail.byteLength > 0) {
- var tailArray = new Uint8Array(bufferTail);
- var isString = tailArray[0] === 0;
- var msgLength = '';
-
- for (var i = 1; ; i++) {
- if (tailArray[i] === 255) break;
-
- // 310 = char length of Number.MAX_VALUE
- if (msgLength.length > 310) {
- return callback(err, 0, 1);
- }
-
- msgLength += tailArray[i];
- }
-
- bufferTail = sliceBuffer(bufferTail, 2 + msgLength.length);
- msgLength = parseInt(msgLength);
-
- var msg = sliceBuffer(bufferTail, 0, msgLength);
- if (isString) {
- try {
- msg = String.fromCharCode.apply(null, new Uint8Array(msg));
- } catch (e) {
- // iPhone Safari doesn't let you apply to typed arrays
- var typed = new Uint8Array(msg);
- msg = '';
- for (var i = 0; i < typed.length; i++) {
- msg += String.fromCharCode(typed[i]);
- }
- }
- }
-
- buffers.push(msg);
- bufferTail = sliceBuffer(bufferTail, msgLength);
- }
-
- var total = buffers.length;
- buffers.forEach(function(buffer, i) {
- callback(exports.decodePacket(buffer, binaryType, true), i, total);
- });
-};
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
-
-/***/ }),
-/* 33 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;/*
- Copyright 2013-2014 Daniel Wirtz
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
- */
-
-/**
- * @license bytebuffer.js (c) 2015 Daniel Wirtz
- * Backing buffer: ArrayBuffer, Accessor: Uint8Array
- * Released under the Apache License, Version 2.0
- * see: https://github.com/dcodeIO/bytebuffer.js for details
- */
-(function(global, factory) {
-
- /* AMD */ if (true)
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(254)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- /* CommonJS */ else if (typeof require === 'function' && typeof module === "object" && module && module["exports"])
- module['exports'] = (function() {
- var Long; try { Long = require("long"); } catch (e) {}
- return factory(Long);
- })();
- /* Global */ else
- (global["dcodeIO"] = global["dcodeIO"] || {})["ByteBuffer"] = factory(global["dcodeIO"]["Long"]);
-
-})(this, function(Long) {
- "use strict";
-
- /**
- * Constructs a new ByteBuffer.
- * @class The swiss army knife for binary data in JavaScript.
- * @exports ByteBuffer
- * @constructor
- * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @expose
- */
- var ByteBuffer = function(capacity, littleEndian, noAssert) {
- if (typeof capacity === 'undefined')
- capacity = ByteBuffer.DEFAULT_CAPACITY;
- if (typeof littleEndian === 'undefined')
- littleEndian = ByteBuffer.DEFAULT_ENDIAN;
- if (typeof noAssert === 'undefined')
- noAssert = ByteBuffer.DEFAULT_NOASSERT;
- if (!noAssert) {
- capacity = capacity | 0;
- if (capacity < 0)
- throw RangeError("Illegal capacity");
- littleEndian = !!littleEndian;
- noAssert = !!noAssert;
- }
-
- /**
- * Backing ArrayBuffer.
- * @type {!ArrayBuffer}
- * @expose
- */
- this.buffer = capacity === 0 ? EMPTY_BUFFER : new ArrayBuffer(capacity);
-
- /**
- * Uint8Array utilized to manipulate the backing buffer. Becomes `null` if the backing buffer has a capacity of `0`.
- * @type {?Uint8Array}
- * @expose
- */
- this.view = capacity === 0 ? null : new Uint8Array(this.buffer);
-
- /**
- * Absolute read/write offset.
- * @type {number}
- * @expose
- * @see ByteBuffer#flip
- * @see ByteBuffer#clear
- */
- this.offset = 0;
-
- /**
- * Marked offset.
- * @type {number}
- * @expose
- * @see ByteBuffer#mark
- * @see ByteBuffer#reset
- */
- this.markedOffset = -1;
-
- /**
- * Absolute limit of the contained data. Set to the backing buffer's capacity upon allocation.
- * @type {number}
- * @expose
- * @see ByteBuffer#flip
- * @see ByteBuffer#clear
- */
- this.limit = capacity;
-
- /**
- * Whether to use little endian byte order, defaults to `false` for big endian.
- * @type {boolean}
- * @expose
- */
- this.littleEndian = littleEndian;
-
- /**
- * Whether to skip assertions of offsets and values, defaults to `false`.
- * @type {boolean}
- * @expose
- */
- this.noAssert = noAssert;
- };
-
- /**
- * ByteBuffer version.
- * @type {string}
- * @const
- * @expose
- */
- ByteBuffer.VERSION = "5.0.1";
-
- /**
- * Little endian constant that can be used instead of its boolean value. Evaluates to `true`.
- * @type {boolean}
- * @const
- * @expose
- */
- ByteBuffer.LITTLE_ENDIAN = true;
-
- /**
- * Big endian constant that can be used instead of its boolean value. Evaluates to `false`.
- * @type {boolean}
- * @const
- * @expose
- */
- ByteBuffer.BIG_ENDIAN = false;
-
- /**
- * Default initial capacity of `16`.
- * @type {number}
- * @expose
- */
- ByteBuffer.DEFAULT_CAPACITY = 16;
-
- /**
- * Default endianess of `false` for big endian.
- * @type {boolean}
- * @expose
- */
- ByteBuffer.DEFAULT_ENDIAN = ByteBuffer.BIG_ENDIAN;
-
- /**
- * Default no assertions flag of `false`.
- * @type {boolean}
- * @expose
- */
- ByteBuffer.DEFAULT_NOASSERT = false;
-
- /**
- * A `Long` class for representing a 64-bit two's-complement integer value. May be `null` if Long.js has not been loaded
- * and int64 support is not available.
- * @type {?Long}
- * @const
- * @see https://github.com/dcodeIO/long.js
- * @expose
- */
- ByteBuffer.Long = Long || null;
-
- /**
- * @alias ByteBuffer.prototype
- * @inner
- */
- var ByteBufferPrototype = ByteBuffer.prototype;
-
- /**
- * An indicator used to reliably determine if an object is a ByteBuffer or not.
- * @type {boolean}
- * @const
- * @expose
- * @private
- */
- ByteBufferPrototype.__isByteBuffer__;
-
- Object.defineProperty(ByteBufferPrototype, "__isByteBuffer__", {
- value: true,
- enumerable: false,
- configurable: false
- });
-
- // helpers
-
- /**
- * @type {!ArrayBuffer}
- * @inner
- */
- var EMPTY_BUFFER = new ArrayBuffer(0);
-
- /**
- * String.fromCharCode reference for compile-time renaming.
- * @type {function(...number):string}
- * @inner
- */
- var stringFromCharCode = String.fromCharCode;
-
- /**
- * Creates a source function for a string.
- * @param {string} s String to read from
- * @returns {function():number|null} Source function returning the next char code respectively `null` if there are
- * no more characters left.
- * @throws {TypeError} If the argument is invalid
- * @inner
- */
- function stringSource(s) {
- var i=0; return function() {
- return i < s.length ? s.charCodeAt(i++) : null;
- };
- }
-
- /**
- * Creates a destination function for a string.
- * @returns {function(number=):undefined|string} Destination function successively called with the next char code.
- * Returns the final string when called without arguments.
- * @inner
- */
- function stringDestination() {
- var cs = [], ps = []; return function() {
- if (arguments.length === 0)
- return ps.join('')+stringFromCharCode.apply(String, cs);
- if (cs.length + arguments.length > 1024)
- ps.push(stringFromCharCode.apply(String, cs)),
- cs.length = 0;
- Array.prototype.push.apply(cs, arguments);
- };
- }
-
- /**
- * Gets the accessor type.
- * @returns {Function} `Buffer` under node.js, `Uint8Array` respectively `DataView` in the browser (classes)
- * @expose
- */
- ByteBuffer.accessor = function() {
- return Uint8Array;
- };
- /**
- * Allocates a new ByteBuffer backed by a buffer of the specified capacity.
- * @param {number=} capacity Initial capacity. Defaults to {@link ByteBuffer.DEFAULT_CAPACITY}.
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer}
- * @expose
- */
- ByteBuffer.allocate = function(capacity, littleEndian, noAssert) {
- return new ByteBuffer(capacity, littleEndian, noAssert);
- };
-
- /**
- * Concatenates multiple ByteBuffers into one.
- * @param {!Array.} buffers Buffers to concatenate
- * @param {(string|boolean)=} encoding String encoding if `buffers` contains a string ("base64", "hex", "binary",
- * defaults to "utf8")
- * @param {boolean=} littleEndian Whether to use little or big endian byte order for the resulting ByteBuffer. Defaults
- * to {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values for the resulting ByteBuffer. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} Concatenated ByteBuffer
- * @expose
- */
- ByteBuffer.concat = function(buffers, encoding, littleEndian, noAssert) {
- if (typeof encoding === 'boolean' || typeof encoding !== 'string') {
- noAssert = littleEndian;
- littleEndian = encoding;
- encoding = undefined;
- }
- var capacity = 0;
- for (var i=0, k=buffers.length, length; i 0) capacity += length;
- }
- if (capacity === 0)
- return new ByteBuffer(0, littleEndian, noAssert);
- var bb = new ByteBuffer(capacity, littleEndian, noAssert),
- bi;
- i=0; while (i} buffer Anything that can be wrapped
- * @param {(string|boolean)=} encoding String encoding if `buffer` is a string ("base64", "hex", "binary", defaults to
- * "utf8")
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} A ByteBuffer wrapping `buffer`
- * @expose
- */
- ByteBuffer.wrap = function(buffer, encoding, littleEndian, noAssert) {
- if (typeof encoding !== 'string') {
- noAssert = littleEndian;
- littleEndian = encoding;
- encoding = undefined;
- }
- if (typeof buffer === 'string') {
- if (typeof encoding === 'undefined')
- encoding = "utf8";
- switch (encoding) {
- case "base64":
- return ByteBuffer.fromBase64(buffer, littleEndian);
- case "hex":
- return ByteBuffer.fromHex(buffer, littleEndian);
- case "binary":
- return ByteBuffer.fromBinary(buffer, littleEndian);
- case "utf8":
- return ByteBuffer.fromUTF8(buffer, littleEndian);
- case "debug":
- return ByteBuffer.fromDebug(buffer, littleEndian);
- default:
- throw Error("Unsupported encoding: "+encoding);
- }
- }
- if (buffer === null || typeof buffer !== 'object')
- throw TypeError("Illegal buffer");
- var bb;
- if (ByteBuffer.isByteBuffer(buffer)) {
- bb = ByteBufferPrototype.clone.call(buffer);
- bb.markedOffset = -1;
- return bb;
- }
- if (buffer instanceof Uint8Array) { // Extract ArrayBuffer from Uint8Array
- bb = new ByteBuffer(0, littleEndian, noAssert);
- if (buffer.length > 0) { // Avoid references to more than one EMPTY_BUFFER
- bb.buffer = buffer.buffer;
- bb.offset = buffer.byteOffset;
- bb.limit = buffer.byteOffset + buffer.byteLength;
- bb.view = new Uint8Array(buffer.buffer);
- }
- } else if (buffer instanceof ArrayBuffer) { // Reuse ArrayBuffer
- bb = new ByteBuffer(0, littleEndian, noAssert);
- if (buffer.byteLength > 0) {
- bb.buffer = buffer;
- bb.offset = 0;
- bb.limit = buffer.byteLength;
- bb.view = buffer.byteLength > 0 ? new Uint8Array(buffer) : null;
- }
- } else if (Object.prototype.toString.call(buffer) === "[object Array]") { // Create from octets
- bb = new ByteBuffer(buffer.length, littleEndian, noAssert);
- bb.limit = buffer.length;
- for (var i=0; i} value Array of booleans to write
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
- * @returns {!ByteBuffer}
- * @expose
- */
- ByteBufferPrototype.writeBitSet = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (!(value instanceof Array))
- throw TypeError("Illegal BitSet: Not an array");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
-
- var start = offset,
- bits = value.length,
- bytes = (bits >> 3),
- bit = 0,
- k;
-
- offset += this.writeVarint32(bits,offset);
-
- while(bytes--) {
- k = (!!value[bit++] & 1) |
- ((!!value[bit++] & 1) << 1) |
- ((!!value[bit++] & 1) << 2) |
- ((!!value[bit++] & 1) << 3) |
- ((!!value[bit++] & 1) << 4) |
- ((!!value[bit++] & 1) << 5) |
- ((!!value[bit++] & 1) << 6) |
- ((!!value[bit++] & 1) << 7);
- this.writeByte(k,offset++);
- }
-
- if(bit < bits) {
- var m = 0; k = 0;
- while(bit < bits) k = k | ((!!value[bit++] & 1) << (m++));
- this.writeByte(k,offset++);
- }
-
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- }
-
- /**
- * Reads a BitSet as an array of booleans.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
- * @returns {Array
- * @expose
- */
- ByteBufferPrototype.readBitSet = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
-
- var ret = this.readVarint32(offset),
- bits = ret.value,
- bytes = (bits >> 3),
- bit = 0,
- value = [],
- k;
-
- offset += ret.length;
-
- while(bytes--) {
- k = this.readByte(offset++);
- value[bit++] = !!(k & 0x01);
- value[bit++] = !!(k & 0x02);
- value[bit++] = !!(k & 0x04);
- value[bit++] = !!(k & 0x08);
- value[bit++] = !!(k & 0x10);
- value[bit++] = !!(k & 0x20);
- value[bit++] = !!(k & 0x40);
- value[bit++] = !!(k & 0x80);
- }
-
- if(bit < bits) {
- var m = 0;
- k = this.readByte(offset++);
- while(bit < bits) value[bit++] = !!((k >> (m++)) & 1);
- }
-
- if (relative) {
- this.offset = offset;
- }
- return value;
- }
- /**
- * Reads the specified number of bytes.
- * @param {number} length Number of bytes to read
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `length` if omitted.
- * @returns {!ByteBuffer}
- * @expose
- */
- ByteBufferPrototype.readBytes = function(length, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + length > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
- }
- var slice = this.slice(offset, offset + length);
- if (relative) this.offset += length;
- return slice;
- };
-
- /**
- * Writes a payload of bytes. This is an alias of {@link ByteBuffer#append}.
- * @function
- * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to write. If `source` is a ByteBuffer, its offsets
- * will be modified according to the performed read operation.
- * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeBytes = ByteBufferPrototype.append;
-
- // types/ints/int8
-
- /**
- * Writes an 8bit signed integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeInt8 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 1;
- var capacity0 = this.buffer.byteLength;
- if (offset > capacity0)
- this.resize((capacity0 *= 2) > offset ? capacity0 : offset);
- offset -= 1;
- this.view[offset] = value;
- if (relative) this.offset += 1;
- return this;
- };
-
- /**
- * Writes an 8bit signed integer. This is an alias of {@link ByteBuffer#writeInt8}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeByte = ByteBufferPrototype.writeInt8;
-
- /**
- * Reads an 8bit signed integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readInt8 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var value = this.view[offset];
- if ((value & 0x80) === 0x80) value = -(0xFF - value + 1); // Cast to signed
- if (relative) this.offset += 1;
- return value;
- };
-
- /**
- * Reads an 8bit signed integer. This is an alias of {@link ByteBuffer#readInt8}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readByte = ByteBufferPrototype.readInt8;
-
- /**
- * Writes an 8bit unsigned integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUint8 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value >>>= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 1;
- var capacity1 = this.buffer.byteLength;
- if (offset > capacity1)
- this.resize((capacity1 *= 2) > offset ? capacity1 : offset);
- offset -= 1;
- this.view[offset] = value;
- if (relative) this.offset += 1;
- return this;
- };
-
- /**
- * Writes an 8bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint8}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUInt8 = ByteBufferPrototype.writeUint8;
-
- /**
- * Reads an 8bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUint8 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var value = this.view[offset];
- if (relative) this.offset += 1;
- return value;
- };
-
- /**
- * Reads an 8bit unsigned integer. This is an alias of {@link ByteBuffer#readUint8}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `1` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUInt8 = ByteBufferPrototype.readUint8;
-
- // types/ints/int16
-
- /**
- * Writes a 16bit signed integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeInt16 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 2;
- var capacity2 = this.buffer.byteLength;
- if (offset > capacity2)
- this.resize((capacity2 *= 2) > offset ? capacity2 : offset);
- offset -= 2;
- if (this.littleEndian) {
- this.view[offset+1] = (value & 0xFF00) >>> 8;
- this.view[offset ] = value & 0x00FF;
- } else {
- this.view[offset] = (value & 0xFF00) >>> 8;
- this.view[offset+1] = value & 0x00FF;
- }
- if (relative) this.offset += 2;
- return this;
- };
-
- /**
- * Writes a 16bit signed integer. This is an alias of {@link ByteBuffer#writeInt16}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeShort = ByteBufferPrototype.writeInt16;
-
- /**
- * Reads a 16bit signed integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readInt16 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 2 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset ];
- value |= this.view[offset+1] << 8;
- } else {
- value = this.view[offset ] << 8;
- value |= this.view[offset+1];
- }
- if ((value & 0x8000) === 0x8000) value = -(0xFFFF - value + 1); // Cast to signed
- if (relative) this.offset += 2;
- return value;
- };
-
- /**
- * Reads a 16bit signed integer. This is an alias of {@link ByteBuffer#readInt16}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readShort = ByteBufferPrototype.readInt16;
-
- /**
- * Writes a 16bit unsigned integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeUint16 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value >>>= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 2;
- var capacity3 = this.buffer.byteLength;
- if (offset > capacity3)
- this.resize((capacity3 *= 2) > offset ? capacity3 : offset);
- offset -= 2;
- if (this.littleEndian) {
- this.view[offset+1] = (value & 0xFF00) >>> 8;
- this.view[offset ] = value & 0x00FF;
- } else {
- this.view[offset] = (value & 0xFF00) >>> 8;
- this.view[offset+1] = value & 0x00FF;
- }
- if (relative) this.offset += 2;
- return this;
- };
-
- /**
- * Writes a 16bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint16}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @throws {TypeError} If `offset` or `value` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.writeUInt16 = ByteBufferPrototype.writeUint16;
-
- /**
- * Reads a 16bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readUint16 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 2 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+2+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset ];
- value |= this.view[offset+1] << 8;
- } else {
- value = this.view[offset ] << 8;
- value |= this.view[offset+1];
- }
- if (relative) this.offset += 2;
- return value;
- };
-
- /**
- * Reads a 16bit unsigned integer. This is an alias of {@link ByteBuffer#readUint16}.
- * @function
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `2` if omitted.
- * @returns {number} Value read
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @expose
- */
- ByteBufferPrototype.readUInt16 = ByteBufferPrototype.readUint16;
-
- // types/ints/int32
-
- /**
- * Writes a 32bit signed integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeInt32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 4;
- var capacity4 = this.buffer.byteLength;
- if (offset > capacity4)
- this.resize((capacity4 *= 2) > offset ? capacity4 : offset);
- offset -= 4;
- if (this.littleEndian) {
- this.view[offset+3] = (value >>> 24) & 0xFF;
- this.view[offset+2] = (value >>> 16) & 0xFF;
- this.view[offset+1] = (value >>> 8) & 0xFF;
- this.view[offset ] = value & 0xFF;
- } else {
- this.view[offset ] = (value >>> 24) & 0xFF;
- this.view[offset+1] = (value >>> 16) & 0xFF;
- this.view[offset+2] = (value >>> 8) & 0xFF;
- this.view[offset+3] = value & 0xFF;
- }
- if (relative) this.offset += 4;
- return this;
- };
-
- /**
- * Writes a 32bit signed integer. This is an alias of {@link ByteBuffer#writeInt32}.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeInt = ByteBufferPrototype.writeInt32;
-
- /**
- * Reads a 32bit signed integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readInt32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset+2] << 16;
- value |= this.view[offset+1] << 8;
- value |= this.view[offset ];
- value += this.view[offset+3] << 24 >>> 0;
- } else {
- value = this.view[offset+1] << 16;
- value |= this.view[offset+2] << 8;
- value |= this.view[offset+3];
- value += this.view[offset ] << 24 >>> 0;
- }
- value |= 0; // Cast to signed
- if (relative) this.offset += 4;
- return value;
- };
-
- /**
- * Reads a 32bit signed integer. This is an alias of {@link ByteBuffer#readInt32}.
- * @param {number=} offset Offset to read from. Will use and advance {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readInt = ByteBufferPrototype.readInt32;
-
- /**
- * Writes a 32bit unsigned integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeUint32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value >>>= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 4;
- var capacity5 = this.buffer.byteLength;
- if (offset > capacity5)
- this.resize((capacity5 *= 2) > offset ? capacity5 : offset);
- offset -= 4;
- if (this.littleEndian) {
- this.view[offset+3] = (value >>> 24) & 0xFF;
- this.view[offset+2] = (value >>> 16) & 0xFF;
- this.view[offset+1] = (value >>> 8) & 0xFF;
- this.view[offset ] = value & 0xFF;
- } else {
- this.view[offset ] = (value >>> 24) & 0xFF;
- this.view[offset+1] = (value >>> 16) & 0xFF;
- this.view[offset+2] = (value >>> 8) & 0xFF;
- this.view[offset+3] = value & 0xFF;
- }
- if (relative) this.offset += 4;
- return this;
- };
-
- /**
- * Writes a 32bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint32}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @expose
- */
- ByteBufferPrototype.writeUInt32 = ByteBufferPrototype.writeUint32;
-
- /**
- * Reads a 32bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUint32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var value = 0;
- if (this.littleEndian) {
- value = this.view[offset+2] << 16;
- value |= this.view[offset+1] << 8;
- value |= this.view[offset ];
- value += this.view[offset+3] << 24 >>> 0;
- } else {
- value = this.view[offset+1] << 16;
- value |= this.view[offset+2] << 8;
- value |= this.view[offset+3];
- value += this.view[offset ] << 24 >>> 0;
- }
- if (relative) this.offset += 4;
- return value;
- };
-
- /**
- * Reads a 32bit unsigned integer. This is an alias of {@link ByteBuffer#readUint32}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number} Value read
- * @expose
- */
- ByteBufferPrototype.readUInt32 = ByteBufferPrototype.readUint32;
-
- // types/ints/int64
-
- if (Long) {
-
- /**
- * Writes a 64bit signed integer.
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeInt64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- else if (!(value && value instanceof Long))
- throw TypeError("Illegal value: "+value+" (not an integer or Long)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- offset += 8;
- var capacity6 = this.buffer.byteLength;
- if (offset > capacity6)
- this.resize((capacity6 *= 2) > offset ? capacity6 : offset);
- offset -= 8;
- var lo = value.low,
- hi = value.high;
- if (this.littleEndian) {
- this.view[offset+3] = (lo >>> 24) & 0xFF;
- this.view[offset+2] = (lo >>> 16) & 0xFF;
- this.view[offset+1] = (lo >>> 8) & 0xFF;
- this.view[offset ] = lo & 0xFF;
- offset += 4;
- this.view[offset+3] = (hi >>> 24) & 0xFF;
- this.view[offset+2] = (hi >>> 16) & 0xFF;
- this.view[offset+1] = (hi >>> 8) & 0xFF;
- this.view[offset ] = hi & 0xFF;
- } else {
- this.view[offset ] = (hi >>> 24) & 0xFF;
- this.view[offset+1] = (hi >>> 16) & 0xFF;
- this.view[offset+2] = (hi >>> 8) & 0xFF;
- this.view[offset+3] = hi & 0xFF;
- offset += 4;
- this.view[offset ] = (lo >>> 24) & 0xFF;
- this.view[offset+1] = (lo >>> 16) & 0xFF;
- this.view[offset+2] = (lo >>> 8) & 0xFF;
- this.view[offset+3] = lo & 0xFF;
- }
- if (relative) this.offset += 8;
- return this;
- };
-
- /**
- * Writes a 64bit signed integer. This is an alias of {@link ByteBuffer#writeInt64}.
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeLong = ByteBufferPrototype.writeInt64;
-
- /**
- * Reads a 64bit signed integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readInt64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 8 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
- }
- var lo = 0,
- hi = 0;
- if (this.littleEndian) {
- lo = this.view[offset+2] << 16;
- lo |= this.view[offset+1] << 8;
- lo |= this.view[offset ];
- lo += this.view[offset+3] << 24 >>> 0;
- offset += 4;
- hi = this.view[offset+2] << 16;
- hi |= this.view[offset+1] << 8;
- hi |= this.view[offset ];
- hi += this.view[offset+3] << 24 >>> 0;
- } else {
- hi = this.view[offset+1] << 16;
- hi |= this.view[offset+2] << 8;
- hi |= this.view[offset+3];
- hi += this.view[offset ] << 24 >>> 0;
- offset += 4;
- lo = this.view[offset+1] << 16;
- lo |= this.view[offset+2] << 8;
- lo |= this.view[offset+3];
- lo += this.view[offset ] << 24 >>> 0;
- }
- var value = new Long(lo, hi, false);
- if (relative) this.offset += 8;
- return value;
- };
-
- /**
- * Reads a 64bit signed integer. This is an alias of {@link ByteBuffer#readInt64}.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readLong = ByteBufferPrototype.readInt64;
-
- /**
- * Writes a 64bit unsigned integer.
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUint64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- else if (!(value && value instanceof Long))
- throw TypeError("Illegal value: "+value+" (not an integer or Long)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- offset += 8;
- var capacity7 = this.buffer.byteLength;
- if (offset > capacity7)
- this.resize((capacity7 *= 2) > offset ? capacity7 : offset);
- offset -= 8;
- var lo = value.low,
- hi = value.high;
- if (this.littleEndian) {
- this.view[offset+3] = (lo >>> 24) & 0xFF;
- this.view[offset+2] = (lo >>> 16) & 0xFF;
- this.view[offset+1] = (lo >>> 8) & 0xFF;
- this.view[offset ] = lo & 0xFF;
- offset += 4;
- this.view[offset+3] = (hi >>> 24) & 0xFF;
- this.view[offset+2] = (hi >>> 16) & 0xFF;
- this.view[offset+1] = (hi >>> 8) & 0xFF;
- this.view[offset ] = hi & 0xFF;
- } else {
- this.view[offset ] = (hi >>> 24) & 0xFF;
- this.view[offset+1] = (hi >>> 16) & 0xFF;
- this.view[offset+2] = (hi >>> 8) & 0xFF;
- this.view[offset+3] = hi & 0xFF;
- offset += 4;
- this.view[offset ] = (lo >>> 24) & 0xFF;
- this.view[offset+1] = (lo >>> 16) & 0xFF;
- this.view[offset+2] = (lo >>> 8) & 0xFF;
- this.view[offset+3] = lo & 0xFF;
- }
- if (relative) this.offset += 8;
- return this;
- };
-
- /**
- * Writes a 64bit unsigned integer. This is an alias of {@link ByteBuffer#writeUint64}.
- * @function
- * @param {number|!Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeUInt64 = ByteBufferPrototype.writeUint64;
-
- /**
- * Reads a 64bit unsigned integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readUint64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 8 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
- }
- var lo = 0,
- hi = 0;
- if (this.littleEndian) {
- lo = this.view[offset+2] << 16;
- lo |= this.view[offset+1] << 8;
- lo |= this.view[offset ];
- lo += this.view[offset+3] << 24 >>> 0;
- offset += 4;
- hi = this.view[offset+2] << 16;
- hi |= this.view[offset+1] << 8;
- hi |= this.view[offset ];
- hi += this.view[offset+3] << 24 >>> 0;
- } else {
- hi = this.view[offset+1] << 16;
- hi |= this.view[offset+2] << 8;
- hi |= this.view[offset+3];
- hi += this.view[offset ] << 24 >>> 0;
- offset += 4;
- lo = this.view[offset+1] << 16;
- lo |= this.view[offset+2] << 8;
- lo |= this.view[offset+3];
- lo += this.view[offset ] << 24 >>> 0;
- }
- var value = new Long(lo, hi, true);
- if (relative) this.offset += 8;
- return value;
- };
-
- /**
- * Reads a 64bit unsigned integer. This is an alias of {@link ByteBuffer#readUint64}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!Long}
- * @expose
- */
- ByteBufferPrototype.readUInt64 = ByteBufferPrototype.readUint64;
-
- } // Long
-
-
- // types/floats/float32
-
- /*
- ieee754 - https://github.com/feross/ieee754
-
- The MIT License (MIT)
-
- Copyright (c) Feross Aboukhadijeh
-
- 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.
- */
-
- /**
- * Reads an IEEE754 float from a byte array.
- * @param {!Array} buffer
- * @param {number} offset
- * @param {boolean} isLE
- * @param {number} mLen
- * @param {number} nBytes
- * @returns {number}
- * @inner
- */
- function ieee754_read(buffer, offset, isLE, mLen, nBytes) {
- var e, m,
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- nBits = -7,
- i = isLE ? (nBytes - 1) : 0,
- d = isLE ? -1 : 1,
- 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);
- }
-
- /**
- * Writes an IEEE754 float to a byte array.
- * @param {!Array} buffer
- * @param {number} value
- * @param {number} offset
- * @param {boolean} isLE
- * @param {number} mLen
- * @param {number} nBytes
- * @inner
- */
- function ieee754_write(buffer, value, offset, isLE, mLen, nBytes) {
- var e, m, c,
- eLen = nBytes * 8 - mLen - 1,
- eMax = (1 << eLen) - 1,
- eBias = eMax >> 1,
- rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0),
- i = isLE ? 0 : (nBytes - 1),
- d = isLE ? 1 : -1,
- 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;
- }
-
- /**
- * Writes a 32bit float.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeFloat32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number')
- throw TypeError("Illegal value: "+value+" (not a number)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 4;
- var capacity8 = this.buffer.byteLength;
- if (offset > capacity8)
- this.resize((capacity8 *= 2) > offset ? capacity8 : offset);
- offset -= 4;
- ieee754_write(this.view, value, offset, this.littleEndian, 23, 4);
- if (relative) this.offset += 4;
- return this;
- };
-
- /**
- * Writes a 32bit float. This is an alias of {@link ByteBuffer#writeFloat32}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeFloat = ByteBufferPrototype.writeFloat32;
-
- /**
- * Reads a 32bit float.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readFloat32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var value = ieee754_read(this.view, offset, this.littleEndian, 23, 4);
- if (relative) this.offset += 4;
- return value;
- };
-
- /**
- * Reads a 32bit float. This is an alias of {@link ByteBuffer#readFloat32}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `4` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readFloat = ByteBufferPrototype.readFloat32;
-
- // types/floats/float64
-
- /**
- * Writes a 64bit float.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeFloat64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number')
- throw TypeError("Illegal value: "+value+" (not a number)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- offset += 8;
- var capacity9 = this.buffer.byteLength;
- if (offset > capacity9)
- this.resize((capacity9 *= 2) > offset ? capacity9 : offset);
- offset -= 8;
- ieee754_write(this.view, value, offset, this.littleEndian, 52, 8);
- if (relative) this.offset += 8;
- return this;
- };
-
- /**
- * Writes a 64bit float. This is an alias of {@link ByteBuffer#writeFloat64}.
- * @function
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.writeDouble = ByteBufferPrototype.writeFloat64;
-
- /**
- * Reads a 64bit float.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readFloat64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 8 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+8+") <= "+this.buffer.byteLength);
- }
- var value = ieee754_read(this.view, offset, this.littleEndian, 52, 8);
- if (relative) this.offset += 8;
- return value;
- };
-
- /**
- * Reads a 64bit float. This is an alias of {@link ByteBuffer#readFloat64}.
- * @function
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by `8` if omitted.
- * @returns {number}
- * @expose
- */
- ByteBufferPrototype.readDouble = ByteBufferPrototype.readFloat64;
-
-
- // types/varints/varint32
-
- /**
- * Maximum number of bytes required to store a 32bit base 128 variable-length integer.
- * @type {number}
- * @const
- * @expose
- */
- ByteBuffer.MAX_VARINT32_BYTES = 5;
-
- /**
- * Calculates the actual number of bytes required to store a 32bit base 128 variable-length integer.
- * @param {number} value Value to encode
- * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT32_BYTES}
- * @expose
- */
- ByteBuffer.calculateVarint32 = function(value) {
- // ref: src/google/protobuf/io/coded_stream.cc
- value = value >>> 0;
- if (value < 1 << 7 ) return 1;
- else if (value < 1 << 14) return 2;
- else if (value < 1 << 21) return 3;
- else if (value < 1 << 28) return 4;
- else return 5;
- };
-
- /**
- * Zigzag encodes a signed 32bit integer so that it can be effectively used with varint encoding.
- * @param {number} n Signed 32bit integer
- * @returns {number} Unsigned zigzag encoded 32bit integer
- * @expose
- */
- ByteBuffer.zigZagEncode32 = function(n) {
- return (((n |= 0) << 1) ^ (n >> 31)) >>> 0; // ref: src/google/protobuf/wire_format_lite.h
- };
-
- /**
- * Decodes a zigzag encoded signed 32bit integer.
- * @param {number} n Unsigned zigzag encoded 32bit integer
- * @returns {number} Signed 32bit integer
- * @expose
- */
- ByteBuffer.zigZagDecode32 = function(n) {
- return ((n >>> 1) ^ -(n & 1)) | 0; // // ref: src/google/protobuf/wire_format_lite.h
- };
-
- /**
- * Writes a 32bit base 128 variable-length integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
- * @expose
- */
- ByteBufferPrototype.writeVarint32 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var size = ByteBuffer.calculateVarint32(value),
- b;
- offset += size;
- var capacity10 = this.buffer.byteLength;
- if (offset > capacity10)
- this.resize((capacity10 *= 2) > offset ? capacity10 : offset);
- offset -= size;
- value >>>= 0;
- while (value >= 0x80) {
- b = (value & 0x7f) | 0x80;
- this.view[offset++] = b;
- value >>>= 7;
- }
- this.view[offset++] = value;
- if (relative) {
- this.offset = offset;
- return this;
- }
- return size;
- };
-
- /**
- * Writes a zig-zag encoded (signed) 32bit base 128 variable-length integer.
- * @param {number} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} this if `offset` is omitted, else the actual number of bytes written
- * @expose
- */
- ByteBufferPrototype.writeVarint32ZigZag = function(value, offset) {
- return this.writeVarint32(ByteBuffer.zigZagEncode32(value), offset);
- };
-
- /**
- * Reads a 32bit base 128 variable-length integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
- * and the actual number of bytes read.
- * @throws {Error} If it's not a valid varint. Has a property `truncated = true` if there is not enough data available
- * to fully decode the varint.
- * @expose
- */
- ByteBufferPrototype.readVarint32 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var c = 0,
- value = 0 >>> 0,
- b;
- do {
- if (!this.noAssert && offset > this.limit) {
- var err = Error("Truncated");
- err['truncated'] = true;
- throw err;
- }
- b = this.view[offset++];
- if (c < 5)
- value |= (b & 0x7f) << (7*c);
- ++c;
- } while ((b & 0x80) !== 0);
- value |= 0;
- if (relative) {
- this.offset = offset;
- return value;
- }
- return {
- "value": value,
- "length": c
- };
- };
-
- /**
- * Reads a zig-zag encoded (signed) 32bit base 128 variable-length integer.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {number|!{value: number, length: number}} The value read if offset is omitted, else the value read
- * and the actual number of bytes read.
- * @throws {Error} If it's not a valid varint
- * @expose
- */
- ByteBufferPrototype.readVarint32ZigZag = function(offset) {
- var val = this.readVarint32(offset);
- if (typeof val === 'object')
- val["value"] = ByteBuffer.zigZagDecode32(val["value"]);
- else
- val = ByteBuffer.zigZagDecode32(val);
- return val;
- };
-
- // types/varints/varint64
-
- if (Long) {
-
- /**
- * Maximum number of bytes required to store a 64bit base 128 variable-length integer.
- * @type {number}
- * @const
- * @expose
- */
- ByteBuffer.MAX_VARINT64_BYTES = 10;
-
- /**
- * Calculates the actual number of bytes required to store a 64bit base 128 variable-length integer.
- * @param {number|!Long} value Value to encode
- * @returns {number} Number of bytes required. Capped to {@link ByteBuffer.MAX_VARINT64_BYTES}
- * @expose
- */
- ByteBuffer.calculateVarint64 = function(value) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- // ref: src/google/protobuf/io/coded_stream.cc
- var part0 = value.toInt() >>> 0,
- part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
- part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
- if (part2 == 0) {
- if (part1 == 0) {
- if (part0 < 1 << 14)
- return part0 < 1 << 7 ? 1 : 2;
- else
- return part0 < 1 << 21 ? 3 : 4;
- } else {
- if (part1 < 1 << 14)
- return part1 < 1 << 7 ? 5 : 6;
- else
- return part1 < 1 << 21 ? 7 : 8;
- }
- } else
- return part2 < 1 << 7 ? 9 : 10;
- };
-
- /**
- * Zigzag encodes a signed 64bit integer so that it can be effectively used with varint encoding.
- * @param {number|!Long} value Signed long
- * @returns {!Long} Unsigned zigzag encoded long
- * @expose
- */
- ByteBuffer.zigZagEncode64 = function(value) {
- if (typeof value === 'number')
- value = Long.fromNumber(value, false);
- else if (typeof value === 'string')
- value = Long.fromString(value, false);
- else if (value.unsigned !== false) value = value.toSigned();
- // ref: src/google/protobuf/wire_format_lite.h
- return value.shiftLeft(1).xor(value.shiftRight(63)).toUnsigned();
- };
-
- /**
- * Decodes a zigzag encoded signed 64bit integer.
- * @param {!Long|number} value Unsigned zigzag encoded long or JavaScript number
- * @returns {!Long} Signed long
- * @expose
- */
- ByteBuffer.zigZagDecode64 = function(value) {
- if (typeof value === 'number')
- value = Long.fromNumber(value, false);
- else if (typeof value === 'string')
- value = Long.fromString(value, false);
- else if (value.unsigned !== false) value = value.toSigned();
- // ref: src/google/protobuf/wire_format_lite.h
- return value.shiftRightUnsigned(1).xor(value.and(Long.ONE).toSigned().negate()).toSigned();
- };
-
- /**
- * Writes a 64bit base 128 variable-length integer.
- * @param {number|Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeVarint64 = function(value, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof value === 'number')
- value = Long.fromNumber(value);
- else if (typeof value === 'string')
- value = Long.fromString(value);
- else if (!(value && value instanceof Long))
- throw TypeError("Illegal value: "+value+" (not an integer or Long)");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (typeof value === 'number')
- value = Long.fromNumber(value, false);
- else if (typeof value === 'string')
- value = Long.fromString(value, false);
- else if (value.unsigned !== false) value = value.toSigned();
- var size = ByteBuffer.calculateVarint64(value),
- part0 = value.toInt() >>> 0,
- part1 = value.shiftRightUnsigned(28).toInt() >>> 0,
- part2 = value.shiftRightUnsigned(56).toInt() >>> 0;
- offset += size;
- var capacity11 = this.buffer.byteLength;
- if (offset > capacity11)
- this.resize((capacity11 *= 2) > offset ? capacity11 : offset);
- offset -= size;
- switch (size) {
- case 10: this.view[offset+9] = (part2 >>> 7) & 0x01;
- case 9 : this.view[offset+8] = size !== 9 ? (part2 ) | 0x80 : (part2 ) & 0x7F;
- case 8 : this.view[offset+7] = size !== 8 ? (part1 >>> 21) | 0x80 : (part1 >>> 21) & 0x7F;
- case 7 : this.view[offset+6] = size !== 7 ? (part1 >>> 14) | 0x80 : (part1 >>> 14) & 0x7F;
- case 6 : this.view[offset+5] = size !== 6 ? (part1 >>> 7) | 0x80 : (part1 >>> 7) & 0x7F;
- case 5 : this.view[offset+4] = size !== 5 ? (part1 ) | 0x80 : (part1 ) & 0x7F;
- case 4 : this.view[offset+3] = size !== 4 ? (part0 >>> 21) | 0x80 : (part0 >>> 21) & 0x7F;
- case 3 : this.view[offset+2] = size !== 3 ? (part0 >>> 14) | 0x80 : (part0 >>> 14) & 0x7F;
- case 2 : this.view[offset+1] = size !== 2 ? (part0 >>> 7) | 0x80 : (part0 >>> 7) & 0x7F;
- case 1 : this.view[offset ] = size !== 1 ? (part0 ) | 0x80 : (part0 ) & 0x7F;
- }
- if (relative) {
- this.offset += size;
- return this;
- } else {
- return size;
- }
- };
-
- /**
- * Writes a zig-zag encoded 64bit base 128 variable-length integer.
- * @param {number|Long} value Value to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeVarint64ZigZag = function(value, offset) {
- return this.writeVarint64(ByteBuffer.zigZagEncode64(value), offset);
- };
-
- /**
- * Reads a 64bit base 128 variable-length integer. Requires Long.js.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
- * the actual number of bytes read.
- * @throws {Error} If it's not a valid varint
- * @expose
- */
- ByteBufferPrototype.readVarint64 = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- // ref: src/google/protobuf/io/coded_stream.cc
- var start = offset,
- part0 = 0,
- part1 = 0,
- part2 = 0,
- b = 0;
- b = this.view[offset++]; part0 = (b & 0x7F) ; if ( b & 0x80 ) {
- b = this.view[offset++]; part0 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part0 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part0 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 |= (b & 0x7F) << 14; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part1 |= (b & 0x7F) << 21; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part2 = (b & 0x7F) ; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- b = this.view[offset++]; part2 |= (b & 0x7F) << 7; if ((b & 0x80) || (this.noAssert && typeof b === 'undefined')) {
- throw Error("Buffer overrun"); }}}}}}}}}}
- var value = Long.fromBits(part0 | (part1 << 28), (part1 >>> 4) | (part2) << 24, false);
- if (relative) {
- this.offset = offset;
- return value;
- } else {
- return {
- 'value': value,
- 'length': offset-start
- };
- }
- };
-
- /**
- * Reads a zig-zag encoded 64bit base 128 variable-length integer. Requires Long.js.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {!Long|!{value: Long, length: number}} The value read if offset is omitted, else the value read and
- * the actual number of bytes read.
- * @throws {Error} If it's not a valid varint
- * @expose
- */
- ByteBufferPrototype.readVarint64ZigZag = function(offset) {
- var val = this.readVarint64(offset);
- if (val && val['value'] instanceof Long)
- val["value"] = ByteBuffer.zigZagDecode64(val["value"]);
- else
- val = ByteBuffer.zigZagDecode64(val);
- return val;
- };
-
- } // Long
-
-
- // types/strings/cstring
-
- /**
- * Writes a NULL-terminated UTF8 encoded string. For this to work the specified string must not contain any NULL
- * characters itself.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * contained in `str` + 1 if omitted.
- * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written
- * @expose
- */
- ByteBufferPrototype.writeCString = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- var i,
- k = str.length;
- if (!this.noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- for (i=0; i>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- // UTF8 strings do not contain zero bytes in between except for the zero character, so:
- k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
- offset += k+1;
- var capacity12 = this.buffer.byteLength;
- if (offset > capacity12)
- this.resize((capacity12 *= 2) > offset ? capacity12 : offset);
- offset -= k+1;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- this.view[offset++] = 0;
- if (relative) {
- this.offset = offset;
- return this;
- }
- return k;
- };
-
- /**
- * Reads a NULL-terminated UTF8 encoded string. For this to work the string read must not contain any NULL characters
- * itself.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- */
- ByteBufferPrototype.readCString = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var start = offset,
- temp;
- // UTF8 strings do not contain zero bytes in between except for the zero character itself, so:
- var sd, b = -1;
- utfx.decodeUTF8toUTF16(function() {
- if (b === 0) return null;
- if (offset >= this.limit)
- throw RangeError("Illegal range: Truncated data, "+offset+" < "+this.limit);
- b = this.view[offset++];
- return b === 0 ? null : b;
- }.bind(this), sd = stringDestination(), true);
- if (relative) {
- this.offset = offset;
- return sd();
- } else {
- return {
- "string": sd(),
- "length": offset - start
- };
- }
- };
-
- // types/strings/istring
-
- /**
- * Writes a length as uint32 prefixed UTF8 encoded string.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
- * @expose
- * @see ByteBuffer#writeVarint32
- */
- ByteBufferPrototype.writeIString = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var start = offset,
- k;
- k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
- offset += 4+k;
- var capacity13 = this.buffer.byteLength;
- if (offset > capacity13)
- this.resize((capacity13 *= 2) > offset ? capacity13 : offset);
- offset -= 4+k;
- if (this.littleEndian) {
- this.view[offset+3] = (k >>> 24) & 0xFF;
- this.view[offset+2] = (k >>> 16) & 0xFF;
- this.view[offset+1] = (k >>> 8) & 0xFF;
- this.view[offset ] = k & 0xFF;
- } else {
- this.view[offset ] = (k >>> 24) & 0xFF;
- this.view[offset+1] = (k >>> 16) & 0xFF;
- this.view[offset+2] = (k >>> 8) & 0xFF;
- this.view[offset+3] = k & 0xFF;
- }
- offset += 4;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- if (offset !== start + 4 + k)
- throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+4+k));
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- };
-
- /**
- * Reads a length as uint32 prefixed UTF8 encoded string.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- * @see ByteBuffer#readVarint32
- */
- ByteBufferPrototype.readIString = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 4 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+4+") <= "+this.buffer.byteLength);
- }
- var start = offset;
- var len = this.readUint32(offset);
- var str = this.readUTF8String(len, ByteBuffer.METRICS_BYTES, offset += 4);
- offset += str['length'];
- if (relative) {
- this.offset = offset;
- return str['string'];
- } else {
- return {
- 'string': str['string'],
- 'length': offset - start
- };
- }
- };
-
- // types/strings/utf8string
-
- /**
- * Metrics representing number of UTF8 characters. Evaluates to `c`.
- * @type {string}
- * @const
- * @expose
- */
- ByteBuffer.METRICS_CHARS = 'c';
-
- /**
- * Metrics representing number of bytes. Evaluates to `b`.
- * @type {string}
- * @const
- * @expose
- */
- ByteBuffer.METRICS_BYTES = 'b';
-
- /**
- * Writes an UTF8 encoded string.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
- * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeUTF8String = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var k;
- var start = offset;
- k = utfx.calculateUTF16asUTF8(stringSource(str))[1];
- offset += k;
- var capacity14 = this.buffer.byteLength;
- if (offset > capacity14)
- this.resize((capacity14 *= 2) > offset ? capacity14 : offset);
- offset -= k;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- };
-
- /**
- * Writes an UTF8 encoded string. This is an alias of {@link ByteBuffer#writeUTF8String}.
- * @function
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} if omitted.
- * @returns {!ByteBuffer|number} this if offset is omitted, else the actual number of bytes written.
- * @expose
- */
- ByteBufferPrototype.writeString = ByteBufferPrototype.writeUTF8String;
-
- /**
- * Calculates the number of UTF8 characters of a string. JavaScript itself uses UTF-16, so that a string's
- * `length` property does not reflect its actual UTF8 size if it contains code points larger than 0xFFFF.
- * @param {string} str String to calculate
- * @returns {number} Number of UTF8 characters
- * @expose
- */
- ByteBuffer.calculateUTF8Chars = function(str) {
- return utfx.calculateUTF16asUTF8(stringSource(str))[0];
- };
-
- /**
- * Calculates the number of UTF8 bytes of a string.
- * @param {string} str String to calculate
- * @returns {number} Number of UTF8 bytes
- * @expose
- */
- ByteBuffer.calculateUTF8Bytes = function(str) {
- return utfx.calculateUTF16asUTF8(stringSource(str))[1];
- };
-
- /**
- * Calculates the number of UTF8 bytes of a string. This is an alias of {@link ByteBuffer.calculateUTF8Bytes}.
- * @function
- * @param {string} str String to calculate
- * @returns {number} Number of UTF8 bytes
- * @expose
- */
- ByteBuffer.calculateString = ByteBuffer.calculateUTF8Bytes;
-
- /**
- * Reads an UTF8 encoded string.
- * @param {number} length Number of characters or bytes to read.
- * @param {string=} metrics Metrics specifying what `length` is meant to count. Defaults to
- * {@link ByteBuffer.METRICS_CHARS}.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- */
- ByteBufferPrototype.readUTF8String = function(length, metrics, offset) {
- if (typeof metrics === 'number') {
- offset = metrics;
- metrics = undefined;
- }
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (typeof metrics === 'undefined') metrics = ByteBuffer.METRICS_CHARS;
- if (!this.noAssert) {
- if (typeof length !== 'number' || length % 1 !== 0)
- throw TypeError("Illegal length: "+length+" (not an integer)");
- length |= 0;
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var i = 0,
- start = offset,
- sd;
- if (metrics === ByteBuffer.METRICS_CHARS) { // The same for node and the browser
- sd = stringDestination();
- utfx.decodeUTF8(function() {
- return i < length && offset < this.limit ? this.view[offset++] : null;
- }.bind(this), function(cp) {
- ++i; utfx.UTF8toUTF16(cp, sd);
- });
- if (i !== length)
- throw RangeError("Illegal range: Truncated data, "+i+" == "+length);
- if (relative) {
- this.offset = offset;
- return sd();
- } else {
- return {
- "string": sd(),
- "length": offset - start
- };
- }
- } else if (metrics === ByteBuffer.METRICS_BYTES) {
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + length > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+length+") <= "+this.buffer.byteLength);
- }
- var k = offset + length;
- utfx.decodeUTF8toUTF16(function() {
- return offset < k ? this.view[offset++] : null;
- }.bind(this), sd = stringDestination(), this.noAssert);
- if (offset !== k)
- throw RangeError("Illegal range: Truncated data, "+offset+" == "+k);
- if (relative) {
- this.offset = offset;
- return sd();
- } else {
- return {
- 'string': sd(),
- 'length': offset - start
- };
- }
- } else
- throw TypeError("Unsupported metrics: "+metrics);
- };
-
- /**
- * Reads an UTF8 encoded string. This is an alias of {@link ByteBuffer#readUTF8String}.
- * @function
- * @param {number} length Number of characters or bytes to read
- * @param {number=} metrics Metrics specifying what `n` is meant to count. Defaults to
- * {@link ByteBuffer.METRICS_CHARS}.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- */
- ByteBufferPrototype.readString = ByteBufferPrototype.readUTF8String;
-
- // types/strings/vstring
-
- /**
- * Writes a length as varint32 prefixed UTF8 encoded string.
- * @param {string} str String to write
- * @param {number=} offset Offset to write to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer|number} `this` if `offset` is omitted, else the actual number of bytes written
- * @expose
- * @see ByteBuffer#writeVarint32
- */
- ByteBufferPrototype.writeVString = function(str, offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- var start = offset,
- k, l;
- k = utfx.calculateUTF16asUTF8(stringSource(str), this.noAssert)[1];
- l = ByteBuffer.calculateVarint32(k);
- offset += l+k;
- var capacity15 = this.buffer.byteLength;
- if (offset > capacity15)
- this.resize((capacity15 *= 2) > offset ? capacity15 : offset);
- offset -= l+k;
- offset += this.writeVarint32(k, offset);
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- this.view[offset++] = b;
- }.bind(this));
- if (offset !== start+k+l)
- throw RangeError("Illegal range: Truncated data, "+offset+" == "+(offset+k+l));
- if (relative) {
- this.offset = offset;
- return this;
- }
- return offset - start;
- };
-
- /**
- * Reads a length as varint32 prefixed UTF8 encoded string.
- * @param {number=} offset Offset to read from. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {string|!{string: string, length: number}} The string read if offset is omitted, else the string
- * read and the actual number of bytes read.
- * @expose
- * @see ByteBuffer#readVarint32
- */
- ByteBufferPrototype.readVString = function(offset) {
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 1 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+1+") <= "+this.buffer.byteLength);
- }
- var start = offset;
- var len = this.readVarint32(offset);
- var str = this.readUTF8String(len['value'], ByteBuffer.METRICS_BYTES, offset += len['length']);
- offset += str['length'];
- if (relative) {
- this.offset = offset;
- return str['string'];
- } else {
- return {
- 'string': str['string'],
- 'length': offset - start
- };
- }
- };
-
-
- /**
- * Appends some data to this ByteBuffer. This will overwrite any contents behind the specified offset up to the appended
- * data's length.
- * @param {!ByteBuffer|!ArrayBuffer|!Uint8Array|string} source Data to append. If `source` is a ByteBuffer, its offsets
- * will be modified according to the performed read operation.
- * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
- * @param {number=} offset Offset to append at. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @example A relative `<01 02>03.append(<04 05>)` will result in `<01 02 04 05>, 04 05|`
- * @example An absolute `<01 02>03.append(04 05>, 1)` will result in `<01 04>05, 04 05|`
- */
- ByteBufferPrototype.append = function(source, encoding, offset) {
- if (typeof encoding === 'number' || typeof encoding !== 'string') {
- offset = encoding;
- encoding = undefined;
- }
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (!(source instanceof ByteBuffer))
- source = ByteBuffer.wrap(source, encoding);
- var length = source.limit - source.offset;
- if (length <= 0) return this; // Nothing to append
- offset += length;
- var capacity16 = this.buffer.byteLength;
- if (offset > capacity16)
- this.resize((capacity16 *= 2) > offset ? capacity16 : offset);
- offset -= length;
- this.view.set(source.view.subarray(source.offset, source.limit), offset);
- source.offset += length;
- if (relative) this.offset += length;
- return this;
- };
-
- /**
- * Appends this ByteBuffer's contents to another ByteBuffer. This will overwrite any contents at and after the
- specified offset up to the length of this ByteBuffer's data.
- * @param {!ByteBuffer} target Target ByteBuffer
- * @param {number=} offset Offset to append to. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * read if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @see ByteBuffer#append
- */
- ByteBufferPrototype.appendTo = function(target, offset) {
- target.append(this, offset);
- return this;
- };
-
- /**
- * Enables or disables assertions of argument types and offsets. Assertions are enabled by default but you can opt to
- * disable them if your code already makes sure that everything is valid.
- * @param {boolean} assert `true` to enable assertions, otherwise `false`
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.assert = function(assert) {
- this.noAssert = !assert;
- return this;
- };
-
- /**
- * Gets the capacity of this ByteBuffer's backing buffer.
- * @returns {number} Capacity of the backing buffer
- * @expose
- */
- ByteBufferPrototype.capacity = function() {
- return this.buffer.byteLength;
- };
- /**
- * Clears this ByteBuffer's offsets by setting {@link ByteBuffer#offset} to `0` and {@link ByteBuffer#limit} to the
- * backing buffer's capacity. Discards {@link ByteBuffer#markedOffset}.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.clear = function() {
- this.offset = 0;
- this.limit = this.buffer.byteLength;
- this.markedOffset = -1;
- return this;
- };
-
- /**
- * Creates a cloned instance of this ByteBuffer, preset with this ByteBuffer's values for {@link ByteBuffer#offset},
- * {@link ByteBuffer#markedOffset} and {@link ByteBuffer#limit}.
- * @param {boolean=} copy Whether to copy the backing buffer or to return another view on the same, defaults to `false`
- * @returns {!ByteBuffer} Cloned instance
- * @expose
- */
- ByteBufferPrototype.clone = function(copy) {
- var bb = new ByteBuffer(0, this.littleEndian, this.noAssert);
- if (copy) {
- bb.buffer = new ArrayBuffer(this.buffer.byteLength);
- bb.view = new Uint8Array(bb.buffer);
- } else {
- bb.buffer = this.buffer;
- bb.view = this.view;
- }
- bb.offset = this.offset;
- bb.markedOffset = this.markedOffset;
- bb.limit = this.limit;
- return bb;
- };
-
- /**
- * Compacts this ByteBuffer to be backed by a {@link ByteBuffer#buffer} of its contents' length. Contents are the bytes
- * between {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. Will set `offset = 0` and `limit = capacity` and
- * adapt {@link ByteBuffer#markedOffset} to the same relative position if set.
- * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.compact = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin === 0 && end === this.buffer.byteLength)
- return this; // Already compacted
- var len = end - begin;
- if (len === 0) {
- this.buffer = EMPTY_BUFFER;
- this.view = null;
- if (this.markedOffset >= 0) this.markedOffset -= begin;
- this.offset = 0;
- this.limit = 0;
- return this;
- }
- var buffer = new ArrayBuffer(len);
- var view = new Uint8Array(buffer);
- view.set(this.view.subarray(begin, end));
- this.buffer = buffer;
- this.view = view;
- if (this.markedOffset >= 0) this.markedOffset -= begin;
- this.offset = 0;
- this.limit = len;
- return this;
- };
-
- /**
- * Creates a copy of this ByteBuffer's contents. Contents are the bytes between {@link ByteBuffer#offset} and
- * {@link ByteBuffer#limit}.
- * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
- * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
- * @returns {!ByteBuffer} Copy
- * @expose
- */
- ByteBufferPrototype.copy = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin === end)
- return new ByteBuffer(0, this.littleEndian, this.noAssert);
- var capacity = end - begin,
- bb = new ByteBuffer(capacity, this.littleEndian, this.noAssert);
- bb.offset = 0;
- bb.limit = capacity;
- if (bb.markedOffset >= 0) bb.markedOffset -= begin;
- this.copyTo(bb, 0, begin, end);
- return bb;
- };
-
- /**
- * Copies this ByteBuffer's contents to another ByteBuffer. Contents are the bytes between {@link ByteBuffer#offset} and
- * {@link ByteBuffer#limit}.
- * @param {!ByteBuffer} target Target ByteBuffer
- * @param {number=} targetOffset Offset to copy to. Will use and increase the target's {@link ByteBuffer#offset}
- * by the number of bytes copied if omitted.
- * @param {number=} sourceOffset Offset to start copying from. Will use and increase {@link ByteBuffer#offset} by the
- * number of bytes copied if omitted.
- * @param {number=} sourceLimit Offset to end copying from, defaults to {@link ByteBuffer#limit}
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.copyTo = function(target, targetOffset, sourceOffset, sourceLimit) {
- var relative,
- targetRelative;
- if (!this.noAssert) {
- if (!ByteBuffer.isByteBuffer(target))
- throw TypeError("Illegal target: Not a ByteBuffer");
- }
- targetOffset = (targetRelative = typeof targetOffset === 'undefined') ? target.offset : targetOffset | 0;
- sourceOffset = (relative = typeof sourceOffset === 'undefined') ? this.offset : sourceOffset | 0;
- sourceLimit = typeof sourceLimit === 'undefined' ? this.limit : sourceLimit | 0;
-
- if (targetOffset < 0 || targetOffset > target.buffer.byteLength)
- throw RangeError("Illegal target range: 0 <= "+targetOffset+" <= "+target.buffer.byteLength);
- if (sourceOffset < 0 || sourceLimit > this.buffer.byteLength)
- throw RangeError("Illegal source range: 0 <= "+sourceOffset+" <= "+this.buffer.byteLength);
-
- var len = sourceLimit - sourceOffset;
- if (len === 0)
- return target; // Nothing to copy
-
- target.ensureCapacity(targetOffset + len);
-
- target.view.set(this.view.subarray(sourceOffset, sourceLimit), targetOffset);
-
- if (relative) this.offset += len;
- if (targetRelative) target.offset += len;
-
- return this;
- };
-
- /**
- * Makes sure that this ByteBuffer is backed by a {@link ByteBuffer#buffer} of at least the specified capacity. If the
- * current capacity is exceeded, it will be doubled. If double the current capacity is less than the required capacity,
- * the required capacity will be used instead.
- * @param {number} capacity Required capacity
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.ensureCapacity = function(capacity) {
- var current = this.buffer.byteLength;
- if (current < capacity)
- return this.resize((current *= 2) > capacity ? current : capacity);
- return this;
- };
-
- /**
- * Overwrites this ByteBuffer's contents with the specified value. Contents are the bytes between
- * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
- * @param {number|string} value Byte value to fill with. If given as a string, the first character is used.
- * @param {number=} begin Begin offset. Will use and increase {@link ByteBuffer#offset} by the number of bytes
- * written if omitted. defaults to {@link ByteBuffer#offset}.
- * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
- * @returns {!ByteBuffer} this
- * @expose
- * @example `someByteBuffer.clear().fill(0)` fills the entire backing buffer with zeroes
- */
- ByteBufferPrototype.fill = function(value, begin, end) {
- var relative = typeof begin === 'undefined';
- if (relative) begin = this.offset;
- if (typeof value === 'string' && value.length > 0)
- value = value.charCodeAt(0);
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof value !== 'number' || value % 1 !== 0)
- throw TypeError("Illegal value: "+value+" (not an integer)");
- value |= 0;
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin >= end)
- return this; // Nothing to fill
- while (begin < end) this.view[begin++] = value;
- if (relative) this.offset = begin;
- return this;
- };
-
- /**
- * Makes this ByteBuffer ready for a new sequence of write or relative read operations. Sets `limit = offset` and
- * `offset = 0`. Make sure always to flip a ByteBuffer when all relative read or write operations are complete.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.flip = function() {
- this.limit = this.offset;
- this.offset = 0;
- return this;
- };
- /**
- * Marks an offset on this ByteBuffer to be used later.
- * @param {number=} offset Offset to mark. Defaults to {@link ByteBuffer#offset}.
- * @returns {!ByteBuffer} this
- * @throws {TypeError} If `offset` is not a valid number
- * @throws {RangeError} If `offset` is out of bounds
- * @see ByteBuffer#reset
- * @expose
- */
- ByteBufferPrototype.mark = function(offset) {
- offset = typeof offset === 'undefined' ? this.offset : offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- this.markedOffset = offset;
- return this;
- };
- /**
- * Sets the byte order.
- * @param {boolean} littleEndian `true` for little endian byte order, `false` for big endian
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.order = function(littleEndian) {
- if (!this.noAssert) {
- if (typeof littleEndian !== 'boolean')
- throw TypeError("Illegal littleEndian: Not a boolean");
- }
- this.littleEndian = !!littleEndian;
- return this;
- };
-
- /**
- * Switches (to) little endian byte order.
- * @param {boolean=} littleEndian Defaults to `true`, otherwise uses big endian
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.LE = function(littleEndian) {
- this.littleEndian = typeof littleEndian !== 'undefined' ? !!littleEndian : true;
- return this;
- };
-
- /**
- * Switches (to) big endian byte order.
- * @param {boolean=} bigEndian Defaults to `true`, otherwise uses little endian
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.BE = function(bigEndian) {
- this.littleEndian = typeof bigEndian !== 'undefined' ? !bigEndian : false;
- return this;
- };
- /**
- * Prepends some data to this ByteBuffer. This will overwrite any contents before the specified offset up to the
- * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
- * will be resized and its contents moved accordingly.
- * @param {!ByteBuffer|string|!ArrayBuffer} source Data to prepend. If `source` is a ByteBuffer, its offset will be
- * modified according to the performed read operation.
- * @param {(string|number)=} encoding Encoding if `data` is a string ("base64", "hex", "binary", defaults to "utf8")
- * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
- * prepended if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @example A relative `00<01 02 03>.prepend(<04 05>)` results in `<04 05 01 02 03>, 04 05|`
- * @example An absolute `00<01 02 03>.prepend(<04 05>, 2)` results in `04<05 02 03>, 04 05|`
- */
- ByteBufferPrototype.prepend = function(source, encoding, offset) {
- if (typeof encoding === 'number' || typeof encoding !== 'string') {
- offset = encoding;
- encoding = undefined;
- }
- var relative = typeof offset === 'undefined';
- if (relative) offset = this.offset;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: "+offset+" (not an integer)");
- offset >>>= 0;
- if (offset < 0 || offset + 0 > this.buffer.byteLength)
- throw RangeError("Illegal offset: 0 <= "+offset+" (+"+0+") <= "+this.buffer.byteLength);
- }
- if (!(source instanceof ByteBuffer))
- source = ByteBuffer.wrap(source, encoding);
- var len = source.limit - source.offset;
- if (len <= 0) return this; // Nothing to prepend
- var diff = len - offset;
- if (diff > 0) { // Not enough space before offset, so resize + move
- var buffer = new ArrayBuffer(this.buffer.byteLength + diff);
- var view = new Uint8Array(buffer);
- view.set(this.view.subarray(offset, this.buffer.byteLength), len);
- this.buffer = buffer;
- this.view = view;
- this.offset += diff;
- if (this.markedOffset >= 0) this.markedOffset += diff;
- this.limit += diff;
- offset += diff;
- } else {
- var arrayView = new Uint8Array(this.buffer);
- }
- this.view.set(source.view.subarray(source.offset, source.limit), offset - len);
-
- source.offset = source.limit;
- if (relative)
- this.offset -= len;
- return this;
- };
-
- /**
- * Prepends this ByteBuffer to another ByteBuffer. This will overwrite any contents before the specified offset up to the
- * prepended data's length. If there is not enough space available before the specified `offset`, the backing buffer
- * will be resized and its contents moved accordingly.
- * @param {!ByteBuffer} target Target ByteBuffer
- * @param {number=} offset Offset to prepend at. Will use and decrease {@link ByteBuffer#offset} by the number of bytes
- * prepended if omitted.
- * @returns {!ByteBuffer} this
- * @expose
- * @see ByteBuffer#prepend
- */
- ByteBufferPrototype.prependTo = function(target, offset) {
- target.prepend(this, offset);
- return this;
- };
- /**
- * Prints debug information about this ByteBuffer's contents.
- * @param {function(string)=} out Output function to call, defaults to console.log
- * @expose
- */
- ByteBufferPrototype.printDebug = function(out) {
- if (typeof out !== 'function') out = console.log.bind(console);
- out(
- this.toString()+"\n"+
- "-------------------------------------------------------------------\n"+
- this.toDebug(/* columns */ true)
- );
- };
-
- /**
- * Gets the number of remaining readable bytes. Contents are the bytes between {@link ByteBuffer#offset} and
- * {@link ByteBuffer#limit}, so this returns `limit - offset`.
- * @returns {number} Remaining readable bytes. May be negative if `offset > limit`.
- * @expose
- */
- ByteBufferPrototype.remaining = function() {
- return this.limit - this.offset;
- };
- /**
- * Resets this ByteBuffer's {@link ByteBuffer#offset}. If an offset has been marked through {@link ByteBuffer#mark}
- * before, `offset` will be set to {@link ByteBuffer#markedOffset}, which will then be discarded. If no offset has been
- * marked, sets `offset = 0`.
- * @returns {!ByteBuffer} this
- * @see ByteBuffer#mark
- * @expose
- */
- ByteBufferPrototype.reset = function() {
- if (this.markedOffset >= 0) {
- this.offset = this.markedOffset;
- this.markedOffset = -1;
- } else {
- this.offset = 0;
- }
- return this;
- };
- /**
- * Resizes this ByteBuffer to be backed by a buffer of at least the given capacity. Will do nothing if already that
- * large or larger.
- * @param {number} capacity Capacity required
- * @returns {!ByteBuffer} this
- * @throws {TypeError} If `capacity` is not a number
- * @throws {RangeError} If `capacity < 0`
- * @expose
- */
- ByteBufferPrototype.resize = function(capacity) {
- if (!this.noAssert) {
- if (typeof capacity !== 'number' || capacity % 1 !== 0)
- throw TypeError("Illegal capacity: "+capacity+" (not an integer)");
- capacity |= 0;
- if (capacity < 0)
- throw RangeError("Illegal capacity: 0 <= "+capacity);
- }
- if (this.buffer.byteLength < capacity) {
- var buffer = new ArrayBuffer(capacity);
- var view = new Uint8Array(buffer);
- view.set(this.view);
- this.buffer = buffer;
- this.view = view;
- }
- return this;
- };
- /**
- * Reverses this ByteBuffer's contents.
- * @param {number=} begin Offset to start at, defaults to {@link ByteBuffer#offset}
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.reverse = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- if (begin === end)
- return this; // Nothing to reverse
- Array.prototype.reverse.call(this.view.subarray(begin, end));
- return this;
- };
- /**
- * Skips the next `length` bytes. This will just advance
- * @param {number} length Number of bytes to skip. May also be negative to move the offset back.
- * @returns {!ByteBuffer} this
- * @expose
- */
- ByteBufferPrototype.skip = function(length) {
- if (!this.noAssert) {
- if (typeof length !== 'number' || length % 1 !== 0)
- throw TypeError("Illegal length: "+length+" (not an integer)");
- length |= 0;
- }
- var offset = this.offset + length;
- if (!this.noAssert) {
- if (offset < 0 || offset > this.buffer.byteLength)
- throw RangeError("Illegal length: 0 <= "+this.offset+" + "+length+" <= "+this.buffer.byteLength);
- }
- this.offset = offset;
- return this;
- };
-
- /**
- * Slices this ByteBuffer by creating a cloned instance with `offset = begin` and `limit = end`.
- * @param {number=} begin Begin offset, defaults to {@link ByteBuffer#offset}.
- * @param {number=} end End offset, defaults to {@link ByteBuffer#limit}.
- * @returns {!ByteBuffer} Clone of this ByteBuffer with slicing applied, backed by the same {@link ByteBuffer#buffer}
- * @expose
- */
- ByteBufferPrototype.slice = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- var bb = this.clone();
- bb.offset = begin;
- bb.limit = end;
- return bb;
- };
- /**
- * Returns a copy of the backing buffer that contains this ByteBuffer's contents. Contents are the bytes between
- * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}.
- * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory if
- * possible. Defaults to `false`
- * @returns {!ArrayBuffer} Contents as an ArrayBuffer
- * @expose
- */
- ByteBufferPrototype.toBuffer = function(forceCopy) {
- var offset = this.offset,
- limit = this.limit;
- if (!this.noAssert) {
- if (typeof offset !== 'number' || offset % 1 !== 0)
- throw TypeError("Illegal offset: Not an integer");
- offset >>>= 0;
- if (typeof limit !== 'number' || limit % 1 !== 0)
- throw TypeError("Illegal limit: Not an integer");
- limit >>>= 0;
- if (offset < 0 || offset > limit || limit > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+offset+" <= "+limit+" <= "+this.buffer.byteLength);
- }
- // NOTE: It's not possible to have another ArrayBuffer reference the same memory as the backing buffer. This is
- // possible with Uint8Array#subarray only, but we have to return an ArrayBuffer by contract. So:
- if (!forceCopy && offset === 0 && limit === this.buffer.byteLength)
- return this.buffer;
- if (offset === limit)
- return EMPTY_BUFFER;
- var buffer = new ArrayBuffer(limit - offset);
- new Uint8Array(buffer).set(new Uint8Array(this.buffer).subarray(offset, limit), 0);
- return buffer;
- };
-
- /**
- * Returns a raw buffer compacted to contain this ByteBuffer's contents. Contents are the bytes between
- * {@link ByteBuffer#offset} and {@link ByteBuffer#limit}. This is an alias of {@link ByteBuffer#toBuffer}.
- * @function
- * @param {boolean=} forceCopy If `true` returns a copy, otherwise returns a view referencing the same memory.
- * Defaults to `false`
- * @returns {!ArrayBuffer} Contents as an ArrayBuffer
- * @expose
- */
- ByteBufferPrototype.toArrayBuffer = ByteBufferPrototype.toBuffer;
-
- /**
- * Converts the ByteBuffer's contents to a string.
- * @param {string=} encoding Output encoding. Returns an informative string representation if omitted but also allows
- * direct conversion to "utf8", "hex", "base64" and "binary" encoding. "debug" returns a hex representation with
- * highlighted offsets.
- * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}
- * @returns {string} String representation
- * @throws {Error} If `encoding` is invalid
- * @expose
- */
- ByteBufferPrototype.toString = function(encoding, begin, end) {
- if (typeof encoding === 'undefined')
- return "ByteBufferAB(offset="+this.offset+",markedOffset="+this.markedOffset+",limit="+this.limit+",capacity="+this.capacity()+")";
- if (typeof encoding === 'number')
- encoding = "utf8",
- begin = encoding,
- end = begin;
- switch (encoding) {
- case "utf8":
- return this.toUTF8(begin, end);
- case "base64":
- return this.toBase64(begin, end);
- case "hex":
- return this.toHex(begin, end);
- case "binary":
- return this.toBinary(begin, end);
- case "debug":
- return this.toDebug();
- case "columns":
- return this.toColumns();
- default:
- throw Error("Unsupported encoding: "+encoding);
- }
- };
-
- // lxiv-embeddable
-
- /**
- * lxiv-embeddable (c) 2014 Daniel Wirtz
- * Released under the Apache License, Version 2.0
- * see: https://github.com/dcodeIO/lxiv for details
- */
- var lxiv = function() {
- "use strict";
-
- /**
- * lxiv namespace.
- * @type {!Object.}
- * @exports lxiv
- */
- var lxiv = {};
-
- /**
- * Character codes for output.
- * @type {!Array.}
- * @inner
- */
- var aout = [
- 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80,
- 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 97, 98, 99, 100, 101, 102,
- 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118,
- 119, 120, 121, 122, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 43, 47
- ];
-
- /**
- * Character codes for input.
- * @type {!Array.}
- * @inner
- */
- var ain = [];
- for (var i=0, k=aout.length; i>2)&0x3f]);
- t = (b&0x3)<<4;
- if ((b = src()) !== null) {
- t |= (b>>4)&0xf;
- dst(aout[(t|((b>>4)&0xf))&0x3f]);
- t = (b&0xf)<<2;
- if ((b = src()) !== null)
- dst(aout[(t|((b>>6)&0x3))&0x3f]),
- dst(aout[b&0x3f]);
- else
- dst(aout[t&0x3f]),
- dst(61);
- } else
- dst(aout[t&0x3f]),
- dst(61),
- dst(61);
- }
- };
-
- /**
- * Decodes base64 char codes to bytes.
- * @param {!function():number|null} src Characters source as a function returning the next char code respectively
- * `null` if there are no more characters left.
- * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
- * @throws {Error} If a character code is invalid
- */
- lxiv.decode = function(src, dst) {
- var c, t1, t2;
- function fail(c) {
- throw Error("Illegal character code: "+c);
- }
- while ((c = src()) !== null) {
- t1 = ain[c];
- if (typeof t1 === 'undefined') fail(c);
- if ((c = src()) !== null) {
- t2 = ain[c];
- if (typeof t2 === 'undefined') fail(c);
- dst((t1<<2)>>>0|(t2&0x30)>>4);
- if ((c = src()) !== null) {
- t1 = ain[c];
- if (typeof t1 === 'undefined')
- if (c === 61) break; else fail(c);
- dst(((t2&0xf)<<4)>>>0|(t1&0x3c)>>2);
- if ((c = src()) !== null) {
- t2 = ain[c];
- if (typeof t2 === 'undefined')
- if (c === 61) break; else fail(c);
- dst(((t1&0x3)<<6)>>>0|t2);
- }
- }
- }
- }
- };
-
- /**
- * Tests if a string is valid base64.
- * @param {string} str String to test
- * @returns {boolean} `true` if valid, otherwise `false`
- */
- lxiv.test = function(str) {
- return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(str);
- };
-
- return lxiv;
- }();
-
- // encodings/base64
-
- /**
- * Encodes this ByteBuffer's contents to a base64 encoded string.
- * @param {number=} begin Offset to begin at, defaults to {@link ByteBuffer#offset}.
- * @param {number=} end Offset to end at, defaults to {@link ByteBuffer#limit}.
- * @returns {string} Base64 encoded string
- * @throws {RangeError} If `begin` or `end` is out of bounds
- * @expose
- */
- ByteBufferPrototype.toBase64 = function(begin, end) {
- if (typeof begin === 'undefined')
- begin = this.offset;
- if (typeof end === 'undefined')
- end = this.limit;
- begin = begin | 0; end = end | 0;
- if (begin < 0 || end > this.capacity || begin > end)
- throw RangeError("begin, end");
- var sd; lxiv.encode(function() {
- return begin < end ? this.view[begin++] : null;
- }.bind(this), sd = stringDestination());
- return sd();
- };
-
- /**
- * Decodes a base64 encoded string to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromBase64 = function(str, littleEndian) {
- if (typeof str !== 'string')
- throw TypeError("str");
- var bb = new ByteBuffer(str.length/4*3, littleEndian),
- i = 0;
- lxiv.decode(stringSource(str), function(b) {
- bb.view[i++] = b;
- });
- bb.limit = i;
- return bb;
- };
-
- /**
- * Encodes a binary string to base64 like `window.btoa` does.
- * @param {string} str Binary string
- * @returns {string} Base64 encoded string
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.btoa
- * @expose
- */
- ByteBuffer.btoa = function(str) {
- return ByteBuffer.fromBinary(str).toBase64();
- };
-
- /**
- * Decodes a base64 encoded string to binary like `window.atob` does.
- * @param {string} b64 Base64 encoded string
- * @returns {string} Binary string
- * @see https://developer.mozilla.org/en-US/docs/Web/API/Window.atob
- * @expose
- */
- ByteBuffer.atob = function(b64) {
- return ByteBuffer.fromBase64(b64).toBinary();
- };
-
- // encodings/binary
-
- /**
- * Encodes this ByteBuffer to a binary encoded string, that is using only characters 0x00-0xFF as bytes.
- * @param {number=} begin Offset to begin at. Defaults to {@link ByteBuffer#offset}.
- * @param {number=} end Offset to end at. Defaults to {@link ByteBuffer#limit}.
- * @returns {string} Binary encoded string
- * @throws {RangeError} If `offset > limit`
- * @expose
- */
- ByteBufferPrototype.toBinary = function(begin, end) {
- if (typeof begin === 'undefined')
- begin = this.offset;
- if (typeof end === 'undefined')
- end = this.limit;
- begin |= 0; end |= 0;
- if (begin < 0 || end > this.capacity() || begin > end)
- throw RangeError("begin, end");
- if (begin === end)
- return "";
- var chars = [],
- parts = [];
- while (begin < end) {
- chars.push(this.view[begin++]);
- if (chars.length >= 1024)
- parts.push(String.fromCharCode.apply(String, chars)),
- chars = [];
- }
- return parts.join('') + String.fromCharCode.apply(String, chars);
- };
-
- /**
- * Decodes a binary encoded string, that is using only characters 0x00-0xFF as bytes, to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromBinary = function(str, littleEndian) {
- if (typeof str !== 'string')
- throw TypeError("str");
- var i = 0,
- k = str.length,
- charCode,
- bb = new ByteBuffer(k, littleEndian);
- while (i 0xff)
- throw RangeError("illegal char code: "+charCode);
- bb.view[i++] = charCode;
- }
- bb.limit = k;
- return bb;
- };
-
- // encodings/debug
-
- /**
- * Encodes this ByteBuffer to a hex encoded string with marked offsets. Offset symbols are:
- * * `<` : offset,
- * * `'` : markedOffset,
- * * `>` : limit,
- * * `|` : offset and limit,
- * * `[` : offset and markedOffset,
- * * `]` : markedOffset and limit,
- * * `!` : offset, markedOffset and limit
- * @param {boolean=} columns If `true` returns two columns hex + ascii, defaults to `false`
- * @returns {string|!Array.} Debug string or array of lines if `asArray = true`
- * @expose
- * @example `>00'01 02<03` contains four bytes with `limit=0, markedOffset=1, offset=3`
- * @example `00[01 02 03>` contains four bytes with `offset=markedOffset=1, limit=4`
- * @example `00|01 02 03` contains four bytes with `offset=limit=1, markedOffset=-1`
- * @example `|` contains zero bytes with `offset=limit=0, markedOffset=-1`
- */
- ByteBufferPrototype.toDebug = function(columns) {
- var i = -1,
- k = this.buffer.byteLength,
- b,
- hex = "",
- asc = "",
- out = "";
- while (i 32 && b < 127 ? String.fromCharCode(b) : '.';
- }
- ++i;
- if (columns) {
- if (i > 0 && i % 16 === 0 && i !== k) {
- while (hex.length < 3*16+3) hex += " ";
- out += hex+asc+"\n";
- hex = asc = "";
- }
- }
- if (i === this.offset && i === this.limit)
- hex += i === this.markedOffset ? "!" : "|";
- else if (i === this.offset)
- hex += i === this.markedOffset ? "[" : "<";
- else if (i === this.limit)
- hex += i === this.markedOffset ? "]" : ">";
- else
- hex += i === this.markedOffset ? "'" : (columns || (i !== 0 && i !== k) ? " " : "");
- }
- if (columns && hex !== " ") {
- while (hex.length < 3*16+3)
- hex += " ";
- out += hex + asc + "\n";
- }
- return columns ? out : hex;
- };
-
- /**
- * Decodes a hex encoded string with marked offsets to a ByteBuffer.
- * @param {string} str Debug string to decode (not be generated with `columns = true`)
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- * @see ByteBuffer#toDebug
- */
- ByteBuffer.fromDebug = function(str, littleEndian, noAssert) {
- var k = str.length,
- bb = new ByteBuffer(((k+1)/3)|0, littleEndian, noAssert);
- var i = 0, j = 0, ch, b,
- rs = false, // Require symbol next
- ho = false, hm = false, hl = false, // Already has offset (ho), markedOffset (hm), limit (hl)?
- fail = false;
- while (i':
- if (!noAssert) {
- if (hl) {
- fail = true;
- break;
- }
- hl = true;
- }
- bb.limit = j;
- rs = false;
- break;
- case "'":
- if (!noAssert) {
- if (hm) {
- fail = true;
- break;
- }
- hm = true;
- }
- bb.markedOffset = j;
- rs = false;
- break;
- case ' ':
- rs = false;
- break;
- default:
- if (!noAssert) {
- if (rs) {
- fail = true;
- break;
- }
- }
- b = parseInt(ch+str.charAt(i++), 16);
- if (!noAssert) {
- if (isNaN(b) || b < 0 || b > 255)
- throw TypeError("Illegal str: Not a debug encoded string");
- }
- bb.view[j++] = b;
- rs = true;
- }
- if (fail)
- throw TypeError("Illegal str: Invalid symbol at "+i);
- }
- if (!noAssert) {
- if (!ho || !hl)
- throw TypeError("Illegal str: Missing offset or limit");
- if (j>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- var out = new Array(end - begin),
- b;
- while (begin < end) {
- b = this.view[begin++];
- if (b < 0x10)
- out.push("0", b.toString(16));
- else out.push(b.toString(16));
- }
- return out.join('');
- };
-
- /**
- * Decodes a hex encoded string to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromHex = function(str, littleEndian, noAssert) {
- if (!noAssert) {
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- if (str.length % 2 !== 0)
- throw TypeError("Illegal str: Length not a multiple of 2");
- }
- var k = str.length,
- bb = new ByteBuffer((k / 2) | 0, littleEndian),
- b;
- for (var i=0, j=0; i 255)
- throw TypeError("Illegal str: Contains non-hex characters");
- bb.view[j++] = b;
- }
- bb.limit = j;
- return bb;
- };
-
- // utfx-embeddable
-
- /**
- * utfx-embeddable (c) 2014 Daniel Wirtz
- * Released under the Apache License, Version 2.0
- * see: https://github.com/dcodeIO/utfx for details
- */
- var utfx = function() {
- "use strict";
-
- /**
- * utfx namespace.
- * @inner
- * @type {!Object.}
- */
- var utfx = {};
-
- /**
- * Maximum valid code point.
- * @type {number}
- * @const
- */
- utfx.MAX_CODEPOINT = 0x10FFFF;
-
- /**
- * Encodes UTF8 code points to UTF8 bytes.
- * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
- * respectively `null` if there are no more code points left or a single numeric code point.
- * @param {!function(number)} dst Bytes destination as a function successively called with the next byte
- */
- utfx.encodeUTF8 = function(src, dst) {
- var cp = null;
- if (typeof src === 'number')
- cp = src,
- src = function() { return null; };
- while (cp !== null || (cp = src()) !== null) {
- if (cp < 0x80)
- dst(cp&0x7F);
- else if (cp < 0x800)
- dst(((cp>>6)&0x1F)|0xC0),
- dst((cp&0x3F)|0x80);
- else if (cp < 0x10000)
- dst(((cp>>12)&0x0F)|0xE0),
- dst(((cp>>6)&0x3F)|0x80),
- dst((cp&0x3F)|0x80);
- else
- dst(((cp>>18)&0x07)|0xF0),
- dst(((cp>>12)&0x3F)|0x80),
- dst(((cp>>6)&0x3F)|0x80),
- dst((cp&0x3F)|0x80);
- cp = null;
- }
- };
-
- /**
- * Decodes UTF8 bytes to UTF8 code points.
- * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
- * are no more bytes left.
- * @param {!function(number)} dst Code points destination as a function successively called with each decoded code point.
- * @throws {RangeError} If a starting byte is invalid in UTF8
- * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the
- * remaining bytes.
- */
- utfx.decodeUTF8 = function(src, dst) {
- var a, b, c, d, fail = function(b) {
- b = b.slice(0, b.indexOf(null));
- var err = Error(b.toString());
- err.name = "TruncatedError";
- err['bytes'] = b;
- throw err;
- };
- while ((a = src()) !== null) {
- if ((a&0x80) === 0)
- dst(a);
- else if ((a&0xE0) === 0xC0)
- ((b = src()) === null) && fail([a, b]),
- dst(((a&0x1F)<<6) | (b&0x3F));
- else if ((a&0xF0) === 0xE0)
- ((b=src()) === null || (c=src()) === null) && fail([a, b, c]),
- dst(((a&0x0F)<<12) | ((b&0x3F)<<6) | (c&0x3F));
- else if ((a&0xF8) === 0xF0)
- ((b=src()) === null || (c=src()) === null || (d=src()) === null) && fail([a, b, c ,d]),
- dst(((a&0x07)<<18) | ((b&0x3F)<<12) | ((c&0x3F)<<6) | (d&0x3F));
- else throw RangeError("Illegal starting byte: "+a);
- }
- };
-
- /**
- * Converts UTF16 characters to UTF8 code points.
- * @param {!function():number|null} src Characters source as a function returning the next char code respectively
- * `null` if there are no more characters left.
- * @param {!function(number)} dst Code points destination as a function successively called with each converted code
- * point.
- */
- utfx.UTF16toUTF8 = function(src, dst) {
- var c1, c2 = null;
- while (true) {
- if ((c1 = c2 !== null ? c2 : src()) === null)
- break;
- if (c1 >= 0xD800 && c1 <= 0xDFFF) {
- if ((c2 = src()) !== null) {
- if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
- dst((c1-0xD800)*0x400+c2-0xDC00+0x10000);
- c2 = null; continue;
- }
- }
- }
- dst(c1);
- }
- if (c2 !== null) dst(c2);
- };
-
- /**
- * Converts UTF8 code points to UTF16 characters.
- * @param {(!function():number|null) | number} src Code points source, either as a function returning the next code point
- * respectively `null` if there are no more code points left or a single numeric code point.
- * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
- * @throws {RangeError} If a code point is out of range
- */
- utfx.UTF8toUTF16 = function(src, dst) {
- var cp = null;
- if (typeof src === 'number')
- cp = src, src = function() { return null; };
- while (cp !== null || (cp = src()) !== null) {
- if (cp <= 0xFFFF)
- dst(cp);
- else
- cp -= 0x10000,
- dst((cp>>10)+0xD800),
- dst((cp%0x400)+0xDC00);
- cp = null;
- }
- };
-
- /**
- * Converts and encodes UTF16 characters to UTF8 bytes.
- * @param {!function():number|null} src Characters source as a function returning the next char code respectively `null`
- * if there are no more characters left.
- * @param {!function(number)} dst Bytes destination as a function successively called with the next byte.
- */
- utfx.encodeUTF16toUTF8 = function(src, dst) {
- utfx.UTF16toUTF8(src, function(cp) {
- utfx.encodeUTF8(cp, dst);
- });
- };
-
- /**
- * Decodes and converts UTF8 bytes to UTF16 characters.
- * @param {!function():number|null} src Bytes source as a function returning the next byte respectively `null` if there
- * are no more bytes left.
- * @param {!function(number)} dst Characters destination as a function successively called with each converted char code.
- * @throws {RangeError} If a starting byte is invalid in UTF8
- * @throws {Error} If the last sequence is truncated. Has an array property `bytes` holding the remaining bytes.
- */
- utfx.decodeUTF8toUTF16 = function(src, dst) {
- utfx.decodeUTF8(src, function(cp) {
- utfx.UTF8toUTF16(cp, dst);
- });
- };
-
- /**
- * Calculates the byte length of an UTF8 code point.
- * @param {number} cp UTF8 code point
- * @returns {number} Byte length
- */
- utfx.calculateCodePoint = function(cp) {
- return (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
- };
-
- /**
- * Calculates the number of UTF8 bytes required to store UTF8 code points.
- * @param {(!function():number|null)} src Code points source as a function returning the next code point respectively
- * `null` if there are no more code points left.
- * @returns {number} The number of UTF8 bytes required
- */
- utfx.calculateUTF8 = function(src) {
- var cp, l=0;
- while ((cp = src()) !== null)
- l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
- return l;
- };
-
- /**
- * Calculates the number of UTF8 code points respectively UTF8 bytes required to store UTF16 char codes.
- * @param {(!function():number|null)} src Characters source as a function returning the next char code respectively
- * `null` if there are no more characters left.
- * @returns {!Array.} The number of UTF8 code points at index 0 and the number of UTF8 bytes required at index 1.
- */
- utfx.calculateUTF16asUTF8 = function(src) {
- var n=0, l=0;
- utfx.UTF16toUTF8(src, function(cp) {
- ++n; l += (cp < 0x80) ? 1 : (cp < 0x800) ? 2 : (cp < 0x10000) ? 3 : 4;
- });
- return [n,l];
- };
-
- return utfx;
- }();
-
- // encodings/utf8
-
- /**
- * Encodes this ByteBuffer's contents between {@link ByteBuffer#offset} and {@link ByteBuffer#limit} to an UTF8 encoded
- * string.
- * @returns {string} Hex encoded string
- * @throws {RangeError} If `offset > limit`
- * @expose
- */
- ByteBufferPrototype.toUTF8 = function(begin, end) {
- if (typeof begin === 'undefined') begin = this.offset;
- if (typeof end === 'undefined') end = this.limit;
- if (!this.noAssert) {
- if (typeof begin !== 'number' || begin % 1 !== 0)
- throw TypeError("Illegal begin: Not an integer");
- begin >>>= 0;
- if (typeof end !== 'number' || end % 1 !== 0)
- throw TypeError("Illegal end: Not an integer");
- end >>>= 0;
- if (begin < 0 || begin > end || end > this.buffer.byteLength)
- throw RangeError("Illegal range: 0 <= "+begin+" <= "+end+" <= "+this.buffer.byteLength);
- }
- var sd; try {
- utfx.decodeUTF8toUTF16(function() {
- return begin < end ? this.view[begin++] : null;
- }.bind(this), sd = stringDestination());
- } catch (e) {
- if (begin !== end)
- throw RangeError("Illegal range: Truncated data, "+begin+" != "+end);
- }
- return sd();
- };
-
- /**
- * Decodes an UTF8 encoded string to a ByteBuffer.
- * @param {string} str String to decode
- * @param {boolean=} littleEndian Whether to use little or big endian byte order. Defaults to
- * {@link ByteBuffer.DEFAULT_ENDIAN}.
- * @param {boolean=} noAssert Whether to skip assertions of offsets and values. Defaults to
- * {@link ByteBuffer.DEFAULT_NOASSERT}.
- * @returns {!ByteBuffer} ByteBuffer
- * @expose
- */
- ByteBuffer.fromUTF8 = function(str, littleEndian, noAssert) {
- if (!noAssert)
- if (typeof str !== 'string')
- throw TypeError("Illegal str: Not a string");
- var bb = new ByteBuffer(utfx.calculateUTF16asUTF8(stringSource(str), true)[1], littleEndian, noAssert),
- i = 0;
- utfx.encodeUTF16toUTF8(stringSource(str), function(b) {
- bb.view[i++] = b;
- });
- bb.limit = i;
- return bb;
- };
-
- return ByteBuffer;
-});
-
-
-/***/ }),
-/* 34 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var Buffer = __webpack_require__(0).Buffer
-
-// prototype class for hash functions
-function Hash (blockSize, finalSize) {
- this._block = Buffer.alloc(blockSize)
- this._finalSize = finalSize
- this._blockSize = blockSize
- this._len = 0
-}
-
-Hash.prototype.update = function (data, enc) {
- if (typeof data === 'string') {
- enc = enc || 'utf8'
- data = Buffer.from(data, enc)
- }
-
- var block = this._block
- var blockSize = this._blockSize
- var length = data.length
- var accum = this._len
-
- for (var offset = 0; offset < length;) {
- var assigned = accum % blockSize
- var remainder = Math.min(length - offset, blockSize - assigned)
-
- for (var i = 0; i < remainder; i++) {
- block[assigned + i] = data[offset + i]
- }
-
- accum += remainder
- offset += remainder
-
- if ((accum % blockSize) === 0) {
- this._update(block)
- }
- }
-
- this._len += length
- return this
-}
-
-Hash.prototype.digest = function (enc) {
- var rem = this._len % this._blockSize
-
- this._block[rem] = 0x80
-
- // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
- // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
- this._block.fill(0, rem + 1)
-
- if (rem >= this._finalSize) {
- this._update(this._block)
- this._block.fill(0)
- }
-
- var bits = this._len * 8
-
- // uint32
- if (bits <= 0xffffffff) {
- this._block.writeUInt32BE(bits, this._blockSize - 4)
-
- // uint64
- } else {
- var lowBits = (bits & 0xffffffff) >>> 0
- var highBits = (bits - lowBits) / 0x100000000
-
- this._block.writeUInt32BE(highBits, this._blockSize - 8)
- this._block.writeUInt32BE(lowBits, this._blockSize - 4)
- }
-
- this._update(this._block)
- var hash = this._hash()
-
- return enc ? hash.toString(enc) : hash
-}
-
-Hash.prototype._update = function () {
- throw new Error('_update must be implemented by subclass')
-}
-
-module.exports = Hash
-
-
-/***/ }),
-/* 35 */
-/***/ (function(module, exports, __webpack_require__) {
-
-module.exports = { "default": __webpack_require__(186), __esModule: true };
-
-/***/ }),
-/* 36 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// 19.1.2.14 / 15.2.3.14 Object.keys(O)
-var $keys = __webpack_require__(107);
-var enumBugKeys = __webpack_require__(76);
-
-module.exports = Object.keys || function keys(O) {
- return $keys(O, enumBugKeys);
-};
-
-
-/***/ }),
-/* 37 */
-/***/ (function(module, exports) {
-
-var toString = {}.toString;
-
-module.exports = function (it) {
- return toString.call(it).slice(8, -1);
-};
-
-
-/***/ }),
-/* 38 */
-/***/ (function(module, exports) {
-
-module.exports = true;
-
-
-/***/ }),
-/* 39 */
-/***/ (function(module, exports, __webpack_require__) {
-
-module.exports = { "default": __webpack_require__(191), __esModule: true };
-
-/***/ }),
-/* 40 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-exports.__esModule = true;
-
-var _promise = __webpack_require__(39);
-
-var _promise2 = _interopRequireDefault(_promise);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-exports.default = function (fn) {
- return function () {
- var gen = fn.apply(this, arguments);
- return new _promise2.default(function (resolve, reject) {
- function step(key, arg) {
- try {
- var info = gen[key](arg);
- var value = info.value;
- } catch (error) {
- reject(error);
- return;
- }
-
- if (info.done) {
- resolve(value);
- } else {
- return _promise2.default.resolve(value).then(function (value) {
- step("next", value);
- }, function (err) {
- step("throw", err);
- });
- }
- }
-
- return step("next");
- });
- };
-};
-
-/***/ }),
-/* 41 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-exports.__esModule = true;
-
-var _iterator = __webpack_require__(241);
-
-var _iterator2 = _interopRequireDefault(_iterator);
-
-var _symbol = __webpack_require__(243);
-
-var _symbol2 = _interopRequireDefault(_symbol);
-
-var _typeof = typeof _symbol2.default === "function" && typeof _iterator2.default === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj; };
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-exports.default = typeof _symbol2.default === "function" && _typeof(_iterator2.default) === "symbol" ? function (obj) {
- return typeof obj === "undefined" ? "undefined" : _typeof(obj);
-} : function (obj) {
- return obj && typeof _symbol2.default === "function" && obj.constructor === _symbol2.default && obj !== _symbol2.default.prototype ? "symbol" : typeof obj === "undefined" ? "undefined" : _typeof(obj);
-};
-
-/***/ }),
-/* 42 */
-/***/ (function(module, exports, __webpack_require__) {
-
-/* WEBPACK VAR INJECTION */(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
-}
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
-
-/***/ }),
-/* 43 */
-/***/ (function(module, exports, __webpack_require__) {
-
-/* WEBPACK VAR INJECTION */(function(Buffer) {// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// NOTE: These type checking functions intentionally don't use `instanceof`
-// because it is fragile and can be easily faked with `Object.create()`.
-
-function isArray(arg) {
- if (Array.isArray) {
- return Array.isArray(arg);
- }
- return objectToString(arg) === '[object Array]';
-}
-exports.isArray = isArray;
-
-function isBoolean(arg) {
- return typeof arg === 'boolean';
-}
-exports.isBoolean = isBoolean;
-
-function isNull(arg) {
- return arg === null;
-}
-exports.isNull = isNull;
-
-function isNullOrUndefined(arg) {
- return arg == null;
-}
-exports.isNullOrUndefined = isNullOrUndefined;
-
-function isNumber(arg) {
- return typeof arg === 'number';
-}
-exports.isNumber = isNumber;
-
-function isString(arg) {
- return typeof arg === 'string';
-}
-exports.isString = isString;
-
-function isSymbol(arg) {
- return typeof arg === 'symbol';
-}
-exports.isSymbol = isSymbol;
-
-function isUndefined(arg) {
- return arg === void 0;
-}
-exports.isUndefined = isUndefined;
-
-function isRegExp(re) {
- return objectToString(re) === '[object RegExp]';
-}
-exports.isRegExp = isRegExp;
-
-function isObject(arg) {
- return typeof arg === 'object' && arg !== null;
-}
-exports.isObject = isObject;
-
-function isDate(d) {
- return objectToString(d) === '[object Date]';
-}
-exports.isDate = isDate;
-
-function isError(e) {
- return (objectToString(e) === '[object Error]' || e instanceof Error);
-}
-exports.isError = isError;
-
-function isFunction(arg) {
- return typeof arg === 'function';
-}
-exports.isFunction = isFunction;
-
-function isPrimitive(arg) {
- return arg === null ||
- typeof arg === 'boolean' ||
- typeof arg === 'number' ||
- typeof arg === 'string' ||
- typeof arg === 'symbol' || // ES6 symbol
- typeof arg === 'undefined';
-}
-exports.isPrimitive = isPrimitive;
-
-exports.isBuffer = Buffer.isBuffer;
-
-function objectToString(o) {
- return Object.prototype.toString.call(o);
-}
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
-
-/***/ }),
-/* 44 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(Buffer) {
-
-var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
-
-var _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 assert = __webpack_require__(4);
-var ecurve = __webpack_require__(93);
-var BigInteger = __webpack_require__(16);
-var secp256k1 = ecurve.getCurveByName('secp256k1');
-
-var hash = __webpack_require__(25);
-var keyUtils = __webpack_require__(46);
-
-var G = secp256k1.G;
-var n = secp256k1.n;
-
-module.exports = PublicKey;
-
-/** @param {ecurve.Point} public key */
-function PublicKey(Q) {
- if (typeof Q === 'string') {
- var publicKey = PublicKey.fromString(Q);
- assert(publicKey != null, 'Invalid public key');
- return publicKey;
- } else if (Buffer.isBuffer(Q)) {
- return PublicKey.fromBuffer(Q);
- } else if ((typeof Q === 'undefined' ? 'undefined' : _typeof(Q)) === 'object' && Q.Q) {
- return PublicKey(Q.Q);
- }
-
- assert.equal(typeof Q === 'undefined' ? 'undefined' : _typeof(Q), 'object', 'Invalid public key');
- assert.equal(_typeof(Q.compressed), 'boolean', 'Invalid public key');
-
- function toBuffer() {
- var compressed = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : Q.compressed;
-
- return Q.getEncoded(compressed);
- }
-
- var pubdata = void 0; // cache
-
- // /**
- // @todo secp224r1
- // @return {string} PUB_K1_base58pubkey..
- // */
- // function toString() {
- // if(pubdata) {
- // return pubdata
- // }
- // pubdata = `PUB_K1_` + keyUtils.checkEncode(toBuffer(), 'K1')
- // return pubdata;
- // }
-
- /** @todo rename to toStringLegacy
- * @arg {string} [pubkey_prefix = 'EOS'] - public key prefix
- */
- function toString() {
- var pubkey_prefix = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'EOS';
-
- return pubkey_prefix + keyUtils.checkEncode(toBuffer());
- }
-
- function toUncompressed() {
- var buf = Q.getEncoded(false);
- var point = ecurve.Point.decodeFrom(secp256k1, buf);
- return PublicKey.fromPoint(point);
- }
-
- /** @deprecated */
- function child(offset) {
- console.error('Deprecated warning: PublicKey.child');
-
- assert(Buffer.isBuffer(offset), "Buffer required: offset");
- assert.equal(offset.length, 32, "offset length");
-
- offset = Buffer.concat([toBuffer(), offset]);
- offset = hash.sha256(offset);
-
- var c = BigInteger.fromBuffer(offset);
-
- if (c.compareTo(n) >= 0) throw new Error("Child offset went out of bounds, try again");
-
- var cG = G.multiply(c);
- var Qprime = Q.add(cG);
-
- if (secp256k1.isInfinity(Qprime)) throw new Error("Child offset derived to an invalid key, try again");
-
- return PublicKey.fromPoint(Qprime);
- }
-
- function toHex() {
- return toBuffer().toString('hex');
- }
-
- return {
- Q: Q,
- toString: toString,
- // toStringLegacy,
- toUncompressed: toUncompressed,
- toBuffer: toBuffer,
- child: child,
- toHex: toHex
- };
-}
-
-PublicKey.isValid = function (text) {
- try {
- PublicKey(text);
- return true;
- } catch (e) {
- return false;
- }
-};
-
-PublicKey.fromBinary = function (bin) {
- return PublicKey.fromBuffer(new Buffer(bin, 'binary'));
-};
-
-PublicKey.fromBuffer = function (buffer) {
- return PublicKey(ecurve.Point.decodeFrom(secp256k1, buffer));
-};
-
-PublicKey.fromPoint = function (point) {
- return PublicKey(point);
-};
-
-/**
- @arg {string} public_key - like PUB_K1_base58pubkey..
- @arg {string} [pubkey_prefix = 'EOS'] - public key prefix
- @return PublicKey or `null` (invalid)
-*/
-PublicKey.fromString = function (public_key) {
- var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
-
- try {
- return PublicKey.fromStringOrThrow(public_key, pubkey_prefix);
- } catch (e) {
- return null;
- }
-};
-
-/**
- @arg {string} public_key - like PUB_K1_base58pubkey..
- @arg {string} [pubkey_prefix = 'EOS'] - public key prefix
-
- @throws {Error} if public key is invalid
-
- @return PublicKey
-*/
-PublicKey.fromStringOrThrow = function (public_key) {
- var pubkey_prefix = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 'EOS';
-
- assert.equal(typeof public_key === 'undefined' ? 'undefined' : _typeof(public_key), 'string', 'public_key');
- var match = public_key.match(/^PUB_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/);
- if (match === null) {
- // legacy
- // TELOS addition: support for variable public_key prefixes
- var prefix_match = new RegExp("^" + pubkey_prefix);
- if (prefix_match.test(public_key)) {
- public_key = public_key.substring(pubkey_prefix.length);
- }
- return PublicKey.fromBuffer(keyUtils.checkDecode(public_key));
- }
- assert(match.length === 3, 'Expecting public key like: PUB_K1_base58pubkey..');
-
- var _match = _slicedToArray(match, 3),
- keyType = _match[1],
- keyString = _match[2];
-
- assert.equal(keyType, 'K1', 'K1 private key expected');
- return PublicKey.fromBuffer(keyUtils.checkDecode(keyString, keyType));
-};
-
-PublicKey.fromHex = function (hex) {
- return PublicKey.fromBuffer(new Buffer(hex, 'hex'));
-};
-
-PublicKey.fromStringHex = function (hex) {
- return PublicKey.fromString(new Buffer(hex, 'hex'));
-};
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
-
-/***/ }),
-/* 45 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var inherits = __webpack_require__(1)
-var MD5 = __webpack_require__(92)
-var RIPEMD160 = __webpack_require__(152)
-var sha = __webpack_require__(153)
-var Base = __webpack_require__(23)
-
-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 MD5()
- if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()
-
- return new Hash(sha(alg))
-}
-
-
-/***/ }),
-/* 46 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(Buffer) {
-
-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 base58 = __webpack_require__(288);
-var assert = __webpack_require__(4);
-var randomBytes = __webpack_require__(135);
-
-var hash = __webpack_require__(25);
-
-module.exports = {
- random32ByteBuffer: random32ByteBuffer,
- addEntropy: addEntropy,
- cpuEntropy: cpuEntropy,
- entropyCount: function entropyCount() {
- return _entropyCount;
- },
- checkDecode: checkDecode,
- checkEncode: checkEncode
-};
-
-var entropyPos = 0,
- _entropyCount = 0;
-
-var externalEntropyArray = randomBytes(101);
-
-/**
- Additional forms of entropy are used. A week random number generator can run out of entropy. This should ensure even the worst random number implementation will be reasonably safe.
-
- @arg {number} [cpuEntropyBits = 0] generate entropy on the fly. This is
- not required, entropy can be added in advanced via addEntropy or initialize().
-
- @arg {boolean} [safe = true] false for testing, otherwise this will be
- true to ensure initialize() was called.
-
- @return a random buffer obtained from the secure random number generator. Additional entropy is used.
-*/
-function random32ByteBuffer() {
- var _ref = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
- _ref$cpuEntropyBits = _ref.cpuEntropyBits,
- cpuEntropyBits = _ref$cpuEntropyBits === undefined ? 0 : _ref$cpuEntropyBits,
- _ref$safe = _ref.safe,
- safe = _ref$safe === undefined ? true : _ref$safe;
-
- assert.equal(typeof cpuEntropyBits === 'undefined' ? 'undefined' : _typeof(cpuEntropyBits), 'number', 'cpuEntropyBits');
- assert.equal(typeof safe === 'undefined' ? 'undefined' : _typeof(safe), 'boolean', 'boolean');
-
- if (safe) {
- assert(_entropyCount >= 128, 'Call initialize() to add entropy');
- }
-
- // if(entropyCount > 0) {
- // console.log(`Additional private key entropy: ${entropyCount} events`)
- // }
-
- var hash_array = [];
- hash_array.push(randomBytes(32));
- hash_array.push(Buffer.from(cpuEntropy(cpuEntropyBits)));
- hash_array.push(externalEntropyArray);
- hash_array.push(browserEntropy());
- return hash.sha256(Buffer.concat(hash_array));
-}
-
-/**
- Adds entropy. This may be called many times while the amount of data saved
- is accumulatively reduced to 101 integers. Data is retained in RAM for the
- life of this module.
-
- @example React
- componentDidMount() {
- this.refs.MyComponent.addEventListener("mousemove", this.onEntropyEvent, {capture: false, passive: true})
- }
- componentWillUnmount() {
- this.refs.MyComponent.removeEventListener("mousemove", this.onEntropyEvent);
- }
- onEntropyEvent = (e) => {
- if(e.type === 'mousemove')
- key_utils.addEntropy(e.pageX, e.pageY, e.screenX, e.screenY)
- else
- console.log('onEntropyEvent Unknown', e.type, e)
- }
-
-*/
-function addEntropy() {
- assert.equal(externalEntropyArray.length, 101, 'externalEntropyArray');
-
- for (var _len = arguments.length, ints = Array(_len), _key = 0; _key < _len; _key++) {
- ints[_key] = arguments[_key];
- }
-
- _entropyCount += ints.length;
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
-
- try {
- for (var _iterator = ints[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var i = _step.value;
-
- var pos = entropyPos++ % 101;
- var i2 = externalEntropyArray[pos] += i;
- if (i2 > 9007199254740991) externalEntropyArray[pos] = 0;
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
-}
-
-/**
- This runs in just under 1 second and ensures a minimum of cpuEntropyBits
- bits of entropy are gathered.
-
- Based on more-entropy. @see https://github.com/keybase/more-entropy/blob/master/src/generator.iced
-
- @arg {number} [cpuEntropyBits = 128]
- @return {array} counts gathered by measuring variations in the CPU speed during floating point operations.
-*/
-function cpuEntropy() {
- var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 128;
-
- var collected = [];
- var lastCount = null;
- var lowEntropySamples = 0;
- while (collected.length < cpuEntropyBits) {
- var count = floatingPointCount();
- if (lastCount != null) {
- var delta = count - lastCount;
- if (Math.abs(delta) < 1) {
- lowEntropySamples++;
- continue;
- }
- // how many bits of entropy were in this sample
- var bits = Math.floor(log2(Math.abs(delta)) + 1);
- if (bits < 4) {
- if (bits < 2) {
- lowEntropySamples++;
- }
- continue;
- }
- collected.push(delta);
- }
- lastCount = count;
- }
- if (lowEntropySamples > 10) {
- var pct = Number(lowEntropySamples / cpuEntropyBits * 100).toFixed(2);
- // Is this algorithm getting inefficient?
- console.warn('WARN: ' + pct + '% low CPU entropy re-sampled');
- }
- return collected;
-}
-
-/**
- @private
- Count while performing floating point operations during a fixed time
- (7 ms for example). Using a fixed time makes this algorithm
- predictable in runtime.
-*/
-function floatingPointCount() {
- var workMinMs = 7;
- var d = Date.now();
- var i = 0,
- x = 0;
- while (Date.now() < d + workMinMs + 1) {
- x = Math.sin(Math.sqrt(Math.log(++i + x)));
- }
- return i;
-}
-
-var log2 = function log2(x) {
- return Math.log(x) / Math.LN2;
-};
-
-/**
- @private
- Attempt to gather and hash information from the browser's window, history, and supported mime types. For non-browser environments this simply includes secure random data. In any event, the information is re-hashed in a loop for 25 milliseconds seconds.
-
- @return {Buffer} 32 bytes
-*/
-function browserEntropy() {
- var entropyStr = Array(randomBytes(101)).join();
- try {
- entropyStr += new Date().toString() + " " + window.screen.height + " " + window.screen.width + " " + window.screen.colorDepth + " " + " " + window.screen.availHeight + " " + window.screen.availWidth + " " + window.screen.pixelDepth + navigator.language + " " + window.location + " " + window.history.length;
-
- for (var i = 0, mimeType; i < navigator.mimeTypes.length; i++) {
- mimeType = navigator.mimeTypes[i];
- entropyStr += mimeType.description + " " + mimeType.type + " " + mimeType.suffixes + " ";
- }
- } catch (error) {
- //nodejs:ReferenceError: window is not defined
- entropyStr += hash.sha256(new Date().toString());
- }
-
- var b = new Buffer(entropyStr);
- entropyStr += b.toString('binary') + " " + new Date().toString();
-
- var entropy = entropyStr;
- var start_t = Date.now();
- while (Date.now() - start_t < 25) {
- entropy = hash.sha256(entropy);
- }return entropy;
-}
-
-/**
- @arg {Buffer} keyBuffer data
- @arg {string} keyType = sha256x2, K1, etc
- @return {string} checksum encoded base58 string
-*/
-function checkEncode(keyBuffer) {
- var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
-
- assert(Buffer.isBuffer(keyBuffer), 'expecting keyBuffer');
- if (keyType === 'sha256x2') {
- // legacy
- var checksum = hash.sha256(hash.sha256(keyBuffer)).slice(0, 4);
- return base58.encode(Buffer.concat([keyBuffer, checksum]));
- } else {
- var check = [keyBuffer];
- if (keyType) {
- check.push(Buffer.from(keyType));
- }
- var _checksum = hash.ripemd160(Buffer.concat(check)).slice(0, 4);
- return base58.encode(Buffer.concat([keyBuffer, _checksum]));
- }
-}
-
-/**
- @arg {Buffer} keyString data
- @arg {string} keyType = sha256x2, K1, etc
- @return {string} checksum encoded base58 string
-*/
-function checkDecode(keyString) {
- var keyType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
-
- assert(keyString != null, 'private key expected');
- var buffer = new Buffer(base58.decode(keyString));
- var checksum = buffer.slice(-4);
- var key = buffer.slice(0, -4);
-
- var newCheck = void 0;
- if (keyType === 'sha256x2') {
- // legacy
- newCheck = hash.sha256(hash.sha256(key)).slice(0, 4); // WIF (legacy)
- } else {
- var check = [key];
- if (keyType) {
- check.push(Buffer.from(keyType));
- }
- newCheck = hash.ripemd160(Buffer.concat(check)).slice(0, 4); //PVT
- }
-
- if (checksum.toString() !== newCheck.toString()) {
- throw new Error('Invalid checksum, ' + (checksum.toString('hex') + ' != ' + newCheck.toString('hex')));
- }
-
- return key;
-}
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
-
-/***/ }),
-/* 47 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; };
-
-var createKeccakHash = __webpack_require__(333);
-var secp256k1 = __webpack_require__(339);
-var assert = __webpack_require__(4);
-var rlp = __webpack_require__(368);
-var BN = __webpack_require__(9);
-var createHash = __webpack_require__(45);
-var Buffer = __webpack_require__(0).Buffer;
-Object.assign(exports, __webpack_require__(170));
-
-/**
- * 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);
-
-/**
- * Keccak-256 hash of null (a ```String```)
- * @var {String} KECCAK256_NULL_S
- */
-exports.KECCAK256_NULL_S = 'c5d2460186f7233c927e7db2dcc703c0e500b653ca82273b7bfad8045d85a470';
-exports.SHA3_NULL_S = exports.KECCAK256_NULL_S;
-
-/**
- * Keccak-256 hash of null (a ```Buffer```)
- * @var {Buffer} KECCAK256_NULL
- */
-exports.KECCAK256_NULL = Buffer.from(exports.KECCAK256_NULL_S, 'hex');
-exports.SHA3_NULL = exports.KECCAK256_NULL;
-
-/**
- * Keccak-256 of an RLP of an empty array (a ```String```)
- * @var {String} KECCAK256_RLP_ARRAY_S
- */
-exports.KECCAK256_RLP_ARRAY_S = '1dcc4de8dec75d7aab85b567b6ccd41ad312451b948a7413f0a142fd40d49347';
-exports.SHA3_RLP_ARRAY_S = exports.KECCAK256_RLP_ARRAY_S;
-
-/**
- * Keccak-256 of an RLP of an empty array (a ```Buffer```)
- * @var {Buffer} KECCAK256_RLP_ARRAY
- */
-exports.KECCAK256_RLP_ARRAY = Buffer.from(exports.KECCAK256_RLP_ARRAY_S, 'hex');
-exports.SHA3_RLP_ARRAY = exports.KECCAK256_RLP_ARRAY;
-
-/**
- * Keccak-256 hash of the RLP of null (a ```String```)
- * @var {String} KECCAK256_RLP_S
- */
-exports.KECCAK256_RLP_S = '56e81f171bcc55a6ff8345e692c0f86e5b48e01b996cadc001622fb5e363b421';
-exports.SHA3_RLP_S = exports.KECCAK256_RLP_S;
-
-/**
- * Keccak-256 hash of the RLP of null (a ```Buffer```)
- * @var {Buffer} KECCAK256_RLP
- */
-exports.KECCAK256_RLP = Buffer.from(exports.KECCAK256_RLP_S, 'hex');
-exports.SHA3_RLP = exports.KECCAK256_RLP;
-
-/**
- * [`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);
-};
-
-/**
- * Returns a zero address
- * @method zeroAddress
- * @return {String}
- */
-exports.zeroAddress = function () {
- var addressLength = 20;
- var zeroAddress = exports.zeros(addressLength);
- return exports.bufferToHex(zeroAddress);
-};
-
-/**
- * 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 (BN.isBN(v)) {
- v = v.toArrayLike(Buffer);
- } 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 Keccak hash of the input
- * @param {Buffer|Array|String|Number} a the input data
- * @param {Number} [bits=256] the Keccak width
- * @return {Buffer}
- */
-exports.keccak = function (a, bits) {
- a = exports.toBuffer(a);
- if (!bits) bits = 256;
-
- return createKeccakHash('keccak' + bits).update(a).digest();
-};
-
-/**
- * Creates Keccak-256 hash of the input, alias for keccak(a, 256)
- * @param {Buffer|Array|String|Number} a the input data
- * @return {Buffer}
- */
-exports.keccak256 = function (a) {
- return exports.keccak(a);
-};
-
-/**
- * Creates SHA-3 (Keccak) hash of the input [OBSOLETE]
- * @param {Buffer|Array|String|Number} a the input data
- * @param {Number} [bits=256] the SHA-3 width
- * @return {Buffer}
- */
-exports.sha3 = exports.keccak;
-
-/**
- * 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.keccak(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.keccak(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.keccak(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}$/.test(address)
- );
-};
-
-/**
- * Checks if a given address is a zero address
- * @method isZeroAddress
- * @param {String} address
- * @return {Boolean}
- */
-exports.isZeroAddress = function (address) {
- var zeroAddress = exports.zeroAddress();
- return zeroAddress === exports.addHexPrefix(address);
-};
-
-/**
- * Returns a checksummed address
- * @param {String} address
- * @return {String}
- */
-exports.toChecksumAddress = function (address) {
- address = exports.stripHexPrefix(address).toLowerCase();
- var hash = exports.keccak(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 (Byzantium)
- * @param {Buffer|String} address
- * @return {Boolean}
- */
-exports.isPrecompiled = function (address) {
- var a = exports.unpad(address);
- return a.length === 1 && a[0] >= 1 && a[0] <= 8;
-};
-
-/**
- * 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');
- }
- }
-};
-
-/***/ }),
-/* 48 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-var utils = __webpack_require__(13);
-var assert = __webpack_require__(26);
-
-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;
-};
-
-
-/***/ }),
-/* 49 */
-/***/ (function(module, exports) {
-
-/**
- * This method returns `undefined`.
- *
- * @static
- * @memberOf _
- * @since 2.3.0
- * @category Util
- * @example
- *
- * _.times(2, _.noop);
- * // => [undefined, undefined]
- */
-function noop() {
- // No operation performed.
-}
-
-module.exports = noop;
-
-
-/***/ }),
-/* 50 */
-/***/ (function(module, exports, __webpack_require__) {
-
-const getRandomId = __webpack_require__(412)
-const extend = __webpack_require__(67)
-
-module.exports = createPayload
-
-
-function createPayload(data){
- return extend({
- // defaults
- id: getRandomId(),
- jsonrpc: '2.0',
- params: [],
- // user-specified
- }, data)
-}
-
-
-/***/ }),
-/* 51 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// optional / simple context binding
-var aFunction = __webpack_require__(52);
-module.exports = function (fn, that, length) {
- aFunction(fn);
- if (that === undefined) return fn;
- switch (length) {
- case 1: return function (a) {
- return fn.call(that, a);
- };
- case 2: return function (a, b) {
- return fn.call(that, a, b);
- };
- case 3: return function (a, b, c) {
- return fn.call(that, a, b, c);
- };
- }
- return function (/* ...args */) {
- return fn.apply(that, arguments);
- };
-};
-
-
-/***/ }),
-/* 52 */
-/***/ (function(module, exports) {
-
-module.exports = function (it) {
- if (typeof it != 'function') throw TypeError(it + ' is not a function!');
- return it;
-};
-
-
-/***/ }),
-/* 53 */
-/***/ (function(module, exports) {
-
-module.exports = function (bitmap, value) {
- return {
- enumerable: !(bitmap & 1),
- configurable: !(bitmap & 2),
- writable: !(bitmap & 4),
- value: value
- };
-};
-
-
-/***/ }),
-/* 54 */
-/***/ (function(module, exports) {
-
-var id = 0;
-var px = Math.random();
-module.exports = function (key) {
- return 'Symbol('.concat(key === undefined ? '' : key, ')_', (++id + px).toString(36));
-};
-
-
-/***/ }),
-/* 55 */
-/***/ (function(module, exports) {
-
-exports.f = {}.propertyIsEnumerable;
-
-
-/***/ }),
-/* 56 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-var $at = __webpack_require__(192)(true);
-
-// 21.1.3.27 String.prototype[@@iterator]()
-__webpack_require__(111)(String, 'String', function (iterated) {
- this._t = String(iterated); // target
- this._i = 0; // next index
-// 21.1.5.2.1 %StringIteratorPrototype%.next()
-}, function () {
- var O = this._t;
- var index = this._i;
- var point;
- if (index >= O.length) return { value: undefined, done: true };
- point = $at(O, index);
- this._i += point.length;
- return { value: point, done: false };
-});
-
-
-/***/ }),
-/* 57 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var def = __webpack_require__(19).f;
-var has = __webpack_require__(22);
-var TAG = __webpack_require__(7)('toStringTag');
-
-module.exports = function (it, tag, stat) {
- if (it && !has(it = stat ? it : it.prototype, TAG)) def(it, TAG, { configurable: true, value: tag });
-};
-
-
-/***/ }),
-/* 58 */
-/***/ (function(module, exports, __webpack_require__) {
-
-__webpack_require__(196);
-var global = __webpack_require__(6);
-var hide = __webpack_require__(18);
-var Iterators = __webpack_require__(30);
-var TO_STRING_TAG = __webpack_require__(7)('toStringTag');
-
-var DOMIterables = ('CSSRuleList,CSSStyleDeclaration,CSSValueList,ClientRectList,DOMRectList,DOMStringList,' +
- 'DOMTokenList,DataTransferItemList,FileList,HTMLAllCollection,HTMLCollection,HTMLFormElement,HTMLSelectElement,' +
- 'MediaList,MimeTypeArray,NamedNodeMap,NodeList,PaintRequestList,Plugin,PluginArray,SVGLengthList,SVGNumberList,' +
- 'SVGPathSegList,SVGPointList,SVGStringList,SVGTransformList,SourceBufferList,StyleSheetList,TextTrackCueList,' +
- 'TextTrackList,TouchList').split(',');
-
-for (var i = 0; i < DOMIterables.length; i++) {
- var NAME = DOMIterables[i];
- var Collection = global[NAME];
- var proto = Collection && Collection.prototype;
- if (proto && !proto[TO_STRING_TAG]) hide(proto, TO_STRING_TAG, NAME);
- Iterators[NAME] = Iterators.Array;
-}
-
-
-/***/ }),
-/* 59 */
-/***/ (function(module, exports) {
-
-module.exports = function(module) {
- if(!module.webpackPolyfill) {
- module.deprecate = function() {};
- module.paths = [];
- // module.parent = undefined by default
- if(!module.children) module.children = [];
- Object.defineProperty(module, "loaded", {
- enumerable: true,
- get: function() {
- return module.l;
- }
- });
- Object.defineProperty(module, "id", {
- enumerable: true,
- get: function() {
- return module.i;
- }
- });
- module.webpackPolyfill = 1;
- }
- return module;
-};
-
-
-/***/ }),
-/* 60 */
-/***/ (function(module, exports) {
-
-/**
- * Compiles a querystring
- * Returns string representation of the object
- *
- * @param {Object}
- * @api private
- */
-
-exports.encode = function (obj) {
- var str = '';
-
- for (var i in obj) {
- if (obj.hasOwnProperty(i)) {
- if (str.length) str += '&';
- str += encodeURIComponent(i) + '=' + encodeURIComponent(obj[i]);
- }
- }
-
- return str;
-};
-
-/**
- * Parses a simple querystring into an object
- *
- * @param {String} qs
- * @api private
- */
-
-exports.decode = function(qs){
- var qry = {};
- var pairs = qs.split('&');
- for (var i = 0, l = pairs.length; i < l; i++) {
- var pair = pairs[i].split('=');
- qry[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
- }
- return qry;
-};
-
-
-/***/ }),
-/* 61 */
-/***/ (function(module, exports) {
-
-
-module.exports = function(a, b){
- var fn = function(){};
- fn.prototype = b.prototype;
- a.prototype = new fn;
- a.prototype.constructor = a;
-};
-
-/***/ }),
-/* 62 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// 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 Buffer = __webpack_require__(0).Buffer
-
-function asUInt32Array (buf) {
- if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
-
- var len = (buf.length / 4) | 0
- var out = new Array(len)
-
- for (var i = 0; i < len; i++) {
- out[i] = buf.readUInt32BE(i * 4)
- }
-
- return out
-}
-
-function scrubVec (v) {
- for (var i = 0; i < v.length; v++) {
- v[i] = 0
- }
-}
-
-function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
- var SUB_MIX0 = SUB_MIX[0]
- var SUB_MIX1 = SUB_MIX[1]
- var SUB_MIX2 = SUB_MIX[2]
- var SUB_MIX3 = SUB_MIX[3]
-
- var s0 = M[0] ^ keySchedule[0]
- var s1 = M[1] ^ keySchedule[1]
- var s2 = M[2] ^ keySchedule[2]
- var s3 = M[3] ^ keySchedule[3]
- var t0, t1, t2, t3
- var ksRow = 4
-
- for (var round = 1; round < nRounds; round++) {
- t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
- t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
- t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
- t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[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++]
- t0 = t0 >>> 0
- t1 = t1 >>> 0
- t2 = t2 >>> 0
- t3 = t3 >>> 0
-
- return [t0, t1, t2, t3]
-}
-
-// AES constants
-var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
-var G = (function () {
- // Compute double table
- var d = new Array(256)
- for (var j = 0; j < 256; j++) {
- if (j < 128) {
- d[j] = j << 1
- } else {
- d[j] = (j << 1) ^ 0x11b
- }
- }
-
- var SBOX = []
- var INV_SBOX = []
- var SUB_MIX = [[], [], [], []]
- var INV_SUB_MIX = [[], [], [], []]
-
- // Walk GF(2^8)
- var x = 0
- var xi = 0
- for (var i = 0; i < 256; ++i) {
- // Compute sbox
- var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
- sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
- SBOX[x] = sx
- INV_SBOX[sx] = x
-
- // Compute multiplication
- var x2 = d[x]
- var x4 = d[x2]
- var x8 = d[x4]
-
- // Compute sub bytes, mix columns tables
- var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
- SUB_MIX[0][x] = (t << 24) | (t >>> 8)
- SUB_MIX[1][x] = (t << 16) | (t >>> 16)
- SUB_MIX[2][x] = (t << 8) | (t >>> 24)
- SUB_MIX[3][x] = t
-
- // Compute inv sub bytes, inv mix columns tables
- t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
- INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
- INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
- INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
- 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 {
- SBOX: SBOX,
- INV_SBOX: INV_SBOX,
- SUB_MIX: SUB_MIX,
- INV_SUB_MIX: INV_SUB_MIX
- }
-})()
-
-function AES (key) {
- this._key = asUInt32Array(key)
- this._reset()
-}
-
-AES.blockSize = 4 * 4
-AES.keySize = 256 / 8
-AES.prototype.blockSize = AES.blockSize
-AES.prototype.keySize = AES.keySize
-AES.prototype._reset = function () {
- var keyWords = this._key
- var keySize = keyWords.length
- var nRounds = keySize + 6
- var ksRows = (nRounds + 1) * 4
-
- var keySchedule = []
- for (var k = 0; k < keySize; k++) {
- keySchedule[k] = keyWords[k]
- }
-
- for (k = keySize; k < ksRows; k++) {
- var t = keySchedule[k - 1]
-
- if (k % 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 ^= RCON[(k / keySize) | 0] << 24
- } else if (keySize > 6 && k % keySize === 4) {
- t =
- (G.SBOX[t >>> 24] << 24) |
- (G.SBOX[(t >>> 16) & 0xff] << 16) |
- (G.SBOX[(t >>> 8) & 0xff] << 8) |
- (G.SBOX[t & 0xff])
- }
-
- keySchedule[k] = keySchedule[k - keySize] ^ t
- }
-
- var invKeySchedule = []
- for (var ik = 0; ik < ksRows; ik++) {
- var ksR = ksRows - ik
- var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
-
- if (ik < 4 || ksR <= 4) {
- invKeySchedule[ik] = tt
- } else {
- invKeySchedule[ik] =
- G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
- G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
- G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
- G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
- }
- }
-
- this._nRounds = nRounds
- this._keySchedule = keySchedule
- this._invKeySchedule = invKeySchedule
-}
-
-AES.prototype.encryptBlockRaw = function (M) {
- M = asUInt32Array(M)
- return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
-}
-
-AES.prototype.encryptBlock = function (M) {
- var out = this.encryptBlockRaw(M)
- var buf = Buffer.allocUnsafe(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 = asUInt32Array(M)
-
- // swap
- var m1 = M[1]
- M[1] = M[3]
- M[3] = m1
-
- var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
- var buf = Buffer.allocUnsafe(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 () {
- scrubVec(this._keySchedule)
- scrubVec(this._invKeySchedule)
- scrubVec(this._key)
-}
-
-module.exports.AES = AES
-
-
-/***/ }),
-/* 63 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-module.exports = Stream;
-
-var EE = __webpack_require__(12).EventEmitter;
-var inherits = __webpack_require__(1);
-
-inherits(Stream, EE);
-Stream.Readable = __webpack_require__(89);
-Stream.Writable = __webpack_require__(270);
-Stream.Duplex = __webpack_require__(271);
-Stream.Transform = __webpack_require__(272);
-Stream.PassThrough = __webpack_require__(273);
-
-// Backwards-compat with node 0.4.x
-Stream.Stream = Stream;
-
-
-
-// old-style streams. Note that the pipe method (the only relevant
-// part of this class) is overridden in the Readable class.
-
-function Stream() {
- EE.call(this);
-}
-
-Stream.prototype.pipe = function(dest, options) {
- var source = this;
-
- function ondata(chunk) {
- if (dest.writable) {
- if (false === dest.write(chunk) && source.pause) {
- source.pause();
- }
- }
- }
-
- source.on('data', ondata);
-
- function ondrain() {
- if (source.readable && source.resume) {
- source.resume();
- }
- }
-
- dest.on('drain', ondrain);
-
- // If the 'end' option is not supplied, dest.end() will be called when
- // source gets the 'end' or 'close' events. Only dest.end() once.
- if (!dest._isStdio && (!options || options.end !== false)) {
- source.on('end', onend);
- source.on('close', onclose);
- }
-
- var didOnEnd = false;
- function onend() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- dest.end();
- }
-
-
- function onclose() {
- if (didOnEnd) return;
- didOnEnd = true;
-
- if (typeof dest.destroy === 'function') dest.destroy();
- }
-
- // don't leave dangling pipes when there are errors.
- function onerror(er) {
- cleanup();
- if (EE.listenerCount(this, 'error') === 0) {
- throw er; // Unhandled stream error in pipe.
- }
- }
-
- source.on('error', onerror);
- dest.on('error', onerror);
-
- // remove all the event listeners that were added.
- function cleanup() {
- source.removeListener('data', ondata);
- dest.removeListener('drain', ondrain);
-
- source.removeListener('end', onend);
- source.removeListener('close', onclose);
-
- source.removeListener('error', onerror);
- dest.removeListener('error', onerror);
-
- source.removeListener('end', cleanup);
- source.removeListener('close', cleanup);
-
- dest.removeListener('close', cleanup);
- }
-
- source.on('end', cleanup);
- source.on('close', cleanup);
-
- dest.on('close', cleanup);
-
- dest.emit('pipe', source);
-
- // Allow for unix-like usage: A.pipe(B).pipe(C)
- return dest;
-};
-
-
-/***/ }),
-/* 64 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(process) {
-
-if (!process.version ||
- process.version.indexOf('v0.') === 0 ||
- process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
- module.exports = { nextTick: nextTick };
-} else {
- module.exports = process
-}
-
-function nextTick(fn, arg1, arg2, arg3) {
- if (typeof fn !== 'function') {
- throw new TypeError('"callback" argument must be a function');
- }
- var len = arguments.length;
- var args, i;
- switch (len) {
- case 0:
- case 1:
- return process.nextTick(fn);
- case 2:
- return process.nextTick(function afterTickOne() {
- fn.call(null, arg1);
- });
- case 3:
- return process.nextTick(function afterTickTwo() {
- fn.call(null, arg1, arg2);
- });
- case 4:
- return process.nextTick(function afterTickThree() {
- fn.call(null, arg1, arg2, arg3);
- });
- default:
- args = new Array(len - 1);
- i = 0;
- while (i < args.length) {
- args[i++] = arguments[i];
- }
- return process.nextTick(function afterTick() {
- fn.apply(null, args);
- });
- }
-}
-
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11)))
-
-/***/ }),
-/* 65 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(Buffer) {
-
-var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }();
-
-var _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; };
-
-function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }
-
-var ecurve = __webpack_require__(93);
-var Point = ecurve.Point;
-var secp256k1 = ecurve.getCurveByName('secp256k1');
-var BigInteger = __webpack_require__(16);
-var assert = __webpack_require__(4);
-
-var hash = __webpack_require__(25);
-var PublicKey = __webpack_require__(44);
-var keyUtils = __webpack_require__(46);
-var createHash = __webpack_require__(45);
-var promiseAsync = __webpack_require__(290);
-
-var G = secp256k1.G;
-var n = secp256k1.n;
-
-module.exports = PrivateKey;
-
-/**
- @typedef {string} wif - https://en.bitcoin.it/wiki/Wallet_import_format
- @typedef {string} pubkey - EOSKey..
- @typedef {ecurve.Point} Point
-*/
-
-/**
- @param {BigInteger} d
-*/
-function PrivateKey(d) {
- if (typeof d === 'string') {
- return PrivateKey.fromString(d);
- } else if (Buffer.isBuffer(d)) {
- return PrivateKey.fromBuffer(d);
- } else if ((typeof d === 'undefined' ? 'undefined' : _typeof(d)) === 'object' && BigInteger.isBigInteger(d.d)) {
- return PrivateKey(d.d);
- }
-
- if (!BigInteger.isBigInteger(d)) {
- throw new TypeError('Invalid private key');
- }
-
- /** @return {string} private key like PVT_K1_base58privatekey.. */
- function toString() {
- // todo, use PVT_K1_
- // return 'PVT_K1_' + keyUtils.checkEncode(toBuffer(), 'K1')
- return toWif();
- }
-
- /**
- @return {wif}
- */
- function toWif() {
- var private_key = toBuffer();
- // checksum includes the version
- private_key = Buffer.concat([new Buffer([0x80]), private_key]);
- return keyUtils.checkEncode(private_key, 'sha256x2');
- }
-
- var public_key = void 0;
-
- /**
- @return {Point}
- */
- function toPublic() {
- if (public_key) {
- // cache
- // S L O W in the browser
- return public_key;
- }
- var Q = secp256k1.G.multiply(d);
- return public_key = PublicKey.fromPoint(Q);
- }
-
- function toBuffer() {
- return d.toBuffer(32);
- }
-
- /**
- ECIES
- @arg {string|Object} pubkey wif, PublicKey object
- @return {Buffer} 64 byte shared secret
- */
- function getSharedSecret(public_key) {
- public_key = PublicKey(public_key);
- var KB = public_key.toUncompressed().toBuffer();
- var KBP = Point.fromAffine(secp256k1, BigInteger.fromBuffer(KB.slice(1, 33)), // x
- BigInteger.fromBuffer(KB.slice(33, 65)) // y
- );
- var r = toBuffer();
- var P = KBP.multiply(BigInteger.fromBuffer(r));
- var S = P.affineX.toBuffer({ size: 32 });
- // SHA512 used in ECIES
- return hash.sha512(S);
- }
-
- // /** ECIES TODO unit test
- // @arg {string|Object} pubkey wif, PublicKey object
- // @return {Buffer} 64 byte shared secret
- // */
- // function getSharedSecret(public_key) {
- // public_key = PublicKey(public_key).toUncompressed()
- // var P = public_key.Q.multiply( d );
- // var S = P.affineX.toBuffer({size: 32});
- // // ECIES, adds an extra sha512
- // return hash.sha512(S);
- // }
-
- /**
- @arg {string} name - child key name.
- @return {PrivateKey}
- @example activePrivate = masterPrivate.getChildKey('owner').getChildKey('active')
- @example activePrivate.getChildKey('mycontract').getChildKey('myperm')
- */
- function getChildKey(name) {
- // console.error('WARNING: getChildKey untested against eosd'); // no eosd impl yet
- var index = createHash('sha256').update(toBuffer()).update(name).digest();
- return PrivateKey(index);
- }
-
- function toHex() {
- return toBuffer().toString('hex');
- }
-
- return {
- d: d,
- toWif: toWif,
- toString: toString,
- toPublic: toPublic,
- toBuffer: toBuffer,
- getSharedSecret: getSharedSecret,
- getChildKey: getChildKey
- };
-}
-
-/** @private */
-function parseKey(privateStr) {
- assert.equal(typeof privateStr === 'undefined' ? 'undefined' : _typeof(privateStr), 'string', 'privateStr');
- var match = privateStr.match(/^PVT_([A-Za-z0-9]+)_([A-Za-z0-9]+)$/);
-
- if (match === null) {
- // legacy WIF - checksum includes the version
- var versionKey = keyUtils.checkDecode(privateStr, 'sha256x2');
- var version = versionKey.readUInt8(0);
- assert.equal(0x80, version, 'Expected version ' + 0x80 + ', instead got ' + version);
- var _privateKey = PrivateKey.fromBuffer(versionKey.slice(1));
- var _keyType = 'K1';
- var format = 'WIF';
- return { privateKey: _privateKey, format: format, keyType: _keyType };
- }
-
- assert(match.length === 3, 'Expecting private key like: PVT_K1_base58privateKey..');
-
- var _match = _slicedToArray(match, 3),
- keyType = _match[1],
- keyString = _match[2];
-
- assert.equal(keyType, 'K1', 'K1 private key expected');
- var privateKey = PrivateKey.fromBuffer(keyUtils.checkDecode(keyString, keyType));
- return { privateKey: privateKey, format: 'PVT', keyType: keyType };
-}
-
-PrivateKey.fromHex = function (hex) {
- return PrivateKey.fromBuffer(new Buffer(hex, 'hex'));
-};
-
-PrivateKey.fromBuffer = function (buf) {
- if (!Buffer.isBuffer(buf)) {
- throw new Error("Expecting parameter to be a Buffer type");
- }
- if (buf.length === 33 && buf[32] === 1) {
- // remove compression flag
- buf = buf.slice(0, -1);
- }
- if (32 !== buf.length) {
- throw new Error('Expecting 32 bytes, instead got ' + buf.length);
- }
- return PrivateKey(BigInteger.fromBuffer(buf));
-};
-
-/**
- @arg {string} seed - any length string. This is private, the same seed
- produces the same private key every time.
-
- @return {PrivateKey}
-*/
-PrivateKey.fromSeed = function (seed) {
- // generate_private_key
- if (!(typeof seed === 'string')) {
- throw new Error('seed must be of type string');
- }
- return PrivateKey.fromBuffer(hash.sha256(seed));
-};
-
-/**
- @arg {wif} key
- @return {boolean} true if key is in the Wallet Import Format
-*/
-PrivateKey.isWif = function (text) {
- try {
- assert(parseKey(text).format === 'WIF');
- return true;
- } catch (e) {
- return false;
- }
-};
-
-/**
- @arg {wif|Buffer|PrivateKey} key
- @return {boolean} true if key is convertable to a private key object.
-*/
-PrivateKey.isValid = function (key) {
- try {
- PrivateKey(key);
- return true;
- } catch (e) {
- return false;
- }
-};
-
-/** @deprecated */
-PrivateKey.fromWif = function (str) {
- console.log('PrivateKey.fromWif is deprecated, please use PrivateKey.fromString');
- return PrivateKey.fromString(str);
-};
-
-/**
- @throws {AssertError|Error} parsing key
- @arg {string} privateStr Eosio or Wallet Import Format (wif) -- a secret
-*/
-PrivateKey.fromString = function (privateStr) {
- return parseKey(privateStr).privateKey;
-};
-
-/**
- Create a new random private key.
-
- Call initialize() first to run some self-checking code and gather some CPU
- entropy.
-
- @arg {number} [cpuEntropyBits = 0] - additional CPU entropy, this already
- happens once so it should not be needed again.
-
- @return {Promise} - random private key
-*/
-PrivateKey.randomKey = function () {
- var cpuEntropyBits = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 0;
-
- return PrivateKey.initialize().then(function () {
- return PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({ cpuEntropyBits: cpuEntropyBits }));
- });
-};
-
-/**
- @return {Promise} for testing, does not require initialize().
-*/
-PrivateKey.unsafeRandomKey = function () {
- return Promise.resolve(PrivateKey.fromBuffer(keyUtils.random32ByteBuffer({ safe: false })));
-};
-
-var initialized = false,
- unitTested = false;
-
-/**
- Run self-checking code and gather CPU entropy.
-
- Initialization happens once even if called multiple times.
-
- @return {Promise}
-*/
-function initialize() {
- if (initialized) {
- return;
- }
-
- unitTest();
- keyUtils.addEntropy.apply(keyUtils, _toConsumableArray(keyUtils.cpuEntropy()));
- assert(keyUtils.entropyCount() >= 128, 'insufficient entropy');
-
- initialized = true;
-}
-
-PrivateKey.initialize = promiseAsync(initialize);
-
-/**
- Unit test basic private and public key functionality.
-
- @throws {AssertError}
-*/
-function unitTest() {
- var pvt = PrivateKey(hash.sha256(''));
-
- var pvtError = 'key comparison test failed on a known private key';
- assert.equal(pvt.toWif(), '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss', pvtError);
- assert.equal(pvt.toString(), '5KYZdUEo39z3FPrtuX2QbbwGnNP5zTd7yyr2SC1j299sBCnWjss', pvtError);
- // assert.equal(pvt.toString(), 'PVT_K1_2jH3nnhxhR3zPUcsKaWWZC9ZmZAnKm3GAnFD1xynGJE1Znuvjd', pvtError)
-
- var pub = pvt.toPublic();
- var pubError = 'pubkey string comparison test failed on a known public key';
- assert.equal(pub.toString(), 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM', pubError);
- // assert.equal(pub.toString(), 'PUB_K1_859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2Ht7beeX', pubError)
- // assert.equal(pub.toStringLegacy(), 'EOS859gxfnXyUriMgUeThh1fWv3oqcpLFyHa3TfFYC4PK2HqhToVM', pubError)
-
- doesNotThrow(function () {
- return PrivateKey.fromString(pvt.toWif());
- }, 'converting known wif from string');
- doesNotThrow(function () {
- return PrivateKey.fromString(pvt.toString());
- }, 'converting known pvt from string');
- doesNotThrow(function () {
- return PublicKey.fromString(pub.toString());
- }, 'converting known public key from string');
- // doesNotThrow(() => PublicKey.fromString(pub.toStringLegacy()), 'converting known public key from string')
-
- unitTested = true;
-}
-
-/** @private */
-var doesNotThrow = function doesNotThrow(cb, msg) {
- try {
- cb();
- } catch (error) {
- error.message = msg + ' ==> ' + error.message;
- throw error;
- }
-};
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
-
-/***/ }),
-/* 66 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-var curve = exports;
-
-curve.base = __webpack_require__(349);
-curve.short = __webpack_require__(350);
-curve.mont = __webpack_require__(351);
-curve.edwards = __webpack_require__(352);
-
-
-/***/ }),
-/* 67 */
-/***/ (function(module, exports) {
-
-module.exports = extend
-
-var hasOwnProperty = Object.prototype.hasOwnProperty;
-
-function extend() {
- var target = {}
-
- for (var i = 0; i < arguments.length; i++) {
- var source = arguments[i]
-
- for (var key in source) {
- if (hasOwnProperty.call(source, key)) {
- target[key] = source[key]
- }
- }
- }
-
- return target
-}
-
-
-/***/ }),
-/* 68 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var isFunction = __webpack_require__(377),
- isLength = __webpack_require__(177);
-
-/**
- * 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);
-}
-
-module.exports = isArrayLike;
-
-
-/***/ }),
-/* 69 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"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"];
-
-/***/ }),
-/* 70 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var isObject = __webpack_require__(20);
-var document = __webpack_require__(6).document;
-// typeof document.createElement is 'object' in old IE
-var is = isObject(document) && isObject(document.createElement);
-module.exports = function (it) {
- return is ? document.createElement(it) : {};
-};
-
-
-/***/ }),
-/* 71 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// 7.1.1 ToPrimitive(input [, PreferredType])
-var isObject = __webpack_require__(20);
-// instead of the ES6 spec version, we didn't implement @@toPrimitive case
-// and the second argument - flag - preferred type is a string
-module.exports = function (it, S) {
- if (!isObject(it)) return it;
- var fn, val;
- if (S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
- if (typeof (fn = it.valueOf) == 'function' && !isObject(val = fn.call(it))) return val;
- if (!S && typeof (fn = it.toString) == 'function' && !isObject(val = fn.call(it))) return val;
- throw TypeError("Can't convert object to primitive value");
-};
-
-
-/***/ }),
-/* 72 */
-/***/ (function(module, exports) {
-
-// 7.2.1 RequireObjectCoercible(argument)
-module.exports = function (it) {
- if (it == undefined) throw TypeError("Can't call method on " + it);
- return it;
-};
-
-
-/***/ }),
-/* 73 */
-/***/ (function(module, exports) {
-
-// 7.1.4 ToInteger
-var ceil = Math.ceil;
-var floor = Math.floor;
-module.exports = function (it) {
- return isNaN(it = +it) ? 0 : (it > 0 ? floor : ceil)(it);
-};
-
-
-/***/ }),
-/* 74 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var shared = __webpack_require__(75)('keys');
-var uid = __webpack_require__(54);
-module.exports = function (key) {
- return shared[key] || (shared[key] = uid(key));
-};
-
-
-/***/ }),
-/* 75 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var core = __webpack_require__(5);
-var global = __webpack_require__(6);
-var SHARED = '__core-js_shared__';
-var store = global[SHARED] || (global[SHARED] = {});
-
-(module.exports = function (key, value) {
- return store[key] || (store[key] = value !== undefined ? value : {});
-})('versions', []).push({
- version: core.version,
- mode: __webpack_require__(38) ? 'pure' : 'global',
- copyright: '© 2018 Denis Pushkarev (zloirock.ru)'
-});
-
-
-/***/ }),
-/* 76 */
-/***/ (function(module, exports) {
-
-// IE 8- don't enum bug keys
-module.exports = (
- 'constructor,hasOwnProperty,isPrototypeOf,propertyIsEnumerable,toLocaleString,toString,valueOf'
-).split(',');
-
-
-/***/ }),
-/* 77 */
-/***/ (function(module, exports) {
-
-exports.f = Object.getOwnPropertySymbols;
-
-
-/***/ }),
-/* 78 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// 7.1.13 ToObject(argument)
-var defined = __webpack_require__(72);
-module.exports = function (it) {
- return Object(defined(it));
-};
-
-
-/***/ }),
-/* 79 */
-/***/ (function(module, exports, __webpack_require__) {
-
-// getting tag from 19.1.3.6 Object.prototype.toString()
-var cof = __webpack_require__(37);
-var TAG = __webpack_require__(7)('toStringTag');
-// ES3 wrong here
-var ARG = cof(function () { return arguments; }()) == 'Arguments';
-
-// fallback for IE11 Script Access Denied error
-var tryGet = function (it, key) {
- try {
- return it[key];
- } catch (e) { /* empty */ }
-};
-
-module.exports = function (it) {
- var O, T, B;
- return it === undefined ? 'Undefined' : it === null ? 'Null'
- // @@toStringTag case
- : typeof (T = tryGet(O = Object(it), TAG)) == 'string' ? T
- // builtinTag case
- : ARG ? cof(O)
- // ES3 arguments fallback
- : (B = cof(O)) == 'Object' && typeof O.callee == 'function' ? 'Arguments' : B;
-};
-
-
-/***/ }),
-/* 80 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-// 25.4.1.5 NewPromiseCapability(C)
-var aFunction = __webpack_require__(52);
-
-function PromiseCapability(C) {
- var resolve, reject;
- this.promise = new C(function ($$resolve, $$reject) {
- if (resolve !== undefined || reject !== undefined) throw TypeError('Bad Promise constructor');
- resolve = $$resolve;
- reject = $$reject;
- });
- this.resolve = aFunction(resolve);
- this.reject = aFunction(reject);
-}
-
-module.exports.f = function (C) {
- return new PromiseCapability(C);
-};
-
-
-/***/ }),
-/* 81 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-Object.defineProperty(exports, "__esModule", {
- value: true
-});
-
-var _assign = __webpack_require__(35);
-
-var _assign2 = _interopRequireDefault(_assign);
-
-var _promise = __webpack_require__(39);
-
-var _promise2 = _interopRequireDefault(_promise);
-
-var _asyncToGenerator2 = __webpack_require__(40);
-
-var _asyncToGenerator3 = _interopRequireDefault(_asyncToGenerator2);
-
-var _socket = __webpack_require__(212);
-
-var _socket2 = _interopRequireDefault(_socket);
-
-var _StorageService = __webpack_require__(235);
-
-var _StorageService2 = _interopRequireDefault(_StorageService);
-
-var _getRandomValues = __webpack_require__(236);
-
-var _getRandomValues2 = _interopRequireDefault(_getRandomValues);
-
-var _eosjs = __webpack_require__(238);
-
-var _eosjs2 = _interopRequireDefault(_eosjs);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-const { ecc } = _eosjs2.default.modules;
-
-const host = 'http://127.0.0.1:50005';
-
-let socket = null;
-let connected = false;
-let paired = false;
-
-let plugin;
-let openRequests = [];
-
-let allowReconnects = true;
-let reconnectionTimeout = null;
-
-const reconnectOnAbnormalDisconnection = (() => {
- var _ref = (0, _asyncToGenerator3.default)(function* () {
- if (!allowReconnects) return;
-
- clearTimeout(reconnectionTimeout);
- reconnectionTimeout = setTimeout(function () {
- SocketService.link();
- }, 1000);
- });
-
- return function reconnectOnAbnormalDisconnection() {
- return _ref.apply(this, arguments);
- };
-})();
-
-const random = () => {
- const array = new Uint8Array(24);
- (0, _getRandomValues2.default)(array);
- return array.join('');
-};
-
-const getOrigin = () => {
- let origin;
- if (typeof location !== 'undefined') {
- if (location.hasOwnProperty('hostname') && location.hostname.length && location.hostname !== 'localhost') origin = location.hostname;else origin = plugin;
- } else origin = plugin;
- return origin;
-};
-
-// StorageService.removeAppKey();
-// StorageService.removeNonce();
-
-let appkey = _StorageService2.default.getAppKey();
-if (!appkey) appkey = 'appkey:' + random();
-
-let pairingPromise = null;
-const pair = (passthrough = false) => {
- return new _promise2.default((resolve, reject) => {
- pairingPromise = { resolve, reject };
- socket.emit('pair', { data: { appkey, origin: getOrigin(), passthrough }, plugin });
- });
-};
-
-class SocketService {
-
- static init(_plugin, timeout = 60000) {
- plugin = _plugin;
- this.timeout = timeout;
- }
-
- static link() {
- var _this = this;
-
- return (0, _asyncToGenerator3.default)(function* () {
-
- return _promise2.default.race([new _promise2.default(function (resolve, reject) {
- return setTimeout((0, _asyncToGenerator3.default)(function* () {
- if (connected) return;
- resolve(false);
-
- if (socket) {
- socket.disconnect();
- socket = null;
- }
-
- reconnectOnAbnormalDisconnection();
- }), _this.timeout);
- }), new _promise2.default((() => {
- var _ref3 = (0, _asyncToGenerator3.default)(function* (resolve, reject) {
- socket = _socket2.default.connect(`${host}/scatter`, { secure: true, reconnection: false, rejectUnauthorized: false });
-
- socket.on('connected', (0, _asyncToGenerator3.default)(function* () {
- clearTimeout(reconnectionTimeout);
- connected = true;
- yield pair(true);
- resolve(true);
- }));
-
- socket.on('paired', (() => {
- var _ref5 = (0, _asyncToGenerator3.default)(function* (result) {
- paired = result;
-
- if (paired) {
- const savedKey = _StorageService2.default.getAppKey();
- const hashed = appkey.indexOf('appkey:') > -1 ? ecc.sha256(appkey) : appkey;
-
- if (!savedKey || savedKey !== hashed) {
- _StorageService2.default.setAppKey(hashed);
- appkey = _StorageService2.default.getAppKey();
- }
- }
-
- pairingPromise.resolve(result);
- });
-
- return function (_x3) {
- return _ref5.apply(this, arguments);
- };
- })());
-
- socket.on('rekey', (0, _asyncToGenerator3.default)(function* () {
- appkey = 'appkey:' + random();
- socket.emit('rekeyed', { data: { appkey, origin: getOrigin() }, plugin });
- }));
-
- socket.on('event', function (event) {
- console.log('event', event);
- });
-
- socket.on('api', function (result) {
- const openRequest = openRequests.find(function (x) {
- return x.id === result.id;
- });
- if (!openRequest) return;
- if (typeof result.result === 'object' && result.result !== null && result.result.hasOwnProperty('isError')) openRequest.reject(result.result);else openRequest.resolve(result.result);
- });
-
- socket.on('disconnect', (0, _asyncToGenerator3.default)(function* () {
- console.log('Disconnected');
- connected = false;
- socket = null;
-
- // If bad disconnect, retry connection
- reconnectOnAbnormalDisconnection();
- }));
-
- socket.on('connect_error', (0, _asyncToGenerator3.default)(function* () {
- allowReconnects = false;
- resolve(false);
- }));
-
- socket.on('rejected', (() => {
- var _ref9 = (0, _asyncToGenerator3.default)(function* (reason) {
- console.error('reason', reason);
- reject(reason);
- });
-
- return function (_x4) {
- return _ref9.apply(this, arguments);
- };
- })());
- });
-
- return function (_x, _x2) {
- return _ref3.apply(this, arguments);
- };
- })())]);
- })();
- }
-
- static isConnected() {
- return connected;
- }
-
- static disconnect() {
- return (0, _asyncToGenerator3.default)(function* () {
- socket.disconnect();
- return true;
- })();
- }
-
- static sendApiRequest(request) {
- return (0, _asyncToGenerator3.default)(function* () {
- return new _promise2.default((() => {
- var _ref10 = (0, _asyncToGenerator3.default)(function* (resolve, reject) {
- if (request.type === 'identityFromPermissions' && !paired) return resolve(false);
-
- yield pair();
- if (!paired) return reject({ code: 'not_paired', message: 'The user did not allow this app to connect to their Scatter' });
-
- // Request ID used for resolving promises
- request.id = random();
-
- // Set Application Key
- request.appkey = appkey;
-
- // Nonce used to authenticate this request
- request.nonce = _StorageService2.default.getNonce() || 0;
- // Next nonce used to authenticate the next request
- const nextNonce = random();
- request.nextNonce = ecc.sha256(nextNonce);
- _StorageService2.default.setNonce(nextNonce);
-
- if (request.hasOwnProperty('payload') && !request.payload.hasOwnProperty('origin')) request.payload.origin = getOrigin();
-
- openRequests.push((0, _assign2.default)(request, { resolve, reject }));
- socket.emit('api', { data: request, plugin });
- });
-
- return function (_x5, _x6) {
- return _ref10.apply(this, arguments);
- };
- })());
- })();
- }
-
-}
-exports.default = SocketService;
-
-/***/ }),
-/* 82 */
-/***/ (function(module, exports, __webpack_require__) {
-
-
-/**
- * Module dependencies.
- */
-
-var debug = __webpack_require__(15)('socket.io-parser');
-var Emitter = __webpack_require__(31);
-var binary = __webpack_require__(216);
-var isArray = __webpack_require__(83);
-var isBuf = __webpack_require__(121);
-
-/**
- * Protocol version.
- *
- * @api public
- */
-
-exports.protocol = 4;
-
-/**
- * Packet types.
- *
- * @api public
- */
-
-exports.types = [
- 'CONNECT',
- 'DISCONNECT',
- 'EVENT',
- 'ACK',
- 'ERROR',
- 'BINARY_EVENT',
- 'BINARY_ACK'
-];
-
-/**
- * Packet type `connect`.
- *
- * @api public
- */
-
-exports.CONNECT = 0;
-
-/**
- * Packet type `disconnect`.
- *
- * @api public
- */
-
-exports.DISCONNECT = 1;
-
-/**
- * Packet type `event`.
- *
- * @api public
- */
-
-exports.EVENT = 2;
-
-/**
- * Packet type `ack`.
- *
- * @api public
- */
-
-exports.ACK = 3;
-
-/**
- * Packet type `error`.
- *
- * @api public
- */
-
-exports.ERROR = 4;
-
-/**
- * Packet type 'binary event'
- *
- * @api public
- */
-
-exports.BINARY_EVENT = 5;
-
-/**
- * Packet type `binary ack`. For acks with binary arguments.
- *
- * @api public
- */
-
-exports.BINARY_ACK = 6;
-
-/**
- * Encoder constructor.
- *
- * @api public
- */
-
-exports.Encoder = Encoder;
-
-/**
- * Decoder constructor.
- *
- * @api public
- */
-
-exports.Decoder = Decoder;
-
-/**
- * A socket.io Encoder instance
- *
- * @api public
- */
-
-function Encoder() {}
-
-var ERROR_PACKET = exports.ERROR + '"encode error"';
-
-/**
- * Encode a packet as a single string if non-binary, or as a
- * buffer sequence, depending on packet type.
- *
- * @param {Object} obj - packet object
- * @param {Function} callback - function to handle encodings (likely engine.write)
- * @return Calls callback with Array of encodings
- * @api public
- */
-
-Encoder.prototype.encode = function(obj, callback){
- debug('encoding packet %j', obj);
-
- if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
- encodeAsBinary(obj, callback);
- } else {
- var encoding = encodeAsString(obj);
- callback([encoding]);
- }
-};
-
-/**
- * Encode packet as string.
- *
- * @param {Object} packet
- * @return {String} encoded
- * @api private
- */
-
-function encodeAsString(obj) {
-
- // first is type
- var str = '' + obj.type;
-
- // attachments if we have them
- if (exports.BINARY_EVENT === obj.type || exports.BINARY_ACK === obj.type) {
- str += obj.attachments + '-';
- }
-
- // if we have a namespace other than `/`
- // we append it followed by a comma `,`
- if (obj.nsp && '/' !== obj.nsp) {
- str += obj.nsp + ',';
- }
-
- // immediately followed by the id
- if (null != obj.id) {
- str += obj.id;
- }
-
- // json data
- if (null != obj.data) {
- var payload = tryStringify(obj.data);
- if (payload !== false) {
- str += payload;
- } else {
- return ERROR_PACKET;
- }
- }
-
- debug('encoded %j as %s', obj, str);
- return str;
-}
-
-function tryStringify(str) {
- try {
- return JSON.stringify(str);
- } catch(e){
- return false;
- }
-}
-
-/**
- * Encode packet as 'buffer sequence' by removing blobs, and
- * deconstructing packet into object with placeholders and
- * a list of buffers.
- *
- * @param {Object} packet
- * @return {Buffer} encoded
- * @api private
- */
-
-function encodeAsBinary(obj, callback) {
-
- function writeEncoding(bloblessData) {
- var deconstruction = binary.deconstructPacket(bloblessData);
- var pack = encodeAsString(deconstruction.packet);
- var buffers = deconstruction.buffers;
-
- buffers.unshift(pack); // add packet info to beginning of data list
- callback(buffers); // write all the buffers
- }
-
- binary.removeBlobs(obj, writeEncoding);
-}
-
-/**
- * A socket.io Decoder instance
- *
- * @return {Object} decoder
- * @api public
- */
-
-function Decoder() {
- this.reconstructor = null;
-}
-
-/**
- * Mix in `Emitter` with Decoder.
- */
-
-Emitter(Decoder.prototype);
-
-/**
- * Decodes an ecoded packet string into packet JSON.
- *
- * @param {String} obj - encoded packet
- * @return {Object} packet
- * @api public
- */
-
-Decoder.prototype.add = function(obj) {
- var packet;
- if (typeof obj === 'string') {
- packet = decodeString(obj);
- if (exports.BINARY_EVENT === packet.type || exports.BINARY_ACK === packet.type) { // binary packet's json
- this.reconstructor = new BinaryReconstructor(packet);
-
- // no attachments, labeled binary but no binary data to follow
- if (this.reconstructor.reconPack.attachments === 0) {
- this.emit('decoded', packet);
- }
- } else { // non-binary full packet
- this.emit('decoded', packet);
- }
- }
- else if (isBuf(obj) || obj.base64) { // raw binary data
- if (!this.reconstructor) {
- throw new Error('got binary data when not reconstructing a packet');
- } else {
- packet = this.reconstructor.takeBinaryData(obj);
- if (packet) { // received final buffer
- this.reconstructor = null;
- this.emit('decoded', packet);
- }
- }
- }
- else {
- throw new Error('Unknown type: ' + obj);
- }
-};
-
-/**
- * Decode a packet String (JSON data)
- *
- * @param {String} str
- * @return {Object} packet
- * @api private
- */
-
-function decodeString(str) {
- var i = 0;
- // look up type
- var p = {
- type: Number(str.charAt(0))
- };
-
- if (null == exports.types[p.type]) {
- return error('unknown packet type ' + p.type);
- }
-
- // look up attachments if type binary
- if (exports.BINARY_EVENT === p.type || exports.BINARY_ACK === p.type) {
- var buf = '';
- while (str.charAt(++i) !== '-') {
- buf += str.charAt(i);
- if (i == str.length) break;
- }
- if (buf != Number(buf) || str.charAt(i) !== '-') {
- throw new Error('Illegal attachments');
- }
- p.attachments = Number(buf);
- }
-
- // look up namespace (if any)
- if ('/' === str.charAt(i + 1)) {
- p.nsp = '';
- while (++i) {
- var c = str.charAt(i);
- if (',' === c) break;
- p.nsp += c;
- if (i === str.length) break;
- }
- } else {
- p.nsp = '/';
- }
-
- // look up id
- var next = str.charAt(i + 1);
- if ('' !== next && Number(next) == next) {
- p.id = '';
- while (++i) {
- var c = str.charAt(i);
- if (null == c || Number(c) != c) {
- --i;
- break;
- }
- p.id += str.charAt(i);
- if (i === str.length) break;
- }
- p.id = Number(p.id);
- }
-
- // look up json data
- if (str.charAt(++i)) {
- var payload = tryParse(str.substr(i));
- var isPayloadValid = payload !== false && (p.type === exports.ERROR || isArray(payload));
- if (isPayloadValid) {
- p.data = payload;
- } else {
- return error('invalid payload');
- }
- }
-
- debug('decoded %s as %j', str, p);
- return p;
-}
-
-function tryParse(str) {
- try {
- return JSON.parse(str);
- } catch(e){
- return false;
- }
-}
-
-/**
- * Deallocates a parser's resources
- *
- * @api public
- */
-
-Decoder.prototype.destroy = function() {
- if (this.reconstructor) {
- this.reconstructor.finishedReconstruction();
- }
-};
-
-/**
- * A manager of a binary event's 'buffer sequence'. Should
- * be constructed whenever a packet of type BINARY_EVENT is
- * decoded.
- *
- * @param {Object} packet
- * @return {BinaryReconstructor} initialized reconstructor
- * @api private
- */
-
-function BinaryReconstructor(packet) {
- this.reconPack = packet;
- this.buffers = [];
-}
-
-/**
- * Method to be called when binary data received from connection
- * after a BINARY_EVENT packet.
- *
- * @param {Buffer | ArrayBuffer} binData - the raw binary data received
- * @return {null | Object} returns null if more binary data is expected or
- * a reconstructed packet object if all buffers have been received.
- * @api private
- */
-
-BinaryReconstructor.prototype.takeBinaryData = function(binData) {
- this.buffers.push(binData);
- if (this.buffers.length === this.reconPack.attachments) { // done with buffer list
- var packet = binary.reconstructPacket(this.reconPack, this.buffers);
- this.finishedReconstruction();
- return packet;
- }
- return null;
-};
-
-/**
- * Cleans up binary packet reconstruction variables.
- *
- * @api private
- */
-
-BinaryReconstructor.prototype.finishedReconstruction = function() {
- this.reconPack = null;
- this.buffers = [];
-};
-
-function error(msg) {
- return {
- type: exports.ERROR,
- data: 'parser error: ' + msg
- };
-}
-
-
-/***/ }),
-/* 83 */
-/***/ (function(module, exports) {
-
-var toString = {}.toString;
-
-module.exports = Array.isArray || function (arr) {
- return toString.call(arr) == '[object Array]';
-};
-
-
-/***/ }),
-/* 84 */
-/***/ (function(module, exports, __webpack_require__) {
-
-/* WEBPACK VAR INJECTION */(function(global) {// browser shim for xmlhttprequest module
-
-var hasCORS = __webpack_require__(219);
-
-module.exports = function (opts) {
- var xdomain = opts.xdomain;
-
- // scheme must be same when usign XDomainRequest
- // http://blogs.msdn.com/b/ieinternals/archive/2010/05/13/xdomainrequest-restrictions-limitations-and-workarounds.aspx
- var xscheme = opts.xscheme;
-
- // XDomainRequest has a flow of not sending cookie, therefore it should be disabled as a default.
- // https://github.com/Automattic/engine.io-client/pull/217
- var enablesXDR = opts.enablesXDR;
-
- // XMLHttpRequest can be disabled on IE
- try {
- if ('undefined' !== typeof XMLHttpRequest && (!xdomain || hasCORS)) {
- return new XMLHttpRequest();
- }
- } catch (e) { }
-
- // Use XDomainRequest for IE8 if enablesXDR is true
- // because loading bar keeps flashing when using jsonp-polling
- // https://github.com/yujiosaka/socke.io-ie8-loading-example
- try {
- if ('undefined' !== typeof XDomainRequest && !xscheme && enablesXDR) {
- return new XDomainRequest();
- }
- } catch (e) { }
-
- if (!xdomain) {
- try {
- return new global[['Active'].concat('Object').join('X')]('Microsoft.XMLHTTP');
- } catch (e) { }
- }
-};
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(3)))
-
-/***/ }),
-/* 85 */
-/***/ (function(module, exports, __webpack_require__) {
-
-/**
- * Module dependencies.
- */
-
-var parser = __webpack_require__(32);
-var Emitter = __webpack_require__(31);
-
-/**
- * Module exports.
- */
-
-module.exports = Transport;
-
-/**
- * Transport abstract constructor.
- *
- * @param {Object} options.
- * @api private
- */
-
-function Transport (opts) {
- this.path = opts.path;
- this.hostname = opts.hostname;
- this.port = opts.port;
- this.secure = opts.secure;
- this.query = opts.query;
- this.timestampParam = opts.timestampParam;
- this.timestampRequests = opts.timestampRequests;
- this.readyState = '';
- this.agent = opts.agent || false;
- this.socket = opts.socket;
- this.enablesXDR = opts.enablesXDR;
-
- // SSL options for Node.js client
- this.pfx = opts.pfx;
- this.key = opts.key;
- this.passphrase = opts.passphrase;
- this.cert = opts.cert;
- this.ca = opts.ca;
- this.ciphers = opts.ciphers;
- this.rejectUnauthorized = opts.rejectUnauthorized;
- this.forceNode = opts.forceNode;
-
- // other options for Node.js client
- this.extraHeaders = opts.extraHeaders;
- this.localAddress = opts.localAddress;
-}
-
-/**
- * Mix in `Emitter`.
- */
-
-Emitter(Transport.prototype);
-
-/**
- * Emits an error.
- *
- * @param {String} str
- * @return {Transport} for chaining
- * @api public
- */
-
-Transport.prototype.onError = function (msg, desc) {
- var err = new Error(msg);
- err.type = 'TransportError';
- err.description = desc;
- this.emit('error', err);
- return this;
-};
-
-/**
- * Opens the transport.
- *
- * @api public
- */
-
-Transport.prototype.open = function () {
- if ('closed' === this.readyState || '' === this.readyState) {
- this.readyState = 'opening';
- this.doOpen();
- }
-
- return this;
-};
-
-/**
- * Closes the transport.
- *
- * @api private
- */
-
-Transport.prototype.close = function () {
- if ('opening' === this.readyState || 'open' === this.readyState) {
- this.doClose();
- this.onClose();
- }
-
- return this;
-};
-
-/**
- * Sends multiple packets.
- *
- * @param {Array} packets
- * @api private
- */
-
-Transport.prototype.send = function (packets) {
- if ('open' === this.readyState) {
- this.write(packets);
- } else {
- throw new Error('Transport not open');
- }
-};
-
-/**
- * Called upon open
- *
- * @api private
- */
-
-Transport.prototype.onOpen = function () {
- this.readyState = 'open';
- this.writable = true;
- this.emit('open');
-};
-
-/**
- * Called with data.
- *
- * @param {String} data
- * @api private
- */
-
-Transport.prototype.onData = function (data) {
- var packet = parser.decodePacket(data, this.socket.binaryType);
- this.onPacket(packet);
-};
-
-/**
- * Called with a decoded packet.
- */
-
-Transport.prototype.onPacket = function (packet) {
- this.emit('packet', packet);
-};
-
-/**
- * Called upon close.
- *
- * @api private
- */
-
-Transport.prototype.onClose = function () {
- this.readyState = 'closed';
- this.emit('close');
-};
-
-
-/***/ }),
-/* 86 */
-/***/ (function(module, exports, __webpack_require__) {
-
-exports.f = __webpack_require__(7);
-
-
-/***/ }),
-/* 87 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var global = __webpack_require__(6);
-var core = __webpack_require__(5);
-var LIBRARY = __webpack_require__(38);
-var wksExt = __webpack_require__(86);
-var defineProperty = __webpack_require__(19).f;
-module.exports = function (name) {
- var $Symbol = core.Symbol || (core.Symbol = LIBRARY ? {} : global.Symbol || {});
- if (name.charAt(0) != '_' && !(name in $Symbol)) defineProperty($Symbol, name, { value: wksExt.f(name) });
-};
-
-
-/***/ }),
-/* 88 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-
-var commonApi = __webpack_require__(253);
-var objectApi = __webpack_require__(293);
-
-var ecc = Object.assign({}, commonApi, objectApi);
-
-module.exports = ecc;
-
-/***/ }),
-/* 89 */
-/***/ (function(module, exports, __webpack_require__) {
-
-exports = module.exports = __webpack_require__(141);
-exports.Stream = exports;
-exports.Readable = exports;
-exports.Writable = __webpack_require__(90);
-exports.Duplex = __webpack_require__(24);
-exports.Transform = __webpack_require__(145);
-exports.PassThrough = __webpack_require__(269);
-
-
-/***/ }),
-/* 90 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(process, setImmediate, global) {// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-// A bit simpler than readable streams.
-// Implement an async ._write(chunk, encoding, cb), and it'll handle all
-// the drain event emission and buffering.
-
-
-
-/**/
-
-var pna = __webpack_require__(64);
-/**/
-
-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 : pna.nextTick;
-/**/
-
-/**/
-var Duplex;
-/**/
-
-Writable.WritableState = WritableState;
-
-/**/
-var util = __webpack_require__(43);
-util.inherits = __webpack_require__(1);
-/**/
-
-/**/
-var internalUtil = {
- deprecate: __webpack_require__(268)
-};
-/**/
-
-/**/
-var Stream = __webpack_require__(142);
-/**/
-
-/**/
-
-var Buffer = __webpack_require__(0).Buffer;
-var OurUint8Array = global.Uint8Array || function () {};
-function _uint8ArrayToBuffer(chunk) {
- return Buffer.from(chunk);
-}
-function _isUint8Array(obj) {
- return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
-}
-
-/**/
-
-var destroyImpl = __webpack_require__(143);
-
-util.inherits(Writable, Stream);
-
-function nop() {}
-
-function WritableState(options, stream) {
- Duplex = Duplex || __webpack_require__(24);
-
- options = options || {};
-
- // Duplex streams are both readable and writable, but share
- // the same options object.
- // However, some cases require setting options to different
- // values for the readable and the writable sides of the duplex stream.
- // These options can be provided separately as readableXXX and writableXXX.
- var isDuplex = stream instanceof Duplex;
-
- // object stream flag to indicate whether or not this stream
- // contains buffers or objects.
- this.objectMode = !!options.objectMode;
-
- if (isDuplex) 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 writableHwm = options.writableHighWaterMark;
- var defaultHwm = this.objectMode ? 16 : 16 * 1024;
-
- if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = 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;
- if (this !== Writable) return false;
-
- return object && object._writableState instanceof WritableState;
- }
- });
-} else {
- realHasInstance = function (object) {
- return object instanceof this;
- };
-}
-
-function Writable(options) {
- Duplex = Duplex || __webpack_require__(24);
-
- // 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);
- pna.nextTick(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);
- pna.nextTick(cb, er);
- valid = false;
- }
- return valid;
-}
-
-Writable.prototype.write = function (chunk, encoding, cb) {
- var state = this._writableState;
- var ret = false;
- var isBuf = !state.objectMode && _isUint8Array(chunk);
-
- 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;
-}
-
-Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
- // making it explicit this property is not enumerable
- // because otherwise some prototype manipulation in
- // userland will fail
- enumerable: false,
- get: function () {
- return this._writableState.highWaterMark;
- }
-});
-
-// 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
- pna.nextTick(cb, er);
- // this can emit finish, and it will always happen
- // after error
- pna.nextTick(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);
- }
- state.bufferedRequestCount = 0;
- } 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;
- state.bufferedRequestCount--;
- // 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.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;
- pna.nextTick(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) pna.nextTick(cb);else stream.once('finish', cb);
- }
- state.ended = true;
- stream.writable = false;
-}
-
-function onCorkedFinish(corkReq, state, err) {
- var entry = corkReq.entry;
- corkReq.entry = null;
- while (entry) {
- var cb = entry.callback;
- state.pendingcb--;
- cb(err);
- entry = entry.next;
- }
- if (state.corkedRequestsFree) {
- state.corkedRequestsFree.next = corkReq;
- } else {
- state.corkedRequestsFree = corkReq;
- }
-}
-
-Object.defineProperty(Writable.prototype, 'destroyed', {
- get: function () {
- if (this._writableState === undefined) {
- return false;
- }
- return this._writableState.destroyed;
- },
- set: function (value) {
- // we ignore the value if the stream
- // has not been initialized yet
- if (!this._writableState) {
- return;
- }
-
- // backward compatibility, the user is explicitly
- // managing destroyed
- this._writableState.destroyed = value;
- }
-});
-
-Writable.prototype.destroy = destroyImpl.destroy;
-Writable.prototype._undestroy = destroyImpl.undestroy;
-Writable.prototype._destroy = function (err, cb) {
- this.end();
- cb(err);
-};
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(11), __webpack_require__(144).setImmediate, __webpack_require__(3)))
-
-/***/ }),
-/* 91 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-// Copyright Joyent, Inc. and other Node contributors.
-//
-// Permission is hereby granted, free of charge, to any person obtaining a
-// copy of this software and associated documentation files (the
-// "Software"), to deal in the Software without restriction, including
-// without limitation the rights to use, copy, modify, merge, publish,
-// distribute, sublicense, and/or sell copies of the Software, and to permit
-// persons to whom the Software is furnished to do so, subject to the
-// following conditions:
-//
-// The above copyright notice and this permission notice shall be included
-// in all copies or substantial portions of the Software.
-//
-// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
-// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
-// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
-// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
-// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
-// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
-// USE OR OTHER DEALINGS IN THE SOFTWARE.
-
-
-
-/**/
-
-var Buffer = __webpack_require__(0).Buffer;
-/**/
-
-var isEncoding = Buffer.isEncoding || function (encoding) {
- encoding = '' + encoding;
- switch (encoding && encoding.toLowerCase()) {
- case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw':
- return true;
- default:
- return false;
- }
-};
-
-function _normalizeEncoding(enc) {
- if (!enc) return 'utf8';
- var retried;
- while (true) {
- switch (enc) {
- case 'utf8':
- case 'utf-8':
- return 'utf8';
- case 'ucs2':
- case 'ucs-2':
- case 'utf16le':
- case 'utf-16le':
- return 'utf16le';
- case 'latin1':
- case 'binary':
- return 'latin1';
- case 'base64':
- case 'ascii':
- case 'hex':
- return enc;
- default:
- if (retried) return; // undefined
- enc = ('' + enc).toLowerCase();
- retried = true;
- }
- }
-};
-
-// Do not cache `Buffer.isEncoding` when checking encoding names as some
-// modules monkey-patch it to support additional encodings
-function normalizeEncoding(enc) {
- var nenc = _normalizeEncoding(enc);
- if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
- return nenc || enc;
-}
-
-// StringDecoder provides an interface for efficiently splitting a series of
-// buffers into a series of JS strings without breaking apart multi-byte
-// characters.
-exports.StringDecoder = StringDecoder;
-function StringDecoder(encoding) {
- this.encoding = normalizeEncoding(encoding);
- var nb;
- switch (this.encoding) {
- case 'utf16le':
- this.text = utf16Text;
- this.end = utf16End;
- nb = 4;
- break;
- case 'utf8':
- this.fillLast = utf8FillLast;
- nb = 4;
- break;
- case 'base64':
- this.text = base64Text;
- this.end = base64End;
- nb = 3;
- break;
- default:
- this.write = simpleWrite;
- this.end = simpleEnd;
- return;
- }
- this.lastNeed = 0;
- this.lastTotal = 0;
- this.lastChar = Buffer.allocUnsafe(nb);
-}
-
-StringDecoder.prototype.write = function (buf) {
- if (buf.length === 0) return '';
- var r;
- var i;
- if (this.lastNeed) {
- r = this.fillLast(buf);
- if (r === undefined) return '';
- i = this.lastNeed;
- this.lastNeed = 0;
- } else {
- i = 0;
- }
- if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
- return r || '';
-};
-
-StringDecoder.prototype.end = utf8End;
-
-// Returns only complete characters in a Buffer
-StringDecoder.prototype.text = utf8Text;
-
-// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
-StringDecoder.prototype.fillLast = function (buf) {
- if (this.lastNeed <= buf.length) {
- buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
- return this.lastChar.toString(this.encoding, 0, this.lastTotal);
- }
- buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
- this.lastNeed -= buf.length;
-};
-
-// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
-// continuation byte. If an invalid byte is detected, -2 is returned.
-function utf8CheckByte(byte) {
- if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4;
- return byte >> 6 === 0x02 ? -1 : -2;
-}
-
-// Checks at most 3 bytes at the end of a Buffer in order to detect an
-// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
-// needed to complete the UTF-8 character (if applicable) are returned.
-function utf8CheckIncomplete(self, buf, i) {
- var j = buf.length - 1;
- if (j < i) return 0;
- var nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) self.lastNeed = nb - 1;
- return nb;
- }
- if (--j < i || nb === -2) return 0;
- nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) self.lastNeed = nb - 2;
- return nb;
- }
- if (--j < i || nb === -2) return 0;
- nb = utf8CheckByte(buf[j]);
- if (nb >= 0) {
- if (nb > 0) {
- if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
- }
- return nb;
- }
- return 0;
-}
-
-// Validates as many continuation bytes for a multi-byte UTF-8 character as
-// needed or are available. If we see a non-continuation byte where we expect
-// one, we "replace" the validated continuation bytes we've seen so far with
-// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
-// behavior. The continuation byte check is included three times in the case
-// where all of the continuation bytes for a character exist in the same buffer.
-// It is also done this way as a slight performance increase instead of using a
-// loop.
-function utf8CheckExtraBytes(self, buf, p) {
- if ((buf[0] & 0xC0) !== 0x80) {
- self.lastNeed = 0;
- return '\ufffd';
- }
- if (self.lastNeed > 1 && buf.length > 1) {
- if ((buf[1] & 0xC0) !== 0x80) {
- self.lastNeed = 1;
- return '\ufffd';
- }
- if (self.lastNeed > 2 && buf.length > 2) {
- if ((buf[2] & 0xC0) !== 0x80) {
- self.lastNeed = 2;
- return '\ufffd';
- }
- }
- }
-}
-
-// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
-function utf8FillLast(buf) {
- var p = this.lastTotal - this.lastNeed;
- var r = utf8CheckExtraBytes(this, buf, p);
- if (r !== undefined) return r;
- if (this.lastNeed <= buf.length) {
- buf.copy(this.lastChar, p, 0, this.lastNeed);
- return this.lastChar.toString(this.encoding, 0, this.lastTotal);
- }
- buf.copy(this.lastChar, p, 0, buf.length);
- this.lastNeed -= buf.length;
-}
-
-// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
-// partial character, the character's bytes are buffered until the required
-// number of bytes are available.
-function utf8Text(buf, i) {
- var total = utf8CheckIncomplete(this, buf, i);
- if (!this.lastNeed) return buf.toString('utf8', i);
- this.lastTotal = total;
- var end = buf.length - (total - this.lastNeed);
- buf.copy(this.lastChar, 0, end);
- return buf.toString('utf8', i, end);
-}
-
-// For UTF-8, a replacement character is added when ending on a partial
-// character.
-function utf8End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) return r + '\ufffd';
- return r;
-}
-
-// UTF-16LE typically needs two bytes per character, but even if we have an even
-// number of bytes available, we need to check if we end on a leading/high
-// surrogate. In that case, we need to wait for the next two bytes in order to
-// decode the last character properly.
-function utf16Text(buf, i) {
- if ((buf.length - i) % 2 === 0) {
- var r = buf.toString('utf16le', i);
- if (r) {
- var c = r.charCodeAt(r.length - 1);
- if (c >= 0xD800 && c <= 0xDBFF) {
- this.lastNeed = 2;
- this.lastTotal = 4;
- this.lastChar[0] = buf[buf.length - 2];
- this.lastChar[1] = buf[buf.length - 1];
- return r.slice(0, -1);
- }
- }
- return r;
- }
- this.lastNeed = 1;
- this.lastTotal = 2;
- this.lastChar[0] = buf[buf.length - 1];
- return buf.toString('utf16le', i, buf.length - 1);
-}
-
-// For UTF-16LE we do not explicitly append special replacement characters if we
-// end on a partial character, we simply let v8 handle that.
-function utf16End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) {
- var end = this.lastTotal - this.lastNeed;
- return r + this.lastChar.toString('utf16le', 0, end);
- }
- return r;
-}
-
-function base64Text(buf, i) {
- var n = (buf.length - i) % 3;
- if (n === 0) return buf.toString('base64', i);
- this.lastNeed = 3 - n;
- this.lastTotal = 3;
- if (n === 1) {
- this.lastChar[0] = buf[buf.length - 1];
- } else {
- this.lastChar[0] = buf[buf.length - 2];
- this.lastChar[1] = buf[buf.length - 1];
- }
- return buf.toString('base64', i, buf.length - n);
-}
-
-function base64End(buf) {
- var r = buf && buf.length ? this.write(buf) : '';
- if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
- return r;
-}
-
-// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
-function simpleWrite(buf) {
- return buf.toString(this.encoding);
-}
-
-function simpleEnd(buf) {
- return buf && buf.length ? this.write(buf) : '';
-}
-
-/***/ }),
-/* 92 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(Buffer) {
-var inherits = __webpack_require__(1)
-var HashBase = __webpack_require__(148)
-
-var ARRAY16 = new Array(16)
-
-function MD5 () {
- HashBase.call(this, 64)
-
- // state
- this._a = 0x67452301
- this._b = 0xefcdab89
- this._c = 0x98badcfe
- this._d = 0x10325476
-}
-
-inherits(MD5, HashBase)
-
-MD5.prototype._update = function () {
- var M = ARRAY16
- for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
-
- var a = this._a
- var b = this._b
- var c = this._c
- var d = this._d
-
- a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
- d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
- c = fnF(c, d, a, b, M[2], 0x242070db, 17)
- b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
- a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
- d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
- c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
- b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
- a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
- d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
- c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
- b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
- a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
- d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
- c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
- b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
-
- a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
- d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
- c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
- b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
- a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
- d = fnG(d, a, b, c, M[10], 0x02441453, 9)
- c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
- b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
- a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
- d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
- c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
- b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
- a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
- d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
- c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
- b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
-
- a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
- d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
- c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
- b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
- a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
- d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
- c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
- b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
- a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
- d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
- c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
- b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
- a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
- d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
- c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
- b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
-
- a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
- d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
- c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
- b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
- a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
- d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
- c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
- b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
- a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
- d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
- c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
- b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
- a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
- d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
- c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
- b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
-
- this._a = (this._a + a) | 0
- this._b = (this._b + b) | 0
- this._c = (this._c + c) | 0
- this._d = (this._d + d) | 0
-}
-
-MD5.prototype._digest = function () {
- // create padding and handle blocks
- this._block[this._blockOffset++] = 0x80
- if (this._blockOffset > 56) {
- this._block.fill(0, this._blockOffset, 64)
- this._update()
- this._blockOffset = 0
- }
-
- this._block.fill(0, this._blockOffset, 56)
- this._block.writeUInt32LE(this._length[0], 56)
- this._block.writeUInt32LE(this._length[1], 60)
- this._update()
-
- // produce result
- var buffer = new Buffer(16)
- buffer.writeInt32LE(this._a, 0)
- buffer.writeInt32LE(this._b, 4)
- buffer.writeInt32LE(this._c, 8)
- buffer.writeInt32LE(this._d, 12)
- return buffer
-}
-
-function rotl (x, n) {
- return (x << n) | (x >>> (32 - n))
-}
-
-function fnF (a, b, c, d, m, k, s) {
- return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
-}
-
-function fnG (a, b, c, d, m, k, s) {
- return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
-}
-
-function fnH (a, b, c, d, m, k, s) {
- return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
-}
-
-function fnI (a, b, c, d, m, k, s) {
- return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
-}
-
-module.exports = MD5
-
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
-
-/***/ }),
-/* 93 */
-/***/ (function(module, exports, __webpack_require__) {
-
-var Point = __webpack_require__(149)
-var Curve = __webpack_require__(151)
-
-var getCurveByName = __webpack_require__(279)
-
-module.exports = {
- Curve: Curve,
- Point: Point,
- getCurveByName: getCurveByName
-}
-
-
-/***/ }),
-/* 94 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(Buffer) {
-
-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 Types = __webpack_require__(294);
-var Fcbuffer = __webpack_require__(297);
-var assert = __webpack_require__(4);
-
-var create = Fcbuffer.create;
-
-/**
- @typedef {object} SerializerConfig
- @property {boolean} [SerializerConfig.defaults = false] - Insert in defaults (like 0, false, '000...', or '') for any missing values. This helps test and inspect what a definition should look like. Do not enable in production.
- @property {boolean} [SerializerConfig.debug = false] - Prints lots of HEX and field-level information to help debug binary serialization.
- @property {object} [customTypes] - Add or overwrite low level types (see ./src/types.js `const types = {...}`).
-*/
-
-/**
- @typedef {object} CreateStruct
- @property {Array} CreateStruct.errors - If any errors exists, no struts will be created.
- @property {Object} CreateStruct.struct - Struct objects keyed by definition name.
- @property {String} CreateStruct.struct.structName - Struct object that will serialize this type.
- @property {Struct} CreateStruct.struct.struct - Struct object that will serialize this type (see ./src/struct.js).
-*/
-
-/**
- @arg {object} definitions - examples https://github.com/EOSIO/eosjs-json/blob/master/schema
- @arg {SerializerConfig} config
- @return {CreateStruct}
-*/
-
-module.exports = function (definitions) {
- var config = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
-
- if ((typeof definitions === 'undefined' ? 'undefined' : _typeof(definitions)) !== 'object') {
- throw new TypeError('definitions is a required parameter');
- }
-
- if (config.customTypes) {
- definitions = Object.assign({}, definitions); //clone
- for (var key in config.customTypes) {
- // custom types overwrite definitions
- delete definitions[key];
- }
- }
-
- var types = Types(config);
-
- var _create = create(definitions, types),
- errors = _create.errors,
- structs = _create.structs;
-
- /** Extend with more JSON schema and type definitions */
-
-
- var _extend = function _extend(parent, child) {
- var combined = Object.assign({}, parent, child);
-
- var _create2 = create(combined, types),
- structs = _create2.structs,
- errors = _create2.errors;
-
- return {
- errors: errors,
- structs: structs,
- extend: function extend(child) {
- return _extend(combined, child);
- },
- fromBuffer: fromBuffer(types, structs),
- toBuffer: toBuffer(types, structs)
- };
- };
-
- return {
- errors: errors,
- structs: structs,
- types: types,
- extend: function extend(child) {
- return _extend(definitions, child);
- },
-
- /**
- @arg {string} typeName lookup struct or type by name
- @arg {Buffer} buf serialized data to be parsed
- @return {object} deserialized object
- */
- fromBuffer: fromBuffer(types, structs),
-
- /**
- @arg {string} typeName lookup struct or type by name
- @arg {Object} object for serialization
- @return {Buffer} serialized object
- */
- toBuffer: toBuffer(types, structs)
- };
-};
-
-var fromBuffer = function fromBuffer(types, structs) {
- return function (typeName, buf) {
- assert.equal(typeof typeName === 'undefined' ? 'undefined' : _typeof(typeName), 'string', 'typeName (type or struct name)');
- if (typeof buf === 'string') {
- buf = Buffer.from(buf, 'hex');
- }
- assert(Buffer.isBuffer(buf), 'expecting buf');
-
- var type = types[typeName];
- if (type) {
- type = type();
- } else {
- type = structs[typeName];
- }
- assert(type, 'missing type or struct: ' + typeName);
- return Fcbuffer.fromBuffer(type, buf);
- };
-};
-
-var toBuffer = function toBuffer(types, structs) {
- return function (typeName, object) {
- assert.equal(typeof typeName === 'undefined' ? 'undefined' : _typeof(typeName), 'string', 'typeName (type or struct name)');
- assert.equal(typeof object === 'undefined' ? 'undefined' : _typeof(object), 'object', 'object');
-
- var type = types[typeName];
- if (type) {
- type = type();
- } else {
- type = structs[typeName];
- }
- assert(type, 'missing type or struct: ' + typeName);
- return Fcbuffer.toBuffer(type, object);
- };
-};
-
-module.exports.fromBuffer = Fcbuffer.fromBuffer;
-module.exports.toBuffer = Fcbuffer.toBuffer;
-/* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(2).Buffer))
-
-/***/ }),
-/* 95 */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-/* WEBPACK VAR INJECTION */(function(Buffer) {
-
-var _slicedToArray2 = __webpack_require__(96);
-
-var _slicedToArray3 = _interopRequireDefault(_slicedToArray2);
-
-var _typeof2 = __webpack_require__(41);
-
-var _typeof3 = _interopRequireDefault(_typeof2);
-
-function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
-
-var _require = __webpack_require__(88),
- Signature = _require.Signature,
- PublicKey = _require.PublicKey;
-
-var Fcbuffer = __webpack_require__(94);
-var ByteBuffer = __webpack_require__(33);
-var assert = __webpack_require__(4);
-
-var json = { schema: __webpack_require__(161) };
-
-var _require2 = __webpack_require__(162),
- isName = _require2.isName,
- encodeName = _require2.encodeName,
- decodeName = _require2.decodeName,
- DecimalPad = _require2.DecimalPad,
- DecimalImply = _require2.DecimalImply,
- DecimalUnimply = _require2.DecimalUnimply,
- printAsset = _require2.printAsset,
- parseAsset = _require2.parseAsset;
-
-/** Configures Fcbuffer for EOS specific structs and types. */
-
-
-module.exports = function () {
- var config = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
- var extendedSchema = arguments[1];
-
- var structLookup = function structLookup(lookupName, account) {
- var cachedCode = new Set(['eosio', 'eosio.token', 'eosio.null']);
- if (cachedCode.has(account)) {
- return structs[lookupName];
- }
- var abi = config.abiCache.abi(account);
- var struct = abi.structs[lookupName];
- if (struct != null) {
- return struct;
- }
- // TODO: move up (before `const struct = abi.structs[lookupName]`)
- var _iteratorNormalCompletion = true;
- var _didIteratorError = false;
- var _iteratorError = undefined;
-
- try {
- for (var _iterator = abi.abi.actions[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
- var action = _step.value;
- var name = action.name,
- type = action.type;
-
- if (name === lookupName) {
- var _struct = abi.structs[type];
- if (_struct != null) {
- return _struct;
- }
- }
- }
- } catch (err) {
- _didIteratorError = true;
- _iteratorError = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion && _iterator.return) {
- _iterator.return();
- }
- } finally {
- if (_didIteratorError) {
- throw _iteratorError;
- }
- }
- }
-
- throw new Error('Missing ABI struct or action: ' + lookupName);
- };
-
- // If nodeos does not have an ABI setup for a certain action.type, it will throw
- // an error: `Invalid cast from object_type to string` .. forceActionDataHex
- // may be used to until native ABI is added or fixed.
- var forceActionDataHex = config.forceActionDataHex != null ? config.forceActionDataHex : true;
-
- var override = Object.assign({}, authorityOverride, abiOverride(structLookup), wasmCodeOverride(config), actionDataOverride(structLookup, forceActionDataHex), config.override);
-
- var eosTypes = {
- name: function name() {
- return [Name];
- },
- public_key: function public_key() {
- return [variant(PublicKeyEcc)];
- },
-
- symbol: function symbol() {
- return [_Symbol];
- },
- symbol_code: function symbol_code() {
- return [SymbolCode];
- },
- extended_symbol: function extended_symbol() {
- return [ExtendedSymbol];
- },
-
- asset: function asset() {
- return [Asset];
- }, // After Symbol: amount, precision, symbol, contract
- extended_asset: function extended_asset() {
- return [ExtendedAsset];
- }, // After Asset: amount, precision, symbol, contract
-
- signature: function signature() {
- return [variant(SignatureType)];
- }
- };
-
- var customTypes = Object.assign({}, eosTypes, config.customTypes);
- config = Object.assign({ override: override }, { customTypes: customTypes }, config);
-
- // Do not sort transaction actions
- config.sort = Object.assign({}, config.sort);
- config.sort['action.authorization'] = true;
- config.sort['signed_transaction.signature'] = true;
- config.sort['authority.accounts'] = true;
- config.sort['authority.keys'] = true;
-
- var schema = Object.assign({}, json.schema, extendedSchema);
-
- var _Fcbuffer = Fcbuffer(schema, config),
- structs = _Fcbuffer.structs,
- types = _Fcbuffer.types,
- errors = _Fcbuffer.errors,
- fromBuffer = _Fcbuffer.fromBuffer,
- toBuffer = _Fcbuffer.toBuffer;
-
- if (errors.length !== 0) {
- throw new Error(JSON.stringify(errors, null, 4));
- }
-
- return { structs: structs, types: types, fromBuffer: fromBuffer, toBuffer: toBuffer };
-};
-
-/**
- Name eos::types native.hpp
-*/
-var Name = function Name(validation) {
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- var n = decodeName(b.readUint64(), false); // b is already in littleEndian
- // if(validation.debug) {
- // console.error(`${n}`, '(Name.fromByteBuffer)')
- // }
- return n;
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- // if(validation.debug) {
- // console.error(`${value}`, (Name.appendByteBuffer))
- // }
- b.writeUint64(encodeName(value, false)); // b is already in littleEndian
- },
- fromObject: function fromObject(value) {
- return value;
- },
- toObject: function toObject(value) {
- if (validation.defaults && value == null) {
- return '';
- }
- return value;
- }
- };
-};
-
-/**
- A variant is like having a version of an object. A varint comes
- first and identifies which type of object this is.
-
- @arg {Array} variantArray array of types
-*/
-var variant = function variant() {
- for (var _len = arguments.length, variantArray = Array(_len), _key = 0; _key < _len; _key++) {
- variantArray[_key] = arguments[_key];
- }
-
- return function (validation, baseTypes, customTypes) {
- var variants = variantArray.map(function (Type) {
- return Type(validation, baseTypes, customTypes);
- });
- var staticVariant = baseTypes.static_variant(variants);
-
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- return staticVariant.fromByteBuffer(b);
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- if (!Array.isArray(value)) {
- value = [0, value];
- }
- staticVariant.appendByteBuffer(b, value);
- },
- fromObject: function fromObject(value) {
- if (!Array.isArray(value)) {
- value = [0, value];
- }
- return staticVariant.fromObject(value)[1];
- },
- toObject: function toObject(value) {
- if (!Array.isArray(value)) {
- value = [0, value];
- }
- return staticVariant.toObject(value)[1];
- }
- };
- };
-};
-
-var PublicKeyEcc = function PublicKeyEcc(validation) {
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- var bcopy = b.copy(b.offset, b.offset + 33);
- b.skip(33);
- var pubbuf = Buffer.from(bcopy.toBinary(), 'binary');
- return PublicKey.fromBuffer(pubbuf).toString();
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- // if(validation.debug) {
- // console.error(`${value}`, 'PublicKeyType.appendByteBuffer')
- // }
- var buf = PublicKey.fromStringOrThrow(value).toBuffer();
- b.append(buf.toString('binary'), 'binary');
- },
- fromObject: function fromObject(value) {
- return value;
- },
- toObject: function toObject(value) {
- if (validation.defaults && value == null) {
- return 'EOS6MRy..';
- }
- return value;
- }
- };
-};
-
-/**
- Internal: precision, symbol
- External: symbol
- @example 'SYS'
-*/
-var _Symbol = function _Symbol(validation) {
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- var bcopy = b.copy(b.offset, b.offset + 8);
- b.skip(8);
-
- var precision = bcopy.readUint8();
- var bin = bcopy.toBinary();
-
- var symbol = '';
- var _iteratorNormalCompletion2 = true;
- var _didIteratorError2 = false;
- var _iteratorError2 = undefined;
-
- try {
- for (var _iterator2 = bin[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
- var code = _step2.value;
-
- if (code == '\0') {
- break;
- }
- symbol += code;
- }
- } catch (err) {
- _didIteratorError2 = true;
- _iteratorError2 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion2 && _iterator2.return) {
- _iterator2.return();
- }
- } finally {
- if (_didIteratorError2) {
- throw _iteratorError2;
- }
- }
- }
-
- return precision + ',' + symbol;
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- var _parseAsset = parseAsset(value),
- symbol = _parseAsset.symbol,
- precision = _parseAsset.precision;
-
- assert(precision != null, 'Precision unknown for symbol: ' + value);
- var pad = '\0'.repeat(7 - symbol.length);
- b.append(String.fromCharCode(precision) + symbol + pad);
- },
- fromObject: function fromObject(value) {
- assert(value != null, 'Symbol is required: ' + value);
-
- var _parseAsset2 = parseAsset(value),
- symbol = _parseAsset2.symbol,
- precision = _parseAsset2.precision;
-
- if (precision == null) {
- return symbol;
- } else {
- // Internal object, this can have the precision prefix
- return precision + ',' + symbol;
- }
- },
- toObject: function toObject(value) {
- if (validation.defaults && value == null) {
- return 'SYS';
- }
- // symbol only (without precision prefix)
- return parseAsset(value).symbol;
- }
- };
-};
-
-/** Symbol type without the precision */
-var SymbolCode = function SymbolCode(validation) {
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- var bcopy = b.copy(b.offset, b.offset + 8);
- b.skip(8);
-
- var bin = bcopy.toBinary();
-
- var symbol = '';
- var _iteratorNormalCompletion3 = true;
- var _didIteratorError3 = false;
- var _iteratorError3 = undefined;
-
- try {
- for (var _iterator3 = bin[Symbol.iterator](), _step3; !(_iteratorNormalCompletion3 = (_step3 = _iterator3.next()).done); _iteratorNormalCompletion3 = true) {
- var code = _step3.value;
-
- if (code == '\0') {
- break;
- }
- symbol += code;
- }
- } catch (err) {
- _didIteratorError3 = true;
- _iteratorError3 = err;
- } finally {
- try {
- if (!_iteratorNormalCompletion3 && _iterator3.return) {
- _iterator3.return();
- }
- } finally {
- if (_didIteratorError3) {
- throw _iteratorError3;
- }
- }
- }
-
- return '' + symbol;
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- var _parseAsset3 = parseAsset(value),
- symbol = _parseAsset3.symbol;
-
- var pad = '\0'.repeat(8 - symbol.length);
- b.append(symbol + pad);
- },
- fromObject: function fromObject(value) {
- assert(value != null, 'Symbol is required: ' + value);
-
- var _parseAsset4 = parseAsset(value),
- symbol = _parseAsset4.symbol;
-
- return symbol;
- },
- toObject: function toObject(value) {
- if (validation.defaults && value == null) {
- return 'SYS';
- }
- return parseAsset(value).symbol;
- }
- };
-};
-
-/**
- Internal: precision, symbol, contract
- External: symbol, contract
- @example 'SYS@contract'
-*/
-var ExtendedSymbol = function ExtendedSymbol(validation, baseTypes, customTypes) {
- var symbolType = customTypes.symbol(validation);
- var contractName = customTypes.name(validation);
-
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- var symbol = symbolType.fromByteBuffer(b);
- var contract = contractName.fromByteBuffer(b);
- return symbol + '@' + contract;
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- assert.equal(typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value), 'string', 'Invalid extended symbol: ' + value);
-
- var _value$split = value.split('@'),
- _value$split2 = (0, _slicedToArray3.default)(_value$split, 2),
- symbol = _value$split2[0],
- contract = _value$split2[1];
-
- assert(contract != null, 'Missing @contract suffix in extended symbol: ' + value);
-
- symbolType.appendByteBuffer(b, symbol);
- contractName.appendByteBuffer(b, contract);
- },
- fromObject: function fromObject(value) {
- return value;
- },
- toObject: function toObject(value) {
- if (validation.defaults && value == null) {
- return 'SYS@contract';
- }
- return value;
- }
- };
-};
-
-/**
- Internal: amount, precision, symbol, contract
- @example '1.0000 SYS'
-*/
-var Asset = function Asset(validation, baseTypes, customTypes) {
- var amountType = baseTypes.int64(validation);
- var symbolType = customTypes.symbol(validation);
-
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- var amount = amountType.fromByteBuffer(b);
- assert(amount != null, 'amount');
-
- var sym = symbolType.fromByteBuffer(b);
-
- var _parseAsset5 = parseAsset('' + sym),
- precision = _parseAsset5.precision,
- symbol = _parseAsset5.symbol;
-
- assert(precision != null, 'precision');
- assert(symbol != null, 'symbol');
-
- return DecimalUnimply(amount, precision) + ' ' + symbol;
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- var _parseAsset6 = parseAsset(value),
- amount = _parseAsset6.amount,
- precision = _parseAsset6.precision,
- symbol = _parseAsset6.symbol;
-
- assert(amount != null, 'amount');
- assert(precision != null, 'precision');
- assert(symbol != null, 'symbol');
-
- amountType.appendByteBuffer(b, DecimalImply(amount, precision));
- symbolType.appendByteBuffer(b, precision + ',' + symbol);
- },
- fromObject: function fromObject(value) {
- var _parseAsset7 = parseAsset(value),
- amount = _parseAsset7.amount,
- precision = _parseAsset7.precision,
- symbol = _parseAsset7.symbol;
-
- assert(amount != null, 'amount');
- assert(precision != null, 'precision');
- assert(symbol != null, 'symbol');
-
- return DecimalPad(amount, precision) + ' ' + symbol;
- },
- toObject: function toObject(value) {
- if (validation.defaults && value == null) {
- return '0.0001 SYS';
- }
-
- var _parseAsset8 = parseAsset(value),
- amount = _parseAsset8.amount,
- precision = _parseAsset8.precision,
- symbol = _parseAsset8.symbol;
-
- assert(amount != null, 'amount');
- assert(precision != null, 'precision');
- assert(symbol != null, 'symbol');
-
- return DecimalPad(amount, precision) + ' ' + symbol;
- }
- };
-};
-
-/**
- @example '1.0000 SYS@contract'
-*/
-var ExtendedAsset = function ExtendedAsset(validation, baseTypes, customTypes) {
- var assetType = customTypes.asset(validation);
- var contractName = customTypes.name(validation);
-
- return {
- fromByteBuffer: function fromByteBuffer(b) {
- var asset = assetType.fromByteBuffer(b);
- var contract = contractName.fromByteBuffer(b);
- return parseAsset(asset + '@' + contract);
- },
- appendByteBuffer: function appendByteBuffer(b, value) {
- assert.equal(typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value), 'object', 'expecting extended_asset object, got ' + (typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)));
-
- var asset = printAsset(value);
-
- var _asset$split = asset.split('@'),
- _asset$split2 = (0, _slicedToArray3.default)(_asset$split, 2),
- contract = _asset$split2[1];
-
- assert.equal(typeof contract === 'undefined' ? 'undefined' : (0, _typeof3.default)(contract), 'string', 'Invalid extended asset: ' + value);
-
- // asset includes contract (assetType needs this)
- assetType.appendByteBuffer(b, asset);
- contractName.appendByteBuffer(b, contract);
- },
- fromObject: function fromObject(value) {
- // like: 1.0000 SYS@contract or 1 SYS@contract
- var asset = {};
- if (typeof value === 'string') {
- Object.assign(asset, parseAsset(value));
- } else if ((typeof value === 'undefined' ? 'undefined' : (0, _typeof3.default)(value)) === 'object') {
- Object.assign(asset, value);
- } else {
- assert(false, 'expecting extended_asset